Process the validations common to all variable sets
@param XBRL $taxonomy
@param array $contextParameters A list of the parameter values to be used as sources for formula parameters
@return bool
773893
private function validateCommon( $taxonomy, $contextParameters )
	{
		// if ( ! $this->validateParameters( $taxonomy, $contextParameters ) )
		// {
		// 	return false;
		// }

		if ( ! $this->validateCustomFunction( $taxonomy ) )
		{
			return false;
		}

		if ( ! $this->validateVariableSets( $taxonomy, $contextParameters ) )
		{
			return false;
		}

		if ( ! $this->validateConsistencyAssertions( $taxonomy ) )
		{
			return false;
		}

		// validate default dimensions in instances and accumulate multi-instance-default dimension aspects (really, look in the contexts)

		// check for variable set dependencies across output instances produced

		return true;
	}
513045
private function validateCustomFunction( $taxonomy )
	{

		// Get any variable sets.  These will be headed by a formula.
		$signatures = $taxonomy->getGenericResource( 'customfunction',  'signature' );
		$implementationResources = $taxonomy->getGenericResource( 'customfunction',  'implementation' );

		// Make sure any implementations have signatures
		if ( $implementationResources )
		{
			foreach ( $implementationResources as $x => $implementationResource )
			{
				// TODO
			}
		}

		if ( ! $signatures ) return true;

		foreach ( $signatures as $signatureKey => $signatureReference )
		{
			/** @var Signature $signature */
			$signature = Signature::fromArray( $signatureReference['customfunction'] );

			// Make sure the signature label has not been used already
			if ( isset( $this->signatures[ $signatureReference['resourceName'] ] ) )
			{
				$this->log->formula_validation( "custom function", "More than one signature has the same label",
					array(
						'error' => 'xbrlcfie:tooManyCFIRelationships',
						'label' => $signatureReference['resourceName']
					)
				);
			}

			$this->signatures[ $signatureReference['resourceName'] ] = $signature;

			if ( ! $signature->validate( null, $this->nsMgr ) )
			{
				return false;
			}

			// Locate the implementation
			$arcs = $taxonomy->getGenericArc( XBRL_Constants::$arcRoleCustomFunctionImplementation, $signatureReference['roleUri'], $signatureReference['resourceName'] );
			$implementations = array();
			foreach ( $arcs as $arc )
			{
				foreach ( $implementationResources as $implementationResourceKey => $implementationResource )
				{
					if ( $implementationResource['resourceName'] !=  $arc['label'] ) continue;
					if ( $implementationResource['roleUri'] !=  $arc['toRoleUri'] ) continue;

					$resource = $implementationResource['customfunction'];
					$resource['linkbase'] = $implementationResource['linkbase'];
					$implementations[] = Implementation::fromArray( $resource );
					unset( $implementationResources[ $implementationResourceKey ] );
				}

			}

			if ( count( $implementations ) > 1 )
			{
				$this->log->formula_validation( "custom function", "More than one signature has the same label",
					array(
						'error' => 'xbrlcfie:tooManyCFIRelationships',
						'label' => $signatureReference['resourceName'],
						'implementations' => implode( ", ", array_reduce( $implementations, function( $carry, $item ) { $carry[] = $item->label; return $carry; }, [] ) ),
					)
				);
			}

			if ( ! count( $implementations ) )
			{
				// If there is no explicit implementation make sure there is an existing function with this signature
				$functionTable = FunctionTable::getInstance();
				$functionDef = $functionTable->Bind( $signature->name['name'], $signature->name['namespace'], count( $signature->inputs ) );
				if ( ! $functionDef )
				{
					$this->log->formula_validation( 'Custom function', 'Missing implementation for signature', array(
						'signature' => $signatureReference['resourceName'],
						// 'error' => 'xbrlcfie:missingCFIRelationship'
					) );

					// return false;
				}
			}

			foreach ( $implementations as $implementation )
			{
				if ( count( $implementation->inputs ) != count( $signature->inputs ) )
				{
					$this->log->formula_validation( 'Custom function', 'Different parameter counts for implementation and signature', array(
						'signature' => $signatureReference['resourceName'],
						'signature count' => count( $signature->inputs ),
						'$implementation count' => count( $implementation->inputs ),
						'error' => 'xbrlcfie:inputMismatch'
					) );

					return false;
				}

				// Add a defintion to the function table
				$functionTable = FunctionTable::getInstance();
				$parameters = $this->parameterQnames;
				$functionTable->AddWithArity( $signature->name['namespace'], $signature->name['name'],  count( $signature->inputs ), $signature->output,
					function( $context, $provider, $args ) use( $implementation, $signature, $parameters )
					{
						return $implementation->execute( $signature, $context, $provider, $args, $parameters );
					}
				);

			}

			$this->signatures[ $signatureReference['resourceName'] ]->implementations = $implementations;
		}

		if ( count( $implementationResources ) )
		{
			$this->log->formula_validation( "custom function", "One or more implementations do not have a signature",
				array(
					'error' => 'xbrlcfie:missingCFIRelationship',
					'implementations' => implode( ", ", array_reduce( $implementations, function( $carry, $item ) { $carry[] = $item->label; return $carry; }, [] ) ),
				)
			);
		}

		return true;
	}
