Get all use statements from class

@param \ReflectionClass $class

@return array
160642
private function getAllUseStatementsMarkedAsAnnotation(\ReflectionClass $class): array
    {
        $tokens = \token_get_all(\file_get_contents($class->getFileName()));

        $uses = [];
        $buffer = '';
        $startUseParse = false;

        foreach ($tokens as $token) {
            if (\is_scalar($token)) {
                // Single element
                if ($token == ';' || $token = ',') {
                    if ($startUseParse) {
                        // Add "use" statement to collection
                        $uses[] = trim($buffer);
                        // Clear buffer
                        $buffer = ''; // Clear buffer

                        if ($token == ';') {
                            // Stop parse "use"
                            $startUseParse = false;
                        }
                    }
                }

                continue;
            }

            $type = $token[0];
            $value = $token[1];

            if (\in_array($type, [T_ABSTRACT, T_CLASS, T_INTERFACE, T_TRAIT])) {
                // Start class or interface or trait
                break;
            }

            if ($type == T_USE) {
                $startUseParse = true;
                continue;
            }

            if ($startUseParse) {
                $buffer .= $value;
            }
        }

        $useFiltering = function ($class, $searchChild = true) use (&$useFiltering) {
            if (!$class) {
                return false;
            }

            $parts = \explode(' as ', $class, 2);
            $class = $parts[0];

            try {
                $reflection = new \ReflectionClass($class);
            } catch (\ReflectionException $e) {
                if ($searchChild) {
                    foreach (\get_declared_classes() as $declaredClass) {
                        if (\strpos($declaredClass, $class) === 0) {
                            if (true === $useFiltering($declaredClass, false)) {
                                return true;
                            }
                        }
                    }
                }

                return false;
            }

            if ($reflection->getName() == Transactional::class) {
                return false;
            }

            return \strpos($reflection->getDocComment(), '@Annotation') !== false;
        };

        $uses = \array_filter($uses, $useFiltering);

        return $uses;
    }
874063
protected function getDefineDatas($class)
    {
        $class = is_string($class) ? $class : get_class($class);
        $id = $this->request->has('parent') && $this->request->parent != 0 ? $this->request->parent : $this->request->related;
        $parent = $class::findOrFail($id);
        $datas = $this->request->all();
        foreach($this->defineValues as $value) {
            $datas[$value] = $parent->$value;
        }
        return $datas;
    }
558260
private function extractProperties(\ReflectionClass $objectClass): array
    {
        return propertiesOf($objectClass, \ReflectionProperty::IS_PUBLIC)
                ->filter(function(\ReflectionProperty $property)
                        {
                            return !$property->isStatic()
                                && !annotationsOf($property)->contain('XmlIgnore');
                        }
                )->map(function(\ReflectionProperty $property)
                        {
                            return $this->createSerializerDelegate(
                                    annotationsOf($property),
                                    $property->getName()
                            );
                        }
                )->data();
    }
481550
public function fetchAllObj(string $class = null): array
    {
        if (!$this->wasExecuted()) {
            $this->exec();
        }

        if ($class === null) {
            return $this->getAdapter()->getStatement()->fetchAll(\PDO::FETCH_OBJ);
        } else {
            $objectInstances = [];

            foreach ($this->fetchAll() as $r) {
                $objectInstances[] = new $class($r);
            }

            return $objectInstances;
        }
    }
1252274
private static function createMethods(\ReflectionClass $class): string
    {
        $code    = '';
        $methods = [];
        $params  = [];
        $voidMethods = [];
        foreach (self::methodsOf($class) as $method) {
            $return = true;
            $returnType = determineReturnTypeOf($method);
            if ($returnType === ': void') {
                $voidMethods[$method->getName()] = $method->getName();
                $return = false;
            }

            $param = paramsOf($method);
            /* @var $method \ReflectionMethod */
            $code .= sprintf(
                    "    %s function %s(%s)%s {\n"
                  . "        %s\$this->handleMethodCall('%s', func_get_args(), %s);\n"
                  . "    }\n",
                    ($method->isPublic() ? 'public' : 'protected'),
                    $method->getName(),
                    $param['string'],
                    $returnType,
                    $return ? 'return ' : '',
                    $method->getName(),
                    self::shouldReturnSelf($class, $method) ? 'true' : 'false'
            );
            $methods[] = "'" . $method->getName() . "' => '" . $method->getName() . "'";
            $params[$method->getName()] = $param['names'];
        }

        return $code . sprintf(
                "\n    private \$_allowedMethods = [%s];\n",
                join(', ', $methods)
        ) . sprintf(
                "\n    private \$_methodParams = %s;\n",
                var_export($params, true)
        ) . sprintf(
                "\n    private \$_voidMethods = %s;\n",
                var_export($voidMethods, true)
        );
    }
