NodeCollection.php 6.09 KB
Newer Older
1 2 3 4 5
<?php

declare(strict_types=1);

/*
6
 * This file is part of the Application mapper application,
7 8 9 10 11 12 13 14 15 16 17
 * following the Explicit Architecture principles.
 *
 * @link https://herbertograca.com/2017/11/16/explicit-architecture-01-ddd-hexagonal-onion-clean-cqrs-how-i-put-it-all-together
 * @link https://herbertograca.com/2018/07/07/more-than-concentric-layers/
 *
 * (c) Herberto Graça
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

18
namespace Hgraca\AppMapper\Infrastructure\Parser\NikicPhpParser;
19

20 21 22
use Hgraca\AppMapper\Infrastructure\Parser\NikicPhpParser\Exception\AstNodeNotFoundException;
use Hgraca\AppMapper\Infrastructure\Parser\NikicPhpParser\Exception\UnitNotFoundInNamespaceException;
use Hgraca\AppMapper\Infrastructure\Parser\NikicPhpParser\Visitor\ParentConnectorVisitor;
23 24
use Hgraca\AppMapper\Infrastructure\Parser\NikicPhpParser\Visitor\TypeResolverInjectorVisitor;
use Hgraca\AppMapper\Infrastructure\Parser\NikicPhpParser\Visitor\TypeResolverVisitor;
25 26 27 28 29 30 31 32 33 34 35 36 37
use Hgraca\PhpExtension\String\JsonEncoder;
use PhpParser\JsonDecoder;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Interface_;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\Node\Stmt\Trait_;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitor\NameResolver;
use PhpParser\ParserFactory;
use function array_key_exists;
use function array_merge;
use function array_values;
38
use function uniqid;
39 40 41

final class NodeCollection
{
42 43 44 45 46
    /**
     * @var string
     */
    private $name;

47 48 49 50 51 52 53 54 55 56 57 58
    /** @var Namespace_[] */
    private $nodeList = [];

    private function __construct()
    {
    }

    public function serializeToFile(string $filePath, bool $prettyPrint = false): void
    {
        file_put_contents($filePath, $this->toSerializedAst($prettyPrint));
    }

Herberto Graca's avatar
Herberto Graca committed
59 60 61 62 63 64 65 66
    public static function constructFromNodeCollectionList(self ...$nodeCollectionList): self
    {
        $self = new self();
        $self->addCollections(...$nodeCollectionList);

        return $self;
    }

67
    public static function constructFromFolder(string $folder, string $name = ''): self
68 69 70 71 72 73 74 75 76
    {
        $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($folder));
        $files = new \RegexIterator($files, '/\.php$/');
        $nodeList = [];
        foreach ($files as $file) {
            $nodeList[] = self::parse(file_get_contents($file->getPathName()));
        }

        $self = new self();
77
        $self->name = $name ?: uniqid('', true);
78
        $self->nodeList = !empty($nodeList) ? array_merge(...$nodeList) : [];
79 80 81 82

        return $self;
    }

83
    public static function unserializeFromFile(string $filePath, string $name = ''): self
84 85
    {
        $self = self::fromSerializedAst(file_get_contents($filePath));
86
        $self->name = $name ?: uniqid('', true);
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114

        return $self;
    }

    public function hasAstNode(string $fqcn): bool
    {
        $key = trim($fqcn, '\\');
        if (!array_key_exists($key, $this->nodeList)) {
            return false;
        }

        return true;
    }

    public function getAstNode(string $fqcn): Node
    {
        $key = trim($fqcn, '\\');
        if (!array_key_exists($key, $this->nodeList)) {
            throw new AstNodeNotFoundException($key);
        }

        return self::getNamespaceUnitNode($this->nodeList[$key]);
    }

    public function toArray(): array
    {
        return $this->nodeList;
    }
115 116 117 118 119

    public function getName(): string
    {
        return $this->name;
    }
120

Herberto Graca's avatar
Herberto Graca committed
121 122 123 124
    public function enhance(): void
    {
        $traverser = new NodeTraverser();
        $traverser->addVisitor(new NameResolver(null, ['preserveOriginalNames' => true, 'replaceNodes' => false]));
125
        $traverser->addVisitor(new ParentConnectorVisitor());
126 127 128
        $traverser->addVisitor(new TypeResolverInjectorVisitor($this));
        $traverser->traverse(array_values($this->nodeList));
    }
129

130 131
    public function resolveAllTypes(): void
    {
132
        $traverser = new NodeTraverser();
133 134
        $traverser->addVisitor(new TypeResolverVisitor());
        $traverser->traverse(array_values($this->nodeList));
Herberto Graca's avatar
Herberto Graca committed
135 136 137 138 139 140 141 142 143 144 145
    }

    private function addCollections(self ...$nodeCollectionList): void
    {
        $newNodeList = [];
        foreach ($nodeCollectionList as $nodeCollection) {
            $newNodeList[] = $nodeCollection->nodeList;
        }
        $this->nodeList = array_merge($this->nodeList, ...$newNodeList);
    }

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
    private static function fromSerializedAst(string $serializedAst): self
    {
        $self = new self();

        $self->nodeList = (new JsonDecoder())->decode($serializedAst);

        return $self;
    }

    private function toSerializedAst(bool $prettyPrint = false): string
    {
        $jsonEncoder = JsonEncoder::construct();

        if ($prettyPrint) {
            $jsonEncoder->prettyPrint();
        }

        return $jsonEncoder->encode($this->nodeList);
    }

    private static function parse(string $code): array
    {
        $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);

        foreach ($parser->parse($code) as $node) {
            if (!$node instanceof Namespace_) {
                continue;
            }
            $namespaceNode = $node;
            $namespace = $namespaceNode->name->toCodeString();
            $className = self::getUnitName($namespaceNode);

            return [$namespace . '\\' . $className => $namespaceNode];
        }

        return [];
    }

    private static function getUnitName(Namespace_ $namespaceNode): string
    {
        return self::getNamespaceUnitNode($namespaceNode)->name->toString();
    }

    /**
     * @return Class_|Interface_|Trait_
     */
    private static function getNamespaceUnitNode(Namespace_ $namespaceNode): Node
    {
        foreach ($namespaceNode->stmts as $stmt) {
            if (
                $stmt instanceof Class_
                || $stmt instanceof Interface_
                || $stmt instanceof Trait_
            ) {
                return $stmt;
            }
        }
        throw new UnitNotFoundInNamespaceException(
            'Could not find a class in the namespace ' . $namespaceNode->name->toCodeString()
        );
    }
}