Check the select and as
{@inheritDoc}
@see \XBRL\Formulas\Resources\Resource::validate()
@param VariableSet $variableSet
@param XmlNamespaceManager $nsMgr
555548
public function validate( $variableSet, $nsMgr )
	{
		try
		{
			if ( $this->scheme )
			{
				if ( ! $this->schemaXPath2Expression )
				{
					$this->schemaXPath2Expression = XPath2Expression::Compile( $this->scheme, $nsMgr );
				}
			}
		}
		catch ( \Exception $ex )
		{
			\XBRL_Log::getInstance()->formula_validation( "Specific identifier filter", "Failed to compile scheme expression",
				array(
					'schema expression' => $this->scheme,
					'error' => $ex instanceof XPath2Exception ? $ex->ErrorCode : get_class( $ex ),
					'reason' => $ex->getMessage()
				)
			);
			return false;
		}

		try
		{
			if ( $this->value )
			{
				if ( ! $this->valueXPath2Expression )
				{
					$this->valueXPath2Expression = XPath2Expression::Compile( $this->value, $nsMgr );
				}
			}
		}
		catch ( \Exception $ex )
		{
			\XBRL_Log::getInstance()->formula_validation( "Specific identifier filter", "Failed to compile scheme expression",
				array(
					'schema expression' => $this->scheme,
					'error' => $ex instanceof XPath2Exception ? $ex->ErrorCode : get_class( $ex ),
					'reason' => $ex->getMessage()
				)
			);
			return false;
		}

		return true;
	}
1172915
private function checkResult($result, $vars = []) {
        if (!$result) {
            $this->isValidate = false;
            $vars[ 'attribute' ] = $this->as_name;
            $vars[ '1' ] = $this->p1;
            $vars[ '2' ] = $this->p2;
            $vars[ 'rule' ] = $this->rule;
            if ($this->msg_check) {
                $msg = Lang::get('validate', $this->msg_check, $vars);
                if (!$msg) {
                    $msg = $this->msg_check;
                }
            } else {
                $msg = Lang::get('validate', $this->check_role, $vars);
            }
            if ($this->is_throw) {
                throw new ValidateException($msg, 100010, null);
            } else {
                $this->msg = $msg;
            }
        }
        $this->p1 = null;
        $this->p2 = null;
        $this->rule = null;
    }
826585
public function toQuery( $variableSet, $factVariableBinding )
	{
		$clauses = array();

		// Include the qnames if being called as part of a boolean filter or there are qname expressions
		if ( $this->inBoolean || $this->qnameExpressions )
		foreach ( $this->qnames as $clark )
		{
			$qname = qname( $clark );
			$clauses[] = "(fn:node-name(.) eq fn:QName('{$qname->namespaceURI}','{$qname->localName}'))";
		}

		foreach ( $this->qnameExpressions as $qnameExpression )
		{
			$clauses[] = "(fn:node-name(.) eq $qnameExpression)";
		}

		if ( ! $clauses )
		{
			return null;
		}

		$query = implode( " or ", $clauses );
		return count( $clauses ) > 1 ? "($query)" : $query;
	}
582382
public function isValidAttributeNS($namespace_uri, $local_name)
    {
        if (!$this->isHandledNamespace($namespace_uri)) return false;

        $attrs = $this->namespaces_by_uri[$namespace_uri]->getAttributes();
        return isset($attrs[$local_name]);
    }
1204220
private function evaluate( $variableSet )
	{
		if ( ! $this->canEvaluate ) return;
		if ( isset( $variableSet->evaluated ) ) return true;

		// Process the variables in hierarchy order
		// $variableSet->parameters =& $this->parameterQnames;
		$variableSet->nsMgr = $this->nsMgr;
		$variableSet->xbrlInstance = $this->instances[ $this->instanceQName->clarkNotation() ];
		if ( $variableSet->evaluate() )
		{
			// If the variable set is a formula then add a facts container
			if ( $variableSet instanceof Formula )
			{
				if ( is_null( $this->formulaFactsContainer ) ) $this->formulaFactsContainer = new GeneratedFacts();
				$variableSet->factsContainer = $this->formulaFactsContainer;
			}

			$variableSet->ProcessEvaluationResult( $this->log );

			// If the variable set is a formula recover the facts container
			if ( $variableSet instanceof Formula )
			{
				// This is probably redundant because the container instance will be passed to the variable set by reference
				$this->formulaFactsContainer = $variableSet->factsContainer;
			}
		}

		$variableSet->evaluated = true;

		return true;
	}
