Skip to content

Verify PHP classes #38

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 23, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
"repositories": [
{
"type": "git",
"url": "https://github.com/weaverryan/docs-builder"
"url": "https://github.com/symfony-tools/docs-builder"
}
],
"minimum-stability": "dev",
Expand Down
8 changes: 6 additions & 2 deletions config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ services:

_instanceof:
SymfonyTools\CodeBlockChecker\Service\CodeValidator\Validator:
tags:
- 'app.code_validator'
tags: ['app.code_validator']
SymfonyTools\CodeBlockChecker\Service\CodeRunner\Runner:
tags: ['app.code_runner']

SymfonyTools\CodeBlockChecker\:
resource: '../src/'
Expand All @@ -21,3 +22,6 @@ services:

SymfonyTools\CodeBlockChecker\Service\CodeValidator:
arguments: [!tagged_iterator app.code_validator]

SymfonyTools\CodeBlockChecker\Service\CodeRunner:
arguments: [!tagged_iterator app.code_runner]
10 changes: 5 additions & 5 deletions src/Command/CheckDocsCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
use SymfonyTools\CodeBlockChecker\Issue\IssueCollection;
use SymfonyTools\CodeBlockChecker\Listener\CodeNodeCollector;
use SymfonyTools\CodeBlockChecker\Service\Baseline;
use SymfonyTools\CodeBlockChecker\Service\CodeNodeRunner;
use SymfonyTools\CodeBlockChecker\Service\CodeRunner;
use SymfonyTools\CodeBlockChecker\Service\CodeValidator;

class CheckDocsCommand extends Command
Expand All @@ -34,14 +34,14 @@ class CheckDocsCommand extends Command
private CodeNodeCollector $collector;
private CodeValidator $validator;
private Baseline $baseline;
private CodeNodeRunner $codeNodeRunner;
private CodeRunner $codeRunner;

public function __construct(CodeValidator $validator, Baseline $baseline, CodeNodeRunner $codeNodeRunner)
public function __construct(CodeValidator $validator, Baseline $baseline, CodeRunner $codeRunner)
{
parent::__construct(self::$defaultName);
$this->validator = $validator;
$this->baseline = $baseline;
$this->codeNodeRunner = $codeNodeRunner;
$this->codeRunner = $codeRunner;
}

protected function configure()
Expand Down Expand Up @@ -88,7 +88,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
// Verify code blocks
$issues = $this->validator->validateNodes($this->collector->getNodes());
if ($applicationDir = $input->getOption('symfony-application')) {
$issues->append($this->codeNodeRunner->runNodes($this->collector->getNodes(), $applicationDir));
$issues->append($this->codeRunner->runNodes($this->collector->getNodes(), $applicationDir));
}

if ($baselineFile = $input->getOption('generate-baseline')) {
Expand Down
43 changes: 43 additions & 0 deletions src/Service/CodeRunner.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

declare(strict_types=1);

namespace SymfonyTools\CodeBlockChecker\Service;

use Doctrine\RST\Nodes\CodeNode;
use SymfonyTools\CodeBlockChecker\Issue\IssueCollection;
use SymfonyTools\CodeBlockChecker\Service\CodeRunner\Runner;

/**
* Run a Code Node inside a real application.
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class CodeRunner
{
/**
* @var iterable<Runner>
*/
private $runners;

/**
* @param iterable<Runner> $runners
*/
public function __construct(iterable $runners)
{
$this->runners = $runners;
}

/**
* @param list<CodeNode> $nodes
*/
public function runNodes(array $nodes, string $applicationDirectory): IssueCollection
{
$issues = new IssueCollection();
foreach ($this->runners as $runner) {
$runner->run($nodes, $issues, $applicationDirectory);
}

return $issues;
}
}
113 changes: 113 additions & 0 deletions src/Service/CodeRunner/ClassExist.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
<?php

namespace SymfonyTools\CodeBlockChecker\Service\CodeRunner;

use Doctrine\RST\Nodes\CodeNode;
use Symfony\Component\Process\Process;
use SymfonyTools\CodeBlockChecker\Issue\Issue;
use SymfonyTools\CodeBlockChecker\Issue\IssueCollection;