674903
public static function getControllerMethods($class)
    {
        if (!class_exists($class)) {
            throw new TaskManagerException('class ' . $class . ' not found');
        }
        $class_methods = get_class_methods($class);
        if ($parent_class = get_parent_class($class)) {
            $parent_class_methods = get_class_methods($parent_class);
            return array_diff($class_methods, $parent_class_methods);
        }
        return $class_methods;
    }
992200
public function getConstants(): array
    {
        // Check cache.
        if (null === $this->constants) {
            $tokens          = $this->getTokenStream();
            $this->constants = [];

            // Fetch start of class so we do not
            // include use statements that import traits.
            $class = $this->getClassNameLocation();

            // Find all the use statements and parse them one by one
            // and then add them to the use_statements cache.
            $loc = 0;
            while (($loc = $tokens->scan($loc, [T_CONST])) && $loc < $class) {
                $this->constants[] = $this->parseConst($loc++);
            }
        }

        return $this->constants;
    }
287750
public function parseClass(\ReflectionClass $class)
    {
        if (false === $filename = $class->getFilename()) {
            return array();
        }

        $content = $this->getFileContent($filename, $class->getStartLine());
        $namespace = str_replace('\\', '\\\\', $class->getNamespaceName());
        $content = preg_replace('/^.*?(\bnamespace\s+' . $namespace . '\s*[;{].*)$/s', '\\1', $content);
        $this->tokens = token_get_all('<?php ' . $content);
        $this->numTokens = count($this->tokens);
        $this->pointer = 0;

        $statements = $this->parseUseStatements($class->getNamespaceName());

        return $statements;
    }
396014
private function getVersions($class)
    {
        $versions = [
            'versions' => [
                '1.0' => $class
            ],
            'latest'   => '1.0',
            'current'  => '1.0'
        ];

        if (method_exists($class, 'getAllVersions')) {
            // all versions
            $interfaceVersions = $class::getAllVersions();
            if (count($interfaceVersions) > 0) {
                $versions = ['versions' => $interfaceVersions];
            }

            // current
            $interfaceCurrent = $class::getCurrentVersion();
            if (!empty($interfaceCurrent)) {
                $versions['current'] = $interfaceCurrent;
            } else {
                $ak = array_keys($versions['versions']);
                $versions['current'] = end($ak);
            }

            // latest
            $interfaceLatest = $class::getLatestVersion();
            if (!empty($interfaceLatest)) {
                $versions['latest'] = $interfaceLatest;
            } else {
                $ak = array_keys($versions['versions']);
                $versions['latest'] = end($ak);
            }
        }

        return $versions;
    }
59096
public function getPublicMethods($class)
    {
        if (!$class instanceof ClassDescriptor) {
            return [];
        }

        $methods = $class->getMagicMethods()
            ->merge($class->getInheritedMethods())
            ->merge($class->getMethods());

        return array_filter(
            $methods->getAll(),
            function (MethodDescriptor $method) {
                return $method->getVisibility() === 'public';
            }
        );
    }
932460
public static function getAncestors($class)
    {
        $rc = $class instanceof \ReflectionClass ? \ReflectionClass($class->getName()) : new \ReflectionClass($class);
        $ancestors = [];
        while ($parent = $rc->getParentClass()) {
            $ancestors[] = $parent->getName();
            $rc = $parent;
        }

        return $ancestors;
    }
1047760
protected function classUsesDeep($class)
    {
        $traits = [];

        // Get traits of all parent classes
        do {
            $traits = array_merge(class_uses($class), $traits);
        } while ($class = get_parent_class($class));

        // Get traits of all parent traits
        $traitsToSearch = $traits;
        while ( ! empty($traitsToSearch)) {
            $newTraits      = class_uses(array_pop($traitsToSearch));
            $traits         = array_merge($newTraits, $traits);
            $traitsToSearch = array_merge($newTraits, $traitsToSearch);
        };

        foreach ($traits as $trait => $same) {
            $traits = array_merge(class_uses($trait), $traits);
        }

        return array_unique($traits);
    }