221899
private function validateVariableSets( $taxonomy, $contextParameters )
	{
		// Variable sets are headed by a formula or assertion
		$variableSets = $taxonomy->getGenericResource( 'variableset', null );

		if ( $variableSets )
		foreach ( $variableSets as $index => $variableSet )
		{
			$variableSetResource = $variableSet['variableset'];

			// Workout the class for this variable set resource
			$element = $variableSetResource[ "{$variableSetResource['type']}Type" ];
			$variableSetClassName = '\\XBRL\\Formulas\\Resources\\' .
				Formulas::$formulaElements[ $element ]['part'] .
				( isset( Formulas::$formulaElements[ $element ]['className'] )
					? Formulas::$formulaElements[ $element ]['className']
					: ucfirst( $element )
				);
			if ( is_null( $variableSetClassName ) )
			{
				$this->log->err( "Variable set sub-type '{$variableSetResource['type']}Type' is not valid" );
				return false;
			}

			// Create the instance and store it
			/** @var VariableSet $variableSetInstance */
			unset( $variableSetInstance );
			$variableSetInstance = $variableSetClassName::fromArray( $variableSetResource );
			$variableSetInstance->instanceName = $this->instanceQName; // Set a default. It may be overridden by an instance arc
			$variableSetInstance->xbrlTaxonomy = $taxonomy;
			$variableSetInstance->extendedLinkRoleUri = $variableSet['roleUri'];
			$variableSetInstance->linkbase = $variableSet['linkbase'];

			$this->variableSets[ "{$variableSet['roleUri']}#{$variableSet['resourceName']}" ][] =& $variableSetInstance;

			$linkbaseInfo = $taxonomy->getLinkbase( $variableSet['linkbase'] );
			if ( $linkbaseInfo )
			{
				$this->addNamespaces( array( $linkbaseInfo['namespaces'] ) );
			}

			$this->validateLabels( $taxonomy, $variableSetInstance, $taxonomy->getDefaultLanguage() );

			$this->validateParameters( $taxonomy, $contextParameters, $variableSetInstance );

			// Find all variables related to this variable set
			$instanceArcs = $taxonomy->getGenericArc( XBRL_Constants::$arcRoleFormulaInstance, $variableSet['roleUri'], $variableSet['resourceName'], $variableSetInstance->path, $variableSetInstance->linkbase );
			foreach ( $instanceArcs as $instanceArc )
			{
				if ( $instanceArc['from'] != $variableSetInstance->label ) continue;
				// Look for the instance resource
				if ( ! isset( $this->instanceQNames[ $instanceArc['label'] ] ) ) continue;
				$variableSetInstance->instanceName = $this->instanceQNames[ $instanceArc['label'] ];
			}

			// Find all variables related to this variable set
			$variableSetArcs = $taxonomy->getGenericArc( XBRL_Constants::$arcRoleVariableSet, $variableSet['roleUri'], $variableSet['resourceName'], $variableSetInstance->path /* , $variableSetInstance->linkbase */ );
			$variableResources = array();

			foreach ( $variableSetArcs as $arcIndex => $variableSetArc )
			{
				if ( $variableSetArc['fromlinkbase'] != $variableSetInstance->linkbase ) continue;
				if ( $variableSetInstance->path != $variableSetArc['frompath'] ) continue;

				$result = $taxonomy->getGenericResource( 'variable', null, function( $roleUri, $linkbase, $variableSetName, $index, $resource ) use( &$variableResources, $variableSetArc )
				{
					// This test is probably redundant because I believe $variableSetName is the same as $variableSetArc['label']
					if ( /* $linkbase == $variableSetArc['tolinkbase'] && */ $resource['path'] == $variableSetArc['topath'] && $variableSetName == $variableSetArc['label'] )
					{
						$resource['name'] = $variableSetArc['name'];
						$resource['linkbase'] = $linkbase;
						$variableResources[ $variableSetName ][] = $resource;
					}

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

			// Process each located variable resource
			foreach ( $variableResources as $variableLabel => $variableResourceSet )
			{
				foreach ( $variableResourceSet as $variableResource )
				{
					// if ( $variableSetInstance->path != $variableResource['path'] )
					// 	continue;

					if ( $variableResource['variableType'] == 'parameter' )
					{
						// Find the parameter with label $variableResource['label']. This becomes
						// the parameter with qname $variableResource['name']
						$resourceQName = new QName( $variableResource['name']['originalPrefix'], $variableResource['name']['namespace'], $variableResource['name']['name'] );
						foreach ( $this->parameterQnames as $qname => $parameter )
						{
							if ( $parameter->label == $variableResource['label'] )
							{
								// BMS 2018-03-23 One test too many
								// if ( $qname == $resourceQName->clarkNotation() )
								{
									$variableSetInstance->parameters[ $resourceQName->clarkNotation() ] = $this->parameterQnames[ $qname ];
								}
								break;
							}
						}

						continue;
					}

					$variableClassName = '\\XBRL\\Formulas\\Resources\\' .
						Formulas::$formulaElements[ $variableResource['variableType'] ]['part'] .
						( isset( Formulas::$formulaElements[ $variableResource['variableType'] ]['className'] )
							? Formulas::$formulaElements[ $variableResource['variableType'] ]['className']
							: ucfirst( $variableResource['variableType'] )
						);

					if ( is_null( $variableClassName ) )
					{
						$this->log->formula_validation( "Variables", "Invalid variable type",
							array(
								'variable type' => $resource['variableType'],
							)
						);
						return false;
					}

					/** @var \XBRL\Formulas\Resources\Variables\Variable $variable */
					$variable = $variableClassName::fromArray( $variableResource );
					$variable->extendedLinkRoleUri = $variableResource['linkRoleUri'];

					// Add labels
					$this->validateLabels( $taxonomy, $variable, $taxonomy->getDefaultLanguage() );

					// Instances
					// Find all instances related to this variable.  The variable-instance
					// arcs are back-to-front as the arcrole name suggests so get all the
					// arcs and find a suitable one if it exists
					$instanceArcs = $taxonomy->getGenericArc( XBRL_Constants::$arcRoleInstanceVariable, $variable->extendedLinkRoleUri, null, $variable->path, null, $variable->linkbase );
					foreach ( $instanceArcs as $instanceArc )
					{
						if ( $instanceArc['to'] != $variable->label ) continue;
						// Look for the arc source among the valid instance qnames
						if ( ! isset( $this->instanceQNames[ $instanceArc['from'] ] ) ) continue;

						$variable->instanceSourceQName = $this->instanceQNames[ $instanceArc['from'] ];
						break;
					}

					if ( is_null( $variable->instanceSourceQName ) )
					{
						$variable->instanceSourceQName = $this->instanceQNames['standard-input-instance'];
					}

					if ( ! $variableSetInstance->AddVariable( $variable ) )
					{
						return false;
					}

					// This is necessary because $variable is used as a reference.
					// Without this subsequent variables replace earlier ones.
					unset( $variable );
				}
			}

			// BMS 2018-01-25 Moved these here so they can be checked when all variables have been created in case there are interdependencies
			foreach ( $variableSetInstance->variablesByQName as $qname => $variable )
			{
				// Time to pull in the filters for fact variables (general variables do not have filters)
				if ( $variable instanceof FactVariable && ! $this->validateFilters( $taxonomy, XBRL_Constants::$arcRoleVariableFilter, $variable, $variableSetInstance ) )
				{
					return false;
				}

				if ( ! $variable->validate( $variableSetInstance, $this->nsMgr ) )
				{
					return false;
				}

			}

			// Pull in any group filters
			// if ( ! $this->validateGroupFilters( $variableSetInstance ) )
			if ( ! $this->validateFilters( $taxonomy, XBRL_Constants::$arcRoleVariableSetFilter, $variableSetInstance, $variableSetInstance ) )
			{
				return false;
			}

			// Check variable scopes for visible variables
			if ( ! $this->validateVariableScopes( $taxonomy, $variableSetInstance ) )
			{
				return false;
			}

			// Now the variables are known validate the formula
			if ( ! $variableSetInstance->validate( null, $this->nsMgr ) )
			{
				return false;
			}

			$variableSetInstance->validateMessages( $taxonomy->getDefaultLanguage() );

			// The variable refs MUST either refer to variables or parameters
			$variableSetRefs = $variableSetInstance->getVariableRefs();

			foreach ( $variableSetRefs as $qname => $variableSetRefQName )
			{
				// Look for a variable with this name
				if ( ! is_null( $variableSetRefQName ) && isset( $variableSetInstance->variablesByQName[ $variableSetRefQName->clarkNotation() ] ) )
				{
					continue;
				}

				if ( ! is_null( $variableSetRefQName ) && isset( $variableSetInstance->parameters[ $variableSetRefQName->clarkNotation() ] ) )
				{
					// Parameters do not contribute the definition of the dependency tree
					unset( $variableSetRefs[ $qname ] );
					continue;
				}

				// BMS 2018-02-27 See note above with the same date about a line commented out
				// Could be a reference to a global parameter.  If so, add the global parameter.
				if ( isset( $this->parameterQnames[ $variableSetRefQName->clarkNotation() ] ) )
				{
					// Parameters do not contribute the definition of the dependency tree
					$variableSetInstance->parameters[ $variableSetRefQName->clarkNotation() ] = $this->parameterQnames[ $variableSetRefQName->clarkNotation() ];
					unset( $variableSetRefs[ $qname ] );
					continue;
				}

				// Could be a reference to scope dependency
				if ( isset( $variableSetInstance->scopeDependencies[ $variableSetRefQName->clarkNotation() ] ) )
				{
					unset( $variableSetRefs[ $qname ] );
					continue;
				}
				// Are variable references that are not not exist as variables or parameters in the variable set
				unset( $variableSetRefs[ $qname ] );
				$this->log->formula_validation( "Variable set", "Variable reference does not not exist as a variable or parameter in the variable set",
					array(
						'reference' => (string)$variableSetRefQName,
						'error' => 'xbrlve:unresolvedDependency'
					)
				);
			}

			// Create a variables dependency tree
			$variableRefs = array();
			foreach ( $variableSetInstance->variablesByQName as $qname => $variable )
			{
				$variableRefs[ $qname ] = array();
				foreach ( $variable->getVariableRefs() as $variableRefQName )
				{
					// If this is not a reference to a variable ignore because non-variable,
					// such as parameters, do not affect the dependency
					if ( isset( $variableSetInstance->variablesByQName[ $variableRefQName->clarkNotation() ] ) )
					{
						$variableRefs[ $qname ][] = $variableRefQName;
					}
				}
			}

			// Create a hierarchy from the remainder.
			$hierarchy = array();
			$roots = array();

			foreach ( $variableRefs as $dependent => $users )
			{
				if ( ! count( $users ) )
				{
					if ( ! isset( $roots[ $dependent ] ) )
					{
						$roots[ $dependent ] = array();
					}

					if ( ! isset( $hierarchy[ $dependent ] ) )
					{
						$hierarchy[ $dependent ] = array();
					}

					continue;
				}

				foreach ( $users as /** @var QName $userQName */ $userQName )
				{
					$user = $userQName->clarkNotation();

					if ( ! isset( $hierarchy[ $user ] ) )
					{
						$roots[ $user ] = array();
					}

					if ( isset( $roots[ $dependent ] ) )
					{
						unset( $roots[ $dependent ] );
					}

					if ( ! isset( $hierarchy[ $dependent ] ) )
					{
						$hierarchy[ $dependent ] = array();
					}

					$hierarchy[ $user ][ $dependent ] =& $hierarchy[ $dependent ];
				}
			}

			// If there are nodes but no roots then there is a cyclic problem
			if ( $hierarchy && ! $roots )
			{
				$links = array();
				foreach ( $variableRefs as $dependent => $users )
				{
					foreach ( $users as /** @var QName $userQName */ $userQName )
					{
						$user = $userQName->clarkNotation();
						$links[] = "{$userQName->clarkNotation()}->$dependent";
					}
				}

				$this->log->formula_validation( "Variables", "There is a cyclic dependency between the variable references",
					array(
						'variables' => implode( ", ", $links ),
						'error' => 'xbrlve:cyclicDependencies',
					)
				);

				return false;
			}

			$variableSetInstance->variableOrderHierarchy = array_intersect_key( $hierarchy, $roots );

			// check existence assertion @test variable dependencies (not including precondition references)

	        // check messages variable dependencies

	        // check preconditions
			if ( ! $this->validatePreconditions( $taxonomy, $variableSetInstance ) )
			{
				// return false;
			}

			unset( $variableSetInstance );
		}

		// Make sure formulas are executed in the correct order if there are scope dependencies
		$scopeDependencies = array();
		foreach ( $this->variableSets as $variableSetInstances )
		{
			foreach ( $variableSetInstances as $variableSetInstance )
			{
				$toVariableSetKey = "{$variableSetInstance->extendedLinkRoleUri}#{$variableSetInstance->label}";

				if ( $variableSetInstance->scopeDependencies )
				{
					foreach ( $variableSetInstance->scopeDependencies as $qname => $scopeDependency )
					{
						$fromVariableSetKey = "{$scopeDependency['fromRoleUri']}#{$scopeDependency['from']}";

						if ( ! isset( $this->variableSets[ $fromVariableSetKey ] ) )
						{
							$this->log->formula_validation( "variable sets", "The scope dependency formula does not exist",
								array(
									'from formula' => $scopeDependency['from'],
									'to formula' => '$variableSetInstance->label',
									'error' => 'xbrlve:dependentFormulaNotFound'
								)
							);
						}

						$scopeDependencyVariableSet = $this->variableSets[ $fromVariableSetKey ];

						if ( ! ( ( $variableSetInstance instanceof Formula && $scopeDependencyVariableSet[0] instanceof Formula ) ||
								 ( get_class( $variableSetInstance ) == get_class( $scopeDependencyVariableSet[0] ) )
							   )
						)
						{
							$this->log->formula_validation( "variable sets", "The variable set type of the source and target must be the same (formula or one of the assertion type)",
								array(
									'from formula' => $scopeDependency['from'],
									'to formula' => '$variableSetInstance->label',
									'error' => 'xbrlvarscopee:conflictingVariableSet types'
								)
							);
						}

						if ( $variableSetInstance->aspectModel != $scopeDependencyVariableSet[0]->aspectModel )
						{
							$this->log->formula_validation( "variable sets", "The aspect models of the formulas linked by a scope dependency are different",
								array(
									'from formula' => $scopeDependency['from'],
									'to formula' => $variableSetInstance->label,
									'error' => 'xbrlvarscopee:conflictingAspectModels'
								)
							);
						}

						if ( $variableSetInstance->instanceName != $scopeDependencyVariableSet[0]->instanceName )
						{
							$this->log->formula_validation( "variable sets", "The instancs of the scope source and target must be the same",
								array(
									'from formula' => $scopeDependency['from'],
									'to formula' => $variableSetInstance->label,
									'error' => 'xbrlvarscopee:differentInstances'
								)
							);
						}

						$scopeDependencies[ $toVariableSetKey ][] = $fromVariableSetKey;
					}
				}
				else
				{
					// Just add the variable set
					$scopeDependencies[ $toVariableSetKey ] = array();
				}
			}
		}

		// Create a hierarchy of the formulas.
		$hierarchy = array();
		$roots = array();

		foreach ( $scopeDependencies as $dependent => $users )
		{
			if ( ! count( $users ) )
			{
				if ( ! isset( $roots[ $dependent ] ) )
				{
					$roots[ $dependent ] = array();
				}

				if ( ! isset( $hierarchy[ $dependent ] ) )
				{
					$hierarchy[ $dependent ] = array();
				}

				continue;
			}

			foreach ( $users as $user )
			{
				// $user = $userQName->clarkNotation();

				if ( ! isset( $hierarchy[ $user ] ) )
				{
					$roots[ $user ] = array();
				}

				if ( isset( $roots[ $dependent ] ) )
				{
					unset( $roots[ $dependent ] );
				}

				if ( ! isset( $hierarchy[ $dependent ] ) )
				{
					$hierarchy[ $dependent ] = array();
				}

				$hierarchy[ $user ][ $dependent ] =& $hierarchy[ $dependent ];
			}
		}

		// If there are nodes but no roots then there is a cyclic problem
		if ( $hierarchy && ! $roots )
		{
			$links = array();
			foreach ( $variableRefs as $dependent => $users )
			{
				foreach ( $users as /** @var QName $userQName */ $userQName )
				{
					$user = $userQName->clarkNotation();
					$links[] = "{$userQName->clarkNotation()}->$dependent";
				}
			}

			$this->log->formula_validation( "Variables", "There is a cyclic dependency between the formula scope variable references",
				array(
					'variables' => implode( ", ", $links ),
					'error' => 'xbrlve:cyclicDependencies',
				)
			);

			return false;
		}

		$orderedVariables = array();
		$flatten = function( $hierarchy, $parent = null ) use ( &$flatten, &$orderedVariables )
		{
			// $results = array();
			$parents[] = $parent;
			foreach ( $hierarchy as $variable => $dependents )
			{
				// If the variable already exists, remove and re-add so it is appended (moved down the list)
				if ( isset( $orderedVariables[ $variable ] ) )
				{
					$parents = array_merge( $parents, $orderedVariables[ $variable ] );
					unset( $orderedVariables[ $variable ] );
				}
				$orderedVariables[ $variable ] = $parents;
				if ( ! count( $dependents ) ) continue;
				$flatten( $dependents, $variable );
			}
			// return $results;
		};

		$flatten( array_intersect_key( $hierarchy, $roots ) );

		unset( $variableSetInstance );

		// foreach ( $this->variableSets as $variableSetInstances )
		foreach ( $orderedVariables as $formulaQName => $x )
		{
			if ( ! isset( $this->variableSets[ $formulaQName ] ) )
			{
				$this->log->formula_validation( "variables sets", "The dependent formula does not exist",
					array(
						'formula' => $variableSetInstance->label,
						'error' => 'xbrlve:missingFormula'
					)
				);
			}

			$variableSetInstances = $this->variableSets[ $formulaQName ];

			foreach ( $variableSetInstances as $variableSetInstance )
			{
		        // check for variable sets referencing fact or general variables
		        if ( $variableSetInstance->scopeDependencies )
		        {
		        	// Access the variable set containing the scope variable
		        	foreach ( $variableSetInstance->scopeDependencies as $scopeVariableQName => $scopeDependency )
		        	{
						$fromVariableSetKey = "{$scopeDependency['fromRoleUri']}#{$scopeDependency['from']}";
						$scopeVariableSetInstances = $this->variableSets[ $fromVariableSetKey ];

						// Allow for many
						foreach ( $scopeVariableSetInstances as $scopeVariableSetInstance )
						{
							// Copy the evaluation result(s) and the variable binding(s)to this instance
							if ( $variableSetInstance instanceof Formula )
							{
								// Begin by removing any ScopeVariable variables.  These were added to get by the variable set validation.
								foreach ( $variableSetInstance->variablesByQName as $variableQName => $variable )
								{
									if ( ! $variable instanceof ScopeVariable || ! is_null( $variable->binding ) ) continue;
									unset( $variableSetInstance->variablesByQName[ $variableQName ] );
									// Also remove from the variable order list
									unset( $variableSetInstance->variableOrderHierarchy[ $variableQName ] );
								}

								// Now create a variable for the scope variable fact
								$variable = new ScopeVariable();
								$variable->label = $scopeVariableQName;
								$variable->extendedLinkRoleUri = $scopeVariableSetInstance->extendedLinkRoleUri;
								$variable->name = $scopeDependency['name'];
								// Add the variable
								$variableSetInstance->variablesByQName[ $scopeVariableQName ] = $variable;
								// add a reference to the variable to the beginning of the list of
								// order variables so it is processed before any others
								$variableSetInstance->variableOrderHierarchy = array_reverse( $variableSetInstance->variableOrderHierarchy, true );
								$variableSetInstance->variableOrderHierarchy[ $scopeVariableQName ] = array();
								$variableSetInstance->variableOrderHierarchy = array_reverse( $variableSetInstance->variableOrderHierarchy, true );

								// Create a binding for each result
								if ( $variableSetInstance->evaluationResults )
								{
									$variableSetInstance->evaluationResults = array_merge( $variableSetInstance->evaluationResults, $scopeVariableSetInstance->evaluationResults );
								}
								else
								{
									$variableSetInstance->evaluationResults = $scopeVariableSetInstance->evaluationResults;
								}

								$binding = new ScopeVariableBinding( $scopeVariableSetInstance->xbrlInstance, $variable );

								// Create an iterator from the facts
								if ( $scopeVariableSetInstance->evaluationResults )
								{
									// Only take evaluation results generated by the source variable set
									$items = array_filter( $variableSetInstance->evaluationResults,
										function( $evaluationResult ) use( $scopeDependency )
										{
											return $evaluationResult['variableSet'] == $scopeDependency['from'];
										}
									);
									$facts = DocumentOrderNodeIterator::fromItemset( $items );
									$binding->facts = $facts;
								}

								$variable->binding = $binding;
				        		// $variableSetInstance->factVariableBindings[ $variableQName ] = $binding;
				        	}
				        	else
				        	{
				        		// TODO
				        	}
						}
		        	}
		        }

				// Evaluate the variable set
				if ( ! $this->evaluate( $variableSetInstance ) )
				{
					return false;
				}
			}
		}

		if ( $this->formulaFactsContainer )
		{
			$document = $this->formulaFactsContainer->generateInstanceDocument( $this->instances[ $this->instanceQName->clarkNotation() ], $this->nsMgr );
		}

		return true;
	}
1159955
public function validate( $variableSet, $nsMgr )
	{
		if ( isset( $this->dimensionExpression ) && ! empty( $this->dimensionExpression ) )
		{
			try
			{
				$xpath2Expression = XPath2Expression::Compile( $this->dimensionExpression, $nsMgr );
				if ( parent::checkForCoverXFIFunctionUse( $this->dimensionExpression, $xpath2Expression ) )
				{
					return false;
				}
				$this->dimensionXPath2Expression = $xpath2Expression;
			}
			catch ( Exception $ex )
			{
				\XBRL_Log::getInstance()->formula_validation( "Explicit dimension filter", "Failed to compile qname expression",
					array(
						'qname expression' => $this->dimensionExpression,
						'error' => $ex instanceof XPath2Exception ? $ex->ErrorCode : get_class( $ex ),
						'reason' => $ex->getMessage()
					)
				);

				return false;
			}
		}

		foreach ( $this->members as &$member )
		{
			if ( ! isset( $member['qnameExpression'] ) ) continue;

			try
			{
				$xpath2Expression = XPath2Expression::Compile( $member['qnameExpression'], $nsMgr );
				if ( parent::checkForCoverXFIFunctionUse( $member['qnameExpression'], $xpath2Expression ) )
				{
					return false;
				}
				$member['qnameXPath2Expression'] = $xpath2Expression;
			}
			catch ( Exception $ex )
			{
				\XBRL_Log::getInstance()->formula_validation( "Explicit dimension filter", "Failed to compile test expression",
					array(
						'qname expression' => $member['qnameExpression'],
						'error' => $ex instanceof XPath2Exception ? $ex->ErrorCode : get_class( $ex ),
						'reason' => $ex->getMessage()
					)
				);

				return false;
			}
		}

		return true;
	}
573540
public function generateMethodParameter($parameter, Context $context, $reference): Node\Param
    {
        $name = Inflector::camelize($parameter->getName());
        $methodParameter = new Node\Param(new Expr\Variable($name));

        if (!$parameter->getSchema()) {
            return $methodParameter;
        }

        if (!$parameter->getRequired() || null !== $parameter->getSchema()->getDefault()) {
            $methodParameter->default = $this->getDefaultAsExpr($parameter);
        }

        $types = $this->convertParameterType($parameter->getSchema()->getType());

        if (\count($types) === 1) {
            $methodParameter->type = new Node\Name($types[0]);
        }

        return $methodParameter;
    }
574073
public static function all_update_init_params(array &$params,
            context $context, array $options = null) {
        global $CFG;

        // Get list of plugin directories.
        $plugins = core_component::get_plugin_list('tinymce');

        // Get list of disabled subplugins.
        $disabled = array();
        if ($params['moodle_config']->disabledsubplugins) {
            foreach (explode(',', $params['moodle_config']->disabledsubplugins) as $sp) {
                $sp = trim($sp);
                if ($sp !== '') {
                    $disabled[$sp] = $sp;
                }
            }
        }

        // Construct all the plugins.
        $pluginobjects = array();
        foreach ($plugins as $plugin => $dir) {
            if (isset($disabled[$plugin])) {
                continue;
            }
            require_once($dir . '/lib.php');
            $classname = 'tinymce_' . $plugin;
            $pluginobjects[] = new $classname($plugin);
        }

        // Sort plugins by sort order and name.
        usort($pluginobjects, array('editor_tinymce_plugin', 'compare_plugins'));

        // Run the function for each plugin.
        foreach ($pluginobjects as $obj) {
            $obj->update_init_params($params, $context, $options);
        }
    }
173526
public function validate(\SwaggerValidator\Common\Context $context)
    {
        if (!$this->validateBaseSwagger($context)) {
            return false;
        }

        $keyPath = \SwaggerValidator\Common\FactorySwagger::KEY_PATHS;

        $context->logValidate(get_class($this), __METHOD__, __LINE__);
        $result = $this->$keyPath->validate($context->setDataPath($keyPath));

        if (!$result) {
            return false;
        }

        if ($context->getMode() === \SwaggerValidator\Common\Context::MODE_PASS) {
            $context->cleanParams();
            $context->setDataPath('CheckTooMany')->logValidate(get_class($this), __METHOD__, __LINE__);
            return true;
        }

        return $this->validateTooMany($context);
    }
119375
public static function lookup(&$context, $vars) {
        if (isset($vars[0][0]) && ($vars[0][0] === 'lookup')) {
            if (!$context['flags']['nohbh']) {
                if (count($vars) < 2) {
                    $context['error'][] = "No argument after {{lookup}} !";
                } else if (count($vars) < 3) {
                    $context['error'][] = "{{lookup}} requires 2 arguments !";
                }
                $context['usedFeature']['lookup']++;
                return true;
            }
        }
    }
688986
public static function validate_context($context) {
        global $CFG, $PAGE;

        if (empty($context)) {
            throw new invalid_parameter_exception('Context does not exist');
        }
        if (empty(self::$contextrestriction)) {
            self::$contextrestriction = context_system::instance();
        }
        $rcontext = self::$contextrestriction;

        if ($rcontext->contextlevel == $context->contextlevel) {
            if ($rcontext->id != $context->id) {
                throw new restricted_context_exception();
            }
        } else if ($rcontext->contextlevel > $context->contextlevel) {
            throw new restricted_context_exception();
        } else {
            $parents = $context->get_parent_context_ids();
            if (!in_array($rcontext->id, $parents)) {
                throw new restricted_context_exception();
            }
        }

        $PAGE->reset_theme_and_output();
        list($unused, $course, $cm) = get_context_info_array($context->id);
        require_login($course, false, $cm, false, true);
        $PAGE->set_context($context);
    }
800323
protected static function with(&$context, $vars) {
        $v = isset($vars[1]) ? static::getVariableNameOrSubExpression($context, $vars[1]) : array(null, array());
        $bp = Parser::getBlockParams($vars);
        $bs = $bp ? ('array(' . Expression::listString($bp) . ')') : 'null';
        $be = $bp ? " as |$bp[0]|" : '';
        return $context['ops']['seperator'] . static::getFuncName($context, 'wi', 'with ' . $v[1] . $be) . "\$cx, {$v[0]}, $bs, \$in, function(\$cx, \$in) {{$context['ops']['array_check']}{$context['ops']['f_start']}";
    }
122202
public function canEvaluate($context)
    {
        if (count($context) === 0) {
            return true;
        }

        foreach ($context as $contextNode) {
            if (!$contextNode instanceof NodeInterface) {
                return false;
            }
        }
        return true;
    }
1224984
protected function validateBaseSwagger(\SwaggerValidator\Common\Context &$context)
    {
        $context->loadUri();
        $context->loadMethod();

        $this->checkSwaggerVersion($context->setDataPath('swagger')->setDataValue($this->swagger));
        $this->checkSchemes($context->setDataPath('schemes')->setDataValue($context->getScheme()));
        $this->checkHost($context->setDataPath('host')->setDataValue($context->getHost()));

        $ctxPath = $this->checkBasePath($context->setDataPath('basePath')->setDataValue($context->getBasePath()));

        if (!is_object($ctxPath) || !($ctxPath instanceof \SwaggerValidator\Common\Context)) {
            return false;
        }

        $context->setBasePath($ctxPath->getBasePath());
        $context->setRequestPath($ctxPath->getRequestPath());

        if ($context->getType() === \SwaggerValidator\Common\Context::TYPE_REQUEST) {
            $this->checkConsume($context->setDataPath('consumes')->setDataValue(null));
        }
        elseif ($context->getType() === \SwaggerValidator\Common\Context::TYPE_RESPONSE) {
            $this->checkProduce($context->setDataPath('produces')->setDataValue(null));
        }

        return true;
    }
1062133
protected function checkHost(\SwaggerValidator\Common\Context $context)
    {
        if (!isset($this->host)) {
            return true;
        }

        if ($context->getDataValue() === null) {
            return true;
        }

        if (strtolower($context->getDataValue()) && strtolower($this->host)) {
            return true;
        }

        return $context->setValidationError(\SwaggerValidator\Common\Context::VALIDATION_TYPE_HOSTNAME_ERROR, 'HostName requested is not allowed', __METHOD__, __LINE__);
    }
615478
public function process(ContainerBuilder $container)
    {
        $taggedServices = $container->findTaggedServiceIds(
            'elcodi.rule_context'
        );

        $contextProviders = [];
        foreach ($taggedServices as $id => $attributes) {
            $contextProviders[] = new Reference($id);
        }

        $definition = $container->getDefinition(
            'elcodi.expression_language_context_collector'
        );

        $definition->addArgument($contextProviders);
    }
1158320
private function getParameterFromContext(array $context, string $parameterName, $default = null)
    {
        $filters = $context['filters'] ?? [];

        return \array_key_exists($parameterName, $filters) ? $filters[$parameterName] : $default;
    }
1134516
public function validate( $variableSet, $nsMgr )
	{
		$testExpression = function( $expressionName, $expression )
		{
			$xpath2Expression = null;

			try
			{
				$xpath2Expression = XPath2Expression::Compile( $expression, $nsMgr );
				if ( parent::checkForCoverXFIFunctionUse( $this->qnameExpression, $xpath2Expression ) )
				{
					return false;
				}
			}
			catch ( Exception $ex )
			{
				\XBRL_Log::getInstance()->formula_validation( "Concept relation filter", "Failed to compile qname expression",
					array(
						'expression name' => $expressionName,
						'qname expression' => $expression,
						'error' => $ex instanceof XPath2Exception ? $ex->ErrorCode : get_class( $ex ),
						'reason' => $ex->getMessage()
					)
				);

				return false;
			}

			return $xpath2Expression;
		};

		foreach ( $this->expressionsList as $expressionName => $details )
		{
			if ( ! $details['expression'] ) continue;
			$xpath2Expression = $testExpression( $expressionName, $details['expression'] );
			if ( ! $xpath2Expression ) continue;
			$this->${$details['expression']} = $xpath2Expression;
		}

		return true;
	}
768764
protected static function evaluateLogical(ContextInterface $context, array $serializedLogical = null): bool
    {
        if ($serializedLogical === null) {
            return true;
        }

        $evaluation = call_user_func($serializedLogical, $context);
        $result     = $evaluation === true;

        return $result;
    }