Attempts to locate a class within the registered resolvers.
Optionally will build the class on failure.

@param string $class
@param bool $buildOnFailure
@param array $parameters
@return mixed|null|object
177467
public static function resolveClass( $class, $buildOnFailure = false, $parameters = [] )
	{
		if ( !is_string( $class ) )
			throw new ResolverException( "Class must be a string" );

		if ( $class == Framework::class )
			return Framework::fw();
		if ( $class == Configuration::class )
			return Framework::config();
		if ( $class == Logger::class )
			return Framework::log();

		// TODO Add a few more basic classes

		foreach ( static::$resolvers as $resolver )
			if ( false !== ( $result = $resolver->resolveClass( $class ) ) )
				return $result;

		if ( $buildOnFailure )
			return static::buildClass( $class, $parameters );

		return null;
	}
1097161
private function instantiate($class, array $parameters = [])
    {
        if (is_callable($class)) {
            return $class($this, $parameters);
        }
        $reflector = new \ReflectionClass($class);

        if (!$reflector->isInstantiable()) {
            //Try to give a descriptive exception message
            if ($reflector->isAbstract()) {
                throw new \InvalidArgumentException("Class {$class} is abstract and can not be instantiated.");
            }
            if ($reflector->isInterface()) {
                throw new \InvalidArgumentException("{$class} is an interface and can not be instantiated.");
            }
            throw new \InvalidArgumentException("Class {$class} can not be instantiated.");
        }

        $constructor = $reflector->getConstructor();

        if ($constructor === null || $constructor->getNumberOfParameters() === 0) {
            //Since the class has no constructor, it can not be instantiated with ReflectionClass

            //Also, if the class has no constructor arguments, it is cheaper to instantiate it directly
            //Although this has the downside of disallowing variable sized argument lists if
            //no arguments are required by the constructor signature.
            return new $class;
        }

        $constructorArgs = $constructor->getParameters();
        $arguments       = $this->resolveDependencies($constructorArgs, $parameters);

        if (!empty($parameters)) {
            //We need to sort the arguments because ReflectionClass passes them by order, not by index
            ksort($arguments);
        }

        return $reflector->newInstanceArgs($arguments);
    }
35300
public static ClassNameResolver buildDefault() {
        String enable = System.getProperty(Constants.SERIALIZE_BLACKLIST_ENABLE,
            Constants.DEFAULT_SERIALIZE_BLACKLIST_ENABLE);
        if (Boolean.TRUE.toString().equalsIgnoreCase(enable)) {
            ClassNameResolver resolver = new ClassNameResolver();
            resolver.addFilter(new InternalNameBlackListFilter());
            return resolver;
        }
        return null;
    }
918097
private function resolveConstructorArguments(ReflectionMethod $constructor, array $arguments)
    {
        $constructorParameters = $constructor->getParameters();

        foreach ($constructorParameters as $position => $parameter) {
            if ($parameter->getClass() && ServiceMocker::class === $parameter->getClass()->getName()) {
                $arguments[$position] = $this->serviceMocker;
            }
        }

        return $arguments;
    }
1169905
private function checkSessionBuilderClass($builder_class)
    {
        try {
            $reflection = new \ReflectionClass($builder_class);

            if (!$reflection->isSubclassOf('\PommProject\Foundation\Session\SessionBuilder')) {
                throw new FoundationException(
                    sprintf(
                        "Class '%s' is not a subclass of \PommProject\Foundation\Session\SessionBuilder.",
                        $builder_class
                    )
                );
            }
        } catch (\ReflectionException $e) {
            throw new FoundationException(
                sprintf(
                    "Could not instantiate class '%s'.",
                    $builder_class
                ),
                null,
                $e
            );
        }

        return $builder_class;
    }