550206
private function checkNamespaceResources(array $namespaceResources): bool
    {
        $isValid = true;
        foreach ($namespaceResources as $namespace => $resources) {
            $isValid = $isValid === true &&
                empty($namespace) === false &&
                is_array($resources) === true && $this->checkResources($resources);
        }

        return $isValid;
    }
1046966
public function toQuery( $variableSet, $factVariableBinding )
	{
		$variable = new QName( $this->variable['originalPrefix'], $this->variable['namespace'], $this->variable['name'] );

		// Look for this variable among the bindings.  If it exists
		// and has a fallback value the the query is just false()
		if ( isset( $variableSet->factVariableBindings[ $variable->clarkNotation() ] ) )
		{
			/**
			 * @var FactVariableBinding $binding
			 */
			$binding = $variableSet->factVariableBindings[ $variable->clarkNotation() ];
			if ( $binding->isFallback )
			{
				return "false()";
			}
		}
		else // BMS 201803-07 What else could it be? if ( isset( $variableSet->generalVariableBindings[ $variable->clarkNotation() ] ) )
		{
			return "false()";
		}

		$this->allowAspectsCovered = true;
		$result = parent::toQuery( $variableSet, $factVariableBinding );
		// Once the filter has been created the class should return the filters applied
		// $this->allowAspectsCovered = false;

		return $result;
	}
101398
public function toQuery( $variableSet, $factVariableBinding )
	{
		// return "(true())";

		$clauses = array();

		$dimensionClause = "";
		if ( $this->dimension )
		{
			// $qname = qname( $this->dimension );
			$dimensionClause = "fn:QName('{$this->dimension['namespace']}','{$this->dimension['name']}')";
		}
		else if ( $this->dimensionExpression )
		{
			$dimensionClause = $this->dimensionExpression;
		}
		else
		{
			return "false()";
		}

		if ( $this->test )
		{
			return "( xfi:fact-has-typed-dimension(.,$dimensionClause) and xfi:fact-typed-dimension-value(.,$dimensionClause)[{$this->test}] )";
		}
		else
		{
			return "xfi:fact-has-typed-dimension(.,$dimensionClause)";
		}
	}
636201
public function toQuery( $variableSet, $factVariableBinding )
	{
		$test = $this->test ? $this->test : 'true()';
		// $filter = "(if (fn:QName('http://www.xbrl.org/2003/instance','tuple') = xfi:concept-substitutions(fn:node-name(.))) then (false()) else (xfi:period(.)[$test]))";
		$filter = "(xfi:period(.)[$test])";
		return $filter;
	}