/**
* Verify that any reference to a PHP class is actually a real class.
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class ClassExist implements Runner
{
/**
* @param list<CodeNode> $nodes
*/
public function run(array $nodes, IssueCollection $issues, string $applicationDirectory): void
{
$classes = [];
foreach ($nodes as $node) {
$classes = array_merge($classes, $this->getClasses($node));
}

$this->testClasses($classes, $issues, $applicationDirectory);
}

private function getClasses(CodeNode $node): array
{
$language = $node->getLanguage() ?? 'php';
if (!in_array($language, ['php', 'php-symfony', 'php-standalone', 'php-annotations'])) {
return [];
}

$classes = [];
foreach (explode("\n", $node->getValue()) as $i => $line) {
$matches = [];
if (0 !== strpos($line, 'use ') || !preg_match('|^use (.*\\\.*); *?$|m', $line, $matches)) {
continue;
}

$class = $matches[1];
if (false !== $pos = strpos($class, ' as ')) {
$class = substr($class, 0, $pos);
}

if (false !== $pos = strpos($class, 'function ')) {
continue;
}

$explode = explode('\\', $class);
if (
'App' === $explode[0] || 'Acme' === $explode[0]
|| (3 === count($explode) && 'Symfony' === $explode[0] && ('Component' === $explode[1] || 'Config' === $explode[1]))
) {
continue;
}

$classes[] = ['class' => $class, 'line' => $i + 1, 'node' => $node];
}

return $classes;
}