889952
private function _failOnErrorAction(Exception $exception = null, $message = '', $level = Project::MSG_INFO)
    {
        if ($this->_failonerror) {
            throw new BuildException(
                $exception !== null ? $exception : $message,
                $this->getLocation()
            );
        } else {
            $this->log(
                $exception !== null && $message === '' ? $exception->getMessage() : $message,
                $level
            );
        }
    }
837758
protected function compileClassDefinition(ClassBuilder $builder, StreamWriter $writer)
    {
        $namespace = null;
        $class = $this->parseClassName($builder->getClass());
        if ($class['namespace']) {
            $namespace = $class['namespace'];
            $writer->writeLineF('namespace %s;', trim(ltrim($namespace, '\\')));
            $writer->writeLine();
        }

        $docblock = $builder->getDocblock();
        if ($docblock) {
            $writer->writeLine('/**');
            foreach ($docblock as $docline) {
                $docline = trim(ltrim($docline, '>'));
                $writer->writeLine(' * ' . $docline);
            }
            $writer->writeLine(' */');
        }

        $writer->writeF('class %s', $class['classname']);

        if ($extends = $builder->getExtends()) {
            $extends = $this->parseClassName($extends);
            if ($extends['namespace'] == $namespace) {
                $writer->writeF(' extends %s', $extends['classname']);
            } else {
                $writer->writeF(' extends %s', $extends['fqcn']);
            }
        }

        $interfaces = $builder->getInterfaces();
        if (count($interfaces)) {
            $writer->write(' implements ');
            $implements = array();
            foreach ($interfaces as $interface) {
                $interface = $this->parseClassName($interface);
                if ($interface['namespace'] == $namespace) {
                    $implements[] = $interface['classname'];
                } else {
                    $implements[] = $interface['fqcn'];
                }
            }
            $writer->write(implode(', ', $implements));
        }

        $writer->writeLine(' {');
        $writer->writeLine();
    }
292825
public function resolve($factory=false, $parameters=[]) {
        if (!$factory && $this->instance)
            return $this->instance;

        $instance   = null;
        $definition = $this->definition;
        !$factory && $parameters = [];

        if (is_string($definition)) {                       // plain strings are class names without parameters
            if (!is_class($definition)) throw new ClassNotFoundException('Cannot resolve service "'.$this->name.'" (unknown class "'.$definition.'")');
            $instance = new $definition(...$parameters);
        }
        else if (is_object($definition)) {                  // objects may be a \Closure or an already resolved instance
            $instance = $definition instanceof \Closure ? $definition(...$parameters) : $definition;
        }
        else throw new IllegalTypeException('Cannot resolve service "'.$this->name.'" (illegal definition type: '.gettype($definition).')');

        if (!$factory)
            $this->instance = $instance;
        return $instance;
    }
208866
protected function resolve($abstract, $parameters = [])
    {
        $abstract = $this->getAlias($abstract);

        $needsContextualBuild = ! empty($parameters) || ! is_null(
            $this->getContextualConcrete($abstract)
        );

        // If an instance of the type is currently being managed as a singleton we'll
        // just return an existing instance instead of instantiating new instances
        // so the developer can keep using the same objects instance every time.
        if (isset($this->instances[$abstract]) && ! $needsContextualBuild) {
            return $this->instances[$abstract];
        }

        $this->with[] = $parameters;

        $concrete = $this->getConcrete($abstract);

        // We're ready to instantiate an instance of the concrete type registered for
        // the binding. This will instantiate the types, as well as resolve any of
        // its "nested" dependencies recursively until all have gotten resolved.
        if ($this->isBuildable($concrete, $abstract)) {
            $object = $this->build($concrete);
        } else {
            $object = $this->make($concrete);
        }

        // If we defined any extenders for this type, we'll need to spin through them
        // and apply them to the object being built. This allows for the extension
        // of services, such as changing configuration or decorating the object.
        foreach ($this->getExtenders($abstract) as $extender) {
            $object = $extender($object, $this);
        }

        // If the requested type is registered as a singleton we'll want to cache off
        // the instances in "memory" so we can return it later without creating an
        // entirely new instance of an object on each subsequent request for it.
        if ($this->isShared($abstract) && ! $needsContextualBuild) {
            $this->instances[$abstract] = $object;
        }

        $this->fireResolvingCallbacks($abstract, $object);

        // Before returning, we will also set the resolved flag to "true" and pop off
        // the parameter overrides for this build. After those two things are done
        // we will be ready to return back the fully constructed class instance.
        $this->resolved[$abstract] = true;

        array_pop($this->with);

        return $object;
    }
