IdentifierContextFactory::createFromPhpCode()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 2 Features 1
Metric Value
eloc 10
c 3
b 2
f 1
dl 0
loc 13
rs 9.9332
cc 2
nc 2
nop 1
1
<?php
2
3
/**
4
 * This file is part of the sj-i/phpdoc-type-reader package.
5
 *
6
 * (c) sji <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace PhpDocTypeReader\Context;
15
16
use PhpParser\NodeTraverser;
17
use PhpParser\NodeVisitor\NameResolver;
18
use PhpParser\ParserFactory;
19
20
final class IdentifierContextFactory
21
{
22
    public function createFromPhpCode(string $php_code): IdentifierContext
23
    {
24
        $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
25
        $statements = $parser->parse($php_code);
26
        if (is_null($statements)) {
27
            throw new \LogicException('parse error');
28
        }
29
        $traverser = new NodeTraverser();
30
        $name_resolver = new NameResolver();
31
        $traverser->addVisitor($name_resolver);
32
        $traverser->traverse($statements);
33
        $name_context = $name_resolver->getNameContext();
34
        return new PhpParserIdentifierContext($name_context);
35
    }
36
37
    public function createFromFile(string $file_name): IdentifierContext
38
    {
39
        return $this->createFromPhpCode(file_get_contents($file_name));
40
    }
41
}
42