1298705
private function validatePreconditions( $taxonomy, $variableSet )
	{
		$preconditionArcs = $taxonomy->getGenericArc( XBRL_Constants::$arcRoleVariableSetPrecondition, $variableSet->extendedLinkRoleUri, $variableSet->label, $variableSet->path, null, $variableSet->linkbase );
		if ( $preconditionArcs )
		{
			$element = "precondition";
			$preconditionClassName = '\\XBRL\\Formulas\\Resources\\' .
				Formulas::$formulaElements[ $element ]['part'] .
				( isset( Formulas::$formulaElements[ $element ]['className'] )
					? Formulas::$formulaElements[ $element ]['className']
					: ucfirst( $element )
				);

			$preconditionResources = array();
			// BMS 2018-06-29 Modified this loop to put the arcs on the outside so it can take advantage of the indexes on the resources collection
			// $taxonomy->getGenericResource( 'variable', $element, function( $roleUri, $linkbase, $variableSetName, $index, $resource ) use( $preconditionArcs, &$preconditionResources )
			// {
			// 	foreach ( $preconditionArcs as $preconditionArc )
			// 	{
			// 		if ( $roleUri == $preconditionArc['toRoleUri'] )
			// 		if ( $variableSetName == $preconditionArc['label'] )
			// 		{
			// 			$resource['linkbase'] = $linkbase;
			// 			$resource['linkRoleUri'] = $roleUri;
			// 			$preconditionResources[] = $resource;
			// 		}
			// 	}
			// 	return true;
			// } );

			foreach ( $preconditionArcs as $preconditionArc )
			{
				if ( $variableSet->path != $preconditionArc['frompath'] ) continue;
				$taxonomy->getGenericResource( 'variable', $element, function( $roleUri, $linkbase, $variableSetName, $index, $resource ) use( $preconditionArc, &$preconditionResources )
				{
					// This test is probably redundant because I believe $variableSetName is the same as $variableSetArc['label']
					// if ( $variableSetName == $preconditionArc['label'] )
					if ( $resource['path'] == $preconditionArc['topath'] /* || $linkbase == $preconditionArc['linkbase'] */ )
					{
						$resource['linkbase'] = $linkbase;
						$resource['linkRoleUri'] = $roleUri;
						$preconditionResources[] = $resource;
					}

					return true;
				}, $preconditionArc['toRoleUri'], $preconditionArc['to'], $preconditionArc['tolinkbase'] );
			}

			if ( ! $preconditionResources )
			{
				$this->log->formula_validation( "Precondition", "The source precondition for formula resource cannot be located",
					array(
						'formula' => $variableSet->label,
					)
				);

				return false;
			}

			foreach ( $preconditionResources as $preconditionResource )
			{
				/** @var Precondition $precondition */
				$precondition = $preconditionClassName::fromArray( $preconditionResource );
				$precondition->extendedLinkRoleUri = $preconditionResource['linkRoleUri'];
				if ( ! $precondition->validate( $variableSet, $this->nsMgr ) )
				{
					return false;
				}

				$variableSet->preconditions[ "{$precondition->extendedLinkRoleUri}#{$precondition->label}" ] = $precondition;
			}
		}

		return true;
	}
1285907
public function getValue( $variableSet, $evaluationResult, $log )
	{
		$aspect = $variableSet->aspectModel == 'dimensional'
			? ( $this->occ == 'segment' ? ASPECT_NON_XDT_SEGMENT : ASPECT_NON_XDT_SCENARIO )
			: ( $this->occ == 'segment' ? ASPECT_COMPLETE_SEGMENT : ASPECT_COMPLETE_SCENARIO );

		$sourceFact = $variableSet->getSourceFact( $this->source, $evaluationResult, $aspect, $log );
		if ( ! $sourceFact ) return null;
		$contextRef = FactValues::getContextRef( $sourceFact );
		if ( ! $contextRef ) return null;
		$context = $variableSet->xbrlInstance->getContext( $contextRef );
		// $component = isset( $context['entity'][ $this->occ ]['member'] )
		// 	? $context['entity'][ $this->occ ]['member']
		// 	: array();
		$components = array();
		if ( ! $this->select ) return $components;

		$componentNodes = $this->evaluateXPath( $variableSet, "{$this->select}", array( $this->getSourceName() => $sourceFact ) );

		foreach ( $componentNodes as $node )
		{
			if ( ( $this->occ == 'scenario' || $this->occ == 'segment' ) &&
				 $node->getNamespaceURI() == \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_XBRLDI] )
			{
				$log->formula_validation( "OCC XPath", "The result of the XPath query is not consistent with ",
					array(
						'occ' => $this->occ,
						'xpath' => $this->select,
						'error' => 'xbrlfe:badSubsequentOCCValue'
					)
				);
			}
			$components[] = array( 'name' => $node->getName(), 'member' => '' );
		}

		return $components;
	}