/**
* Make sure PHP classes exists in the application directory.
*
* @param array{int, array{ class: string, line: int, node: CodeNode } } $classes
*/
private function testClasses(array $classes, IssueCollection $issues, string $applicationDirectory): void
{
$fileBody = '';
foreach ($classes as $i => $data) {
$fileBody .= sprintf('%s => isLoaded("%s"),', $i, $data['class'])."\n";
}

file_put_contents($applicationDirectory.'/class_exist.php', strtr('<?php
require __DIR__.\'/vendor/autoload.php\';

function isLoaded($class) {
return class_exists($class) || interface_exists($class) || trait_exists($class);
}

echo json_encode([ARRAY_CONTENT]);

', ['ARRAY_CONTENT' => $fileBody]));

$process = new Process(['php', 'class_exist.php'], $applicationDirectory);
$process->run();

if (!$process->isSuccessful()) {
// TODO handle this
return;
}

$output = $process->getOutput();
try {
$results = json_decode($output, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
// TODO handle this
return;
}

foreach ($classes as $i => $data) {
if (!$results[$i]) {
$text = sprintf('Class, interface or trait with name "%s" does not exist', $data['class']);
$issues->addIssue(new Issue($data['node'], $text, 'Missing class', $data['node']->getEnvironment()->getCurrentFileName(), $data['line']));
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?php

namespace SymfonyTools\CodeBlockChecker\Service;
namespace SymfonyTools\CodeBlockChecker\Service\CodeRunner;

use Doctrine\RST\Nodes\CodeNode;
use Symfony\Component\Filesystem\Filesystem;
Expand All @@ -13,24 +13,23 @@
*
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
class CodeNodeRunner
class ConfigurationRunner
{
/**
* @param list<CodeNode> $nodes
*/
public function runNodes(array $nodes, string $applicationDirectory): IssueCollection
public function run(array $nodes, IssueCollection $issues, string $applicationDirectory): void
{
$issues = new IssueCollection();
foreach ($nodes as $node) {
$this->processNode($node, $issues, $applicationDirectory);
}

return $issues;
}

private function processNode(CodeNode $node, IssueCollection $issues, string $applicationDirectory): void
{
$file = $this->getFile($node);
$explodedNode = explode("\n", $node->getValue());
$file = $this->getFile($node, $explodedNode);

if ('config/packages/' !== substr($file, 0, 16)) {
return;
}
Expand All @@ -45,13 +44,13 @@ private function processNode(CodeNode $node, IssueCollection $issues, string $ap
}

// Write config
file_put_contents($fullPath, $this->getNodeContents($node));
file_put_contents($fullPath, $this->getNodeContents($node, $explodedNode));

// Clear cache
$filesystem->remove($applicationDirectory.'/var/cache');

// Warmup and log errors
$this->warmupCache($node, $issues, $applicationDirectory);
$this->warmupCache($node, $issues, $applicationDirectory, count($explodedNode) - 1);
} finally {
// Remove added file and restore original
$filesystem->remove($fullPath);
Expand All @@ -62,20 +61,19 @@ private function processNode(CodeNode $node, IssueCollection $issues, string $ap
}
}

private function warmupCache(CodeNode $node, IssueCollection $issues, string $applicationDirectory): void
private function warmupCache(CodeNode $node, IssueCollection $issues, string $applicationDirectory, int $numberOfLines): void
{
$process = new Process(['php', 'bin/console', 'cache:warmup', '--env', 'dev'], $applicationDirectory);
$process->run();
if ($process->isSuccessful()) {
return;
}

$issues->addIssue(new Issue($node, trim($process->getErrorOutput()), 'Cache Warmup', $node->getEnvironment()->getCurrentFileName(), count(explode("\n", $node->getValue())) - 1));
$issues->addIssue(new Issue($node, trim($process->getErrorOutput()), 'Cache Warmup', $node->getEnvironment()->getCurrentFileName(), $numberOfLines));
}

private function getFile(CodeNode $node): string
private function getFile(CodeNode $node, array $contents): string
{
$contents = explode("\n", $node->getValue());
$regex = match ($node->getLanguage()) {
'php' => '|^// ?([a-z1-9A-Z_\-/]+\.php)$|',
'yaml' => '|^# ?([a-z1-9A-Z_\-/]+\.yaml)$|',
Expand All @@ -90,20 +88,17 @@ private function getFile(CodeNode $node): string
return $matches[1];
}

private function getNodeContents(CodeNode $node): string
private function getNodeContents(CodeNode $node, array $contents): string
{
$language = $node->getLanguage();
if ('php' === $language) {
return '<?php'."\n".$node->getValue();
}

if ('xml' === $language) {
$contents = explode("\n", $node->getValue());
unset($contents[0]);

return implode("\n", $contents);
}

return $node->getValue();
return implode("\n", $contents);
}
}
14 changes: 14 additions & 0 deletions src/Service/CodeRunner/Runner.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace SymfonyTools\CodeBlockChecker\Service\CodeRunner;

use Doctrine\RST\Nodes\CodeNode;
use SymfonyTools\CodeBlockChecker\Issue\IssueCollection;

interface Runner
{
/**
* @param list<CodeNode> $nodes
*/
public function run(array $nodes, IssueCollection $issues, string $applicationDirectory): void;
}
4 changes: 4 additions & 0 deletions src/Service/CodeValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace SymfonyTools\CodeBlockChecker\Service;

use Doctrine\RST\Nodes\CodeNode;
use SymfonyTools\CodeBlockChecker\Issue\IssueCollection;
use SymfonyTools\CodeBlockChecker\Service\CodeValidator\Validator;

Expand All @@ -27,6 +28,9 @@ public function __construct(iterable $validators)
$this->validators = $validators;
}

/**
* @param list<CodeNode> $nodes
*/
public function validateNodes(array $nodes): IssueCollection
{
$issues = new IssueCollection();
Expand Down
1 change: 1 addition & 0 deletions tests/Fixtures/example-application/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
class_exist.php
11 changes: 11 additions & 0 deletions tests/Fixtures/example-application/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"name": "example/app",
"type": "project",
"license": "MIT",
"require": {},
"autoload": {
"psr-4": {
"Example\\App\\": "src/"
}
}
}
7 changes: 7 additions & 0 deletions tests/Fixtures/example-application/src/Foobar.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

namespace Example\App;

class Foobar
{
}
7 changes: 7 additions & 0 deletions tests/Fixtures/example-application/vendor/autoload.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<?php

// Fake autoloader.

foreach (glob(__DIR__.'/../src/**') as $path) {
require_once $path;
}
13 changes: 13 additions & 0 deletions tests/Service/CodeRunner/BaseCodeRunnerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace SymfonyTools\CodeBlockChecker\Tests\Service\CodeRunner;

use PHPUnit\Framework\TestCase;

abstract class BaseCodeRunnerTest extends TestCase
{
protected function getApplicationDirectory(): string
{
return dirname(__DIR__, 2).'/Fixtures/example-application';
}
}
Loading