917494
private function failureException(MethodInvocation $invocation, FailureInterface $failure)
    {
        $class = new \ReflectionClass($invocation->getThis());
        $className = $class->implementsInterface(WeavedInterface::class) ? $class->getParentClass()->name : $class->name;
        $errors = json_encode($failure->getMessages());
        $msg = sprintf('%s::%s() %s', $className, $invocation->getMethod()->name, $errors);

        return new InvalidArgumentException($msg, 400);
    }
941729
public function load($class, $type = null)
    {
        if (!class_exists($class)) {
            throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
        }

        $class = new \ReflectionClass($class);
        if ($class->isAbstract()) {
            throw new \InvalidArgumentException(sprintf('Annotations from class "%s" cannot be read as it is abstract.', $class->getName()));
        }

        $globals = $this->getGlobals($class);

        $collection = new RouteCollection();
        $collection->addResource(new FileResource($class->getFileName()));

        foreach ($class->getMethods() as $method) {
            $this->defaultRouteIndex = 0;
            foreach ($this->reader->getMethodAnnotations($method) as $annot) {
                if ($annot instanceof $this->routeAnnotationClass) {
                    $this->addRoute($collection, $annot, $globals, $class, $method);
                }
            }
        }

        if (0 === $collection->count() && $class->hasMethod('__invoke')) {
            $globals = $this->resetGlobals();
            foreach ($this->reader->getClassAnnotations($class) as $annot) {
                if ($annot instanceof $this->routeAnnotationClass) {
                    $this->addRoute($collection, $annot, $globals, $class, $class->getMethod('__invoke'));
                }
            }
        }

        return $collection;
    }
763394
public function getResolver()/*# : ParameterInterface */
    {
        if (!$this->hasResolver()) {
            throw new NotFoundException(
                Message::get(Message::PARAM_RESOLVER_MISS),
                Message::PARAM_RESOLVER_MISS
            );
        }
        return $this->resolver;
    }
1359468
public function buildClassMethods(StructureInterface $structure, TypeInterface $source_type, TypeInterface $target_type, array &$result)
    {
        $namespace = $structure->getNamespace();

        if ($namespace) {
            $namespace = '\\' . ltrim($namespace, '\\');
        }

        $this->buildGetFinderMethod($structure, $source_type, $target_type, $namespace, $result);

        $result[] = '';
        $result[] = '    /**';
        $result[] = '     * Return ' . Inflector::singularize($source_type->getName()) . ' ' . $this->getName() . '.';
        $result[] = '     *';
        $result[] = '     * @return ' . $this->getInstanceClassFrom($namespace, $target_type) . '[]';
        $result[] = '     */';
        $result[] = "    public function get{$this->getClassifiedAssociationName()}()";
        $result[] = '    {';
        $result[] = '        return $this->' . $this->getFinderMethodName() . '()->all();';
        $result[] = '    }';

        $result[] = '';
        $result[] = '    /**';
        $result[] = '     * Return ' . Inflector::singularize($source_type->getName()) . ' ' . Inflector::singularize($this->getName()) . ' ID-s.';
        $result[] = '     *';
        $result[] = '     * @return int[]';
        $result[] = '     */';
        $result[] = '    public function get' . Inflector::classify(Inflector::singularize($this->getName())) . 'Ids()';
        $result[] = '    {';
        $result[] = '        return $this->' . $this->getFinderMethodName() . '()->ids();';
        $result[] = '    }';

        $result[] = '';
        $result[] = '    /**';
        $result[] = '     * Return number of ' . Inflector::singularize($source_type->getName()) . ' ' . $this->getName() . '.';
        $result[] = '     *';
        $result[] = '     * @return int';
        $result[] = '     */';
        $result[] = "    public function count{$this->getClassifiedAssociationName()}()";
        $result[] = '    {';
        $result[] = '        return $this->' . $this->getFinderMethodName() . '()->count();';
        $result[] = '    }';

        $this->buildAddRelatedObjectMethod($structure, $source_type, $target_type, $namespace, $result);
        $this->buildRemoveRelatedObjectMethod($structure, $source_type, $target_type, $namespace, $result);
        $this->buildClearRelatedObjectsMethod($structure, $source_type, $target_type, $namespace, $result);
    }