246885
public function generateInstanceDocument( $xbrlInstance, $nsMgr )
	{
		// Get the namespaces from the input documment
		// $namespaces = $xbrlInstance->getInstanceXml()->getDocNamespaces();

		// Get the taxonomy document uri from the input document
		$taxonomyUri = $xbrlInstance->getInstanceTaxonomy()->getTaxonomyXSD();

		$document[] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		$document[] = "<!-- Generated by XBRLQuery formula processor -->";

		// Add the root element and namespaces
		// First make sure there is a default xbrli prefix
		if ( ! isset( $this->namespaces[''] ) )
		{
			$this->namespaces[''] = \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_XBRLI ];
		}
		$document[] ="<xbrl";
		foreach ( $this->namespaces as $prefix => $namespace )
		{
			$document[] = "  " . ( $prefix ? "xmlns:$prefix=\"$namespace\"" : "xmlns=\"$namespace\"" );
		}

		if ( ! isset( $this->namespaces['xsi'] ) &&
				array_filter( $this->facts, function( $facts ) {
					return array_filter( $facts, function( $fact ) { return is_null( $fact['value'] ); } ); }
				)
		   )
		{
			$document[] = "  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"";
		}

		if ( ! isset( $this->namespaces['link'] ) )
		{
			$document[] = "  xmlns:link=\"http://www.xbrl.org/2003/linkbase\"";
		}

		$document[] =">";

		// Add the schema ref
		$document[] = "";
		$document[] = "  <link:schemaRef  xlink:type=\"simple\" xlink:href=\"$taxonomyUri\"/>";
		$document[] = "";

		foreach ( $this->linkbases as $linkbase )
		{
			$document[] = "  <link:linkbaseRef";
			$document[] = "    xlink:type=\"{$linkbase['xlink:type']}\"";
			$document[] = "    xlink:arcrole=\"{$linkbase['xlink:arcrole']}\"";
			$document[] = "    xlink:href=\"{$linkbase['xlink:href']}\"";
			$document[] = "  />";
			$document[] = "";
		}

		// Add the contexts
		// $this->addContexts( $document, $xbrlInstance->getPrefixForNamespace( \XBRL_Constants::$standardPrefixes[ STANDARD_PREFIX_XBRLDI ] ) );
		$this->addContexts( $document, STANDARD_PREFIX_XBRLDI );

		// Add the units
		$this->addUnits( $document );

		// Add the facts
		$this->addFacts2( $document );

		// Close the document
		$document[] ="</xbrl>";

		// Run validation on the generated document

		return implode( "\n", $document) ;
	}
1208621
public static function getDimensionsForFact( $variableSet, $fact )
	{
		$contextRef = FactValues::getContextRef( $fact );
		return FactValues::getDimensionsInContextRef( $variableSet, $contextRef );
	}
1206838
function setVariable( $var, $val, $namespace = '', $scopeSafe = false )
    {
        if ( $scopeSafe && isset( $this->Variables[$namespace][$var] ) )
        {
            $safeNamespace = $namespace;
            do
            {
                $safeNamespace .= ':safe';
            }
            while( isset( $this->Variables[$safeNamespace][$var] ) );

            $this->Variables[$safeNamespace][$var] = $this->Variables[$namespace][$var];
        }

        $this->Variables[$namespace][$var] = $val;
    }
751321
public function ns($key, $url) {
        if (strpos($key, 'xmlns') !== 0) {
            $key = 'xmlns:' . $key;
        }

        $this->_namespaces[$key] = $url;

        return $this;
    }
669963
public static function GetNamespaceUriForPrefix( $context, $prefix, $nav )
	{
		$ns  = "";
		if ( $prefix instanceof  Undefined || $prefix . "" == "" )
		{
			$ns = $nav->getNamespaceURI();
		}
		else
		{
			/**
			 * @var XmlNamespaceManager $nsmgr
			 */
		    $nsmgr = new XmlNamespaceManager();
		    ExtFuncs::ScanLocalNamespaces( $nsmgr, $nav->CloneInstance(), false );
		    $ns = $nsmgr->lookupNamespace( $prefix . "" );
		}
		return is_null( $ns )
			? Undefined::getValue()
			: new AnyUriValue( $ns );
	}
332503
public function toQuery( $variableSet, $factVariableBinding )
	{
		$expressions = array();

		// Include the qnames if being called as part of a boolean filter or there are qname expressions
		if ( $this->inBoolean || $this->qnameExpressions )
		foreach ( $this->qnames as $qname )
		{
			$name = qname( $qname );
			$expressions[] = "(fn:node-name(..) eq fn:QName('{$name->namespaceURI}','{$name->localName}'))";
		}

		foreach ( $this->qnameExpressions as $qnameExpression )
		{
			$expressions[] = "(fn:node-name(..) eq {$qnameExpression})";
		}

		return implode( " or ", $expressions );
	}