824072
public function addUseStatementIfNecessary(string $class): string
    {
        $shortClassName = Str::getShortClassName($class);
        if ($this->isInSameNamespace($class)) {
            return $shortClassName;
        }

        $namespaceNode = $this->getNamespaceNode();

        $targetIndex = null;
        $addLineBreak = false;
        $lastUseStmtIndex = null;
        foreach ($namespaceNode->stmts as $index => $stmt) {
            if ($stmt instanceof Node\Stmt\Use_) {
                // I believe this is an array to account for use statements with {}
                foreach ($stmt->uses as $use) {
                    $alias = $use->alias ? $use->alias->name : $use->name->getLast();

                    // the use statement already exists? Don't add it again
                    if ($class === (string) $use->name) {
                        return $alias;
                    }

                    if ($alias === $shortClassName) {
                        // we have a conflicting alias!
                        // to be safe, use the fully-qualified class name
                        // everywhere and do not add another use statement
                        return '\\'.$class;
                    }
                }

                // if $class is alphabetically before this use statement, place it before
                // only set $targetIndex the first time you find it
                if (null === $targetIndex && Str::areClassesAlphabetical($class, (string) $stmt->uses[0]->name)) {
                    $targetIndex = $index;
                }

                $lastUseStmtIndex = $index;
            } elseif ($stmt instanceof Node\Stmt\Class_) {
                if (null !== $targetIndex) {
                    // we already found where to place the use statement

                    break;
                }

                // we hit the class! If there were any use statements,
                // then put this at the bottom of the use statement list
                if (null !== $lastUseStmtIndex) {
                    $targetIndex = $lastUseStmtIndex + 1;
                } else {
                    $targetIndex = $index;
                    $addLineBreak = true;
                }

                break;
            }
        }

        if (null === $targetIndex) {
            throw new \Exception('Could not find a class!');
        }

        $newUseNode = (new Builder\Use_($class, Node\Stmt\Use_::TYPE_NORMAL))->getNode();
        array_splice(
            $namespaceNode->stmts,
            $targetIndex,
            0,
            $addLineBreak ? [$newUseNode, $this->createBlankLineNode(self::CONTEXT_OUTSIDE_CLASS)] : [$newUseNode]
        );

        $this->updateSourceCodeFromNewStmts();

        return $shortClassName;
    }
653919
public function getUseStatements(): array
    {
        // Check cache.
        if (null === $this->use_statements) {
            $this->use_statements = [];

            // Fetch start of class so we do not
            // include use statements that import traits.
            $tokens = $this->getTokenStream();
            $class  = $this->getClassNameLocation();

            // Find all the use statements and parse them one by one
            // and then add them to the use_statements cache.
            $loc = 0;
            while (($loc = $tokens->scan($loc, [T_USE])) && $loc < $class) {
                [$alias, $use_statement] = $this->parseUse($loc++);
                if ($alias !== null) {
                    $this->use_statements[$alias] = $use_statement;
                } else {
                    $this->use_statements[] = $use_statement;
                }
            }
        }

        return $this->use_statements;
    }
1207889
private static function getProps($class)
    {
        if ($class == NULL) {
            return array();
        }
        $class = new \ReflectionClass($class);
        $properties = array_filter($class->getProperties(), function ($prop) use($class)
        {
            return $prop->getDeclaringClass()->name == $class->name;
        });
        return $properties;
    }
583913
public function fromReflection(ReflectionClass $reflectionClass) : array
    {
        $class      = new Class_($reflectionClass->getShortName());
        $statements = array($class);

        if ($parentClass = $reflectionClass->getParentClass()) {
            $class->extends = new FullyQualified($parentClass->getName());
        }

        $interfaces = array();

        foreach ($reflectionClass->getInterfaces() as $reflectionInterface) {
            $interfaces[] = new FullyQualified($reflectionInterface->getName());
        }

        $class->implements = $interfaces;

        foreach ($reflectionClass->getConstants() as $constant => $value) {
            $class->stmts[] = new ClassConst(
                array(new Const_($constant, BuilderHelpers::normalizeValue($value)))
            );
        }

        foreach ($reflectionClass->getProperties() as $reflectionProperty) {
            $class->stmts[] = $this->buildProperty($reflectionProperty);
        }

        foreach ($reflectionClass->getMethods() as $reflectionMethod) {
            $class->stmts[] = $this->buildMethod($reflectionMethod);
        }

        if (! $namespace = $reflectionClass->getNamespaceName()) {
            return $statements;
        }

        return array(new Namespace_(new Name(explode('\\', $namespace)), $statements));
    }
414550
public function fetchAllObj(string $class = null): array
    {
        if (!$this->wasExecuted()) {
            $this->exec();
        }

        if ($class === null) {
            return $this->getAdapter()->getStatement()->fetchAll(PDO::FETCH_OBJ);
        } else {
            $objects = [];
            foreach ($this->fetchAll() as $record) {
                $objects[] = new $class($record);
            }

            return $objects;
        }
    }