828975
public function resolveMethodDependencies(array $parameters, ReflectionFunctionAbstract $reflector)
	{
		foreach ($reflector->getParameters() as $key => $parameter)
		{
			// If the parameter has a type-hinted class, we will check to see if it is already in
			// the list of parameters. If it is we will just skip it as it is probably a model
			// binding and we do not want to mess with those; otherwise, we resolve it here.
			$class = $parameter->getClass();

			if ($class && ! $this->alreadyInParameters($class->name, $parameters))
			{
				array_splice(
					$parameters, $key, 0, [$this->container->make($class->name)]
				);
			}
		}

		return $parameters;
	}
179131
private function classToNode(core_kernel_classes_Class $class, core_kernel_classes_Class $parent = null) {
        $returnValue = $this->buildClassNode($class, $parent);

        // allow the class to be opened if it contains either instances or subclasses
        $subclasses = $this->getSubClasses($class);

        if($this->showResources) {
            $options = array_merge(['recursive' => false], $this->optionsFilter);
            $queryBuilder = $this->getQueryBuilder($class, $this->propertyFilter, $options);
            $search = $this->getSearchService();
            $search->setLanguage($queryBuilder, \common_session_SessionManager::getSession()->getDataLanguage());
            $instancesCount = $search->getGateway()->count($queryBuilder);

            if ($instancesCount > 0 || count($subclasses) > 0) {
                if (in_array($class->getUri(), $this->openNodes)) {
                    $returnValue['state']	= 'open';
                    $returnValue['children'] = $this->buildChildNodes($class, $subclasses);
                } else {
                    $returnValue['state']	= 'closed';
                }

                // only show the resources count if we allow resources to be viewed
                $returnValue['count'] = $instancesCount;
            }
        } else {
            if(count($subclasses) > 0) {
                if (in_array($class->getUri(), $this->openNodes)) {
                    $returnValue['state'] = 'open';
                    $returnValue['children'] = $this->buildChildNodes($class, $subclasses);
                } else {
                    $returnValue['state'] = 'closed';
                }

                $returnValue['count'] = 0;
            }
        }
        return $returnValue;
    }
169142
static function getAnnotationParam($name, $param, $class, $method = NULL, $default = NULL)
	{
		$annotation = self::getAnnotation($name, $class, $method, TRUE);

		return NULL === $annotation || !isset($annotation->{$param})
			? $default
			: $annotation->{$param};
	}
1001086
public function build(ReflectionClass $reflectionClass, Service $annotation, Definition $definition)
    {
        /** @var Definition $definition */
        [$serviceId, $definition] = parent::build($reflectionClass, $annotation, $definition);

        $definition->setPublic(false);
        $this->container->setDefinition($serviceId, $definition);

        /** @var CompilerPassInterface $compilerPass */
        $compilerPass = $this->container->get($serviceId);
        $this->container->addCompilerPass(
            $compilerPass,
            $annotation->type,
            $annotation->priority
        );

        return [$serviceId, $definition];
    }