Skip to content

Commit

Permalink
Add new microsoft/tolerant-php-parser importer.
Browse files Browse the repository at this point in the history
  • Loading branch information
drupol committed Mar 4, 2020
1 parent 968e58e commit 50b7f4f
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 0 deletions.
1 change: 1 addition & 0 deletions composer.json
Expand Up @@ -25,6 +25,7 @@
"friends-of-phpspec/phpspec-code-coverage": "^4.3.2",
"graphp/graphviz": "^0.2",
"infection/infection": "^0.13.6 || ^0.15.0",
"microsoft/tolerant-php-parser": "^0.0.20",
"nikic/php-parser": "^4.3",
"phpbench/phpbench": "^0.16.10",
"phpspec/phpspec": "^5.1.2 || ^6.1.1",
Expand Down
44 changes: 44 additions & 0 deletions spec/loophp/phptree/Importer/MicrosoftTolerantPhpParserSpec.php
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

namespace spec\loophp\phptree\Importer;

use loophp\phptree\Importer\MicrosoftTolerantPhpParser;
use loophp\phptree\Node\AttributeNodeInterface;
use Microsoft\PhpParser\Parser;
use PhpSpec\ObjectBehavior;

class MicrosoftTolerantPhpParserSpec extends ObjectBehavior
{
public function it_can_import(): void
{
$file = __DIR__ . '/../../../../src/Node/Node.php';

$parser = new Parser();
$ast = $parser->parseSourceFile(file_get_contents($file));

$this
->import($ast)
->shouldImplement(AttributeNodeInterface::class);

$this
->import($ast)
->count()
->shouldReturn(582);

$file = __DIR__ . '/../../../../tests/sample.php';

$ast = $parser->parseSourceFile(file_get_contents($file));

$this
->import($ast)
->count()
->shouldReturn(112);
}

public function it_is_initializable(): void
{
$this->shouldHaveType(MicrosoftTolerantPhpParser::class);
}
}
52 changes: 52 additions & 0 deletions src/Importer/MicrosoftTolerantPhpParser.php
@@ -0,0 +1,52 @@
<?php

declare(strict_types=1);

namespace loophp\phptree\Importer;

use Exception;
use loophp\phptree\Node\AttributeNode;
use loophp\phptree\Node\AttributeNodeInterface;
use loophp\phptree\Node\NodeInterface;
use Microsoft\PhpParser\Node;
use Microsoft\PhpParser\Node\SourceFileNode;

/**
* Class MicrosoftTolerantPhpParser.
*/
final class MicrosoftTolerantPhpParser implements ImporterInterface
{
/**
* @param SourceFileNode $data
*
* @throws Exception
*
* @return \loophp\phptree\Node\NodeInterface
*/
public function import($data): NodeInterface
{
return $this->parseNode($data, (new AttributeNode(['label' => 'root'])));
}

/**
* @param \Microsoft\PhpParser\Node $astNode
* @param \loophp\phptree\Node\AttributeNodeInterface $parent
*
* @return \loophp\phptree\Node\AttributeNodeInterface
*/
private function parseNode(Node $astNode, AttributeNodeInterface $parent): AttributeNodeInterface
{
$node = new AttributeNode([
'label' => $astNode->getNodeKindName(),
'astNode' => $astNode,
]);

$parent->add($node);

foreach ($astNode->getChildNodes() as $child) {
$this->parseNode($child, $node);
}

return $parent;
}
}

0 comments on commit 50b7f4f

Please sign in to comment.