Skip to content
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
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ Packages can still keep custom implementations behind the same script names. CI

```bash
vendor/bin/qa cs
vendor/bin/qa lint:php
vendor/bin/qa lint:php --package=packages/example --exclude=tests/site/public
vendor/bin/qa cs:fix
vendor/bin/qa static-analysis
vendor/bin/qa tests
Expand All @@ -63,6 +65,15 @@ configured and referenced by `composer qa`.

## DevOps Usage

`lint:php` checks package PHP files with the interpreter running QA (`PHP_BINARY`),
without executing the files. It propagates syntax failures and the interpreter's
exit code. Dependency, generated-output and cache directories (`vendor`,
`node_modules`, `.git`, `var`, `build`, `phpstan-cache`, `test-results` and
`playwright-report`) and symlinks are excluded. Public PHP entrypoints are checked;
use repeatable `--exclude` options for additional package-relative directories.
Packages opt in through `"lint:php": "@php vendor/bin/qa lint:php"` and `@lint:php`
in `composer qa`. The aggregate `qa qa` command keeps its existing three gates.

CI jobs can keep their package-specific behavior simple:

```bash
Expand Down
2 changes: 2 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
"bin/qa"
],
"scripts": {
"lint:php": "@php bin/qa lint:php",
"cs": [
"Composer\\Config::disableProcessTimeout",
"@php bin/qa cs --strict"
Expand All @@ -58,6 +59,7 @@
],
"qa": [
"@php bin/qa doctor --strict",
"@lint:php",
"@cs",
"@static-analysis",
"@tests"
Expand Down
1 change: 1 addition & 0 deletions qa-adoption.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": 1,
"defaults": {
"required": [
"lint:php",
"cs",
"static-analysis",
"tests"
Expand Down
2 changes: 1 addition & 1 deletion src/Command/DoctorCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ private function qaRunsGate(string $gate, array $scripts): bool
{
$script = implode("\n", $this->scriptCommands($scripts, 'qa'));

if (str_contains($script, 'qa qa')) {
if (str_contains($script, 'qa qa') && in_array($gate, ['cs', 'static-analysis', 'tests'], true)) {
return true;
}

Expand Down
80 changes: 80 additions & 0 deletions src/Command/LintPhpCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

declare(strict_types=1);

namespace SymPress\Qa\Command;

use RecursiveCallbackFilterIterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use SplFileInfo;
use SymPress\Qa\Support\PackageContextFactory;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\Process;

final class LintPhpCommand extends AbstractPackageCommand
{
public function __construct(PackageContextFactory $contextFactory)
{
parent::__construct($contextFactory, 'lint:php');
}

protected function configure(): void
{
$this
->setDescription('Check package PHP syntax with the current PHP interpreter.')
->addOption('exclude', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Exclude a directory relative to the package root.')
->configurePackageOption();
}

protected function execute(InputInterface $input, OutputInterface $output): int
{
$root = $this->packageContext($input)->packageDir();
$excluded = $input->getOption('exclude');
if (!is_array($excluded)) {
return self::INVALID;
}
foreach ($excluded as $path) {
if (!is_string($path) || $path === '' || str_starts_with($path, '/') || in_array('..', explode('/', $path), true)) {
$output->writeln('<error>Exclusions must be non-empty package-relative directory paths without .. segments.</error>');

return self::INVALID;
}
}

$excluded = array_map(static fn (string $path): string => trim($path, '/'), $excluded);
$iterator = new RecursiveIteratorIterator(new RecursiveCallbackFilterIterator(
new RecursiveDirectoryIterator($root, RecursiveDirectoryIterator::SKIP_DOTS),
static function (SplFileInfo $file) use ($root, $excluded): bool {
if ($file->isLink()) {
return false;
}
if (!$file->isDir()) {
return true;
}

return !in_array($file->getFilename(), ['vendor', 'node_modules', '.git', 'var', 'build', 'phpstan-cache', 'test-results', 'playwright-report'], true)
&& !in_array(substr($file->getPathname(), strlen($root) + 1), $excluded, true);
},
));
$count = 0;
foreach ($iterator as $file) {
if (!$file instanceof SplFileInfo || !$file->isFile() || $file->getExtension() !== 'php') {
continue;
}
$process = new Process([PHP_BINARY, '-l', $file->getPathname()], $root);
$process->run();
if (!$process->isSuccessful()) {
$output->write($process->getOutput() . $process->getErrorOutput());

return $process->getExitCode() ?? self::FAILURE;
}
++$count;
}
$output->writeln(sprintf('PHP syntax checked: %d files.', $count));

return self::SUCCESS;
}
}
4 changes: 3 additions & 1 deletion src/Console/ApplicationFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace SymPress\Qa\Console;

use SymPress\Qa\Command\DoctorCommand;
use SymPress\Qa\Command\LintPhpCommand;
use SymPress\Qa\Command\QaCommand;
use SymPress\Qa\Command\ToolCommand;
use SymPress\Qa\Runner\ToolRunner;
Expand All @@ -20,7 +21,8 @@ public static function create(): Application
$configDiscovery = new ConfigDiscovery();
$toolRunner = new ToolRunner($configDiscovery);

$application = new Application('SymPress QA', '0.1.0');
$application = new Application('SymPress QA', '0.1.1');
$application->addCommand(new LintPhpCommand($contextFactory));
$application->addCommand(new ToolCommand('cs', 'Run PHP_CodeSniffer.', $contextFactory, $toolRunner));
$application->addCommand(new ToolCommand('cs:fix', 'Fix PHPCS violations with PHPCBF.', $contextFactory, $toolRunner));
$application->addCommand(new ToolCommand('static-analysis', 'Run PHPStan.', $contextFactory, $toolRunner));
Expand Down
16 changes: 16 additions & 0 deletions tests/Unit/Command/DoctorCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,22 @@ public function testMissingExplicitAdoptionFileAlwaysFails(): void
self::assertStringContainsString('is not readable', $tester->getDisplay());
}

public function testAggregateGateDoesNotImplicitlyRunTheOptInPhpLinter(): void
{
file_put_contents(
$this->workspace . '/composer.json',
'{"name":"sympress/fixture","scripts":{"qa":"@php vendor/bin/qa qa --strict","lint:php":"@php vendor/bin/qa lint:php"}}',
);
file_put_contents(
$this->workspace . '/qa-adoption.json',
'{"version":1,"defaults":{"required":["lint:php"],"planned":[]},"packages":{}}',
);
$tester = new CommandTester(ApplicationFactory::create()->find('doctor'));

self::assertSame(1, $tester->execute(['--package' => $this->workspace, '--strict' => true]));
self::assertStringContainsString('required gate is not referenced by composer qa: lint:php', $tester->getDisplay());
}

public function testEmptyPackageRequiredListOverridesDefaults(): void
{
file_put_contents(
Expand Down
90 changes: 90 additions & 0 deletions tests/Unit/Command/LintPhpCommandTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
<?php

declare(strict_types=1);

namespace SymPress\Qa\Tests\Unit\Command;

use PHPUnit\Framework\TestCase;
use SymPress\Qa\Console\ApplicationFactory;
use Symfony\Component\Console\Tester\CommandTester;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Process;

final class LintPhpCommandTest extends TestCase
{
private string $workspace;

protected function setUp(): void
{
$this->workspace = sys_get_temp_dir() . '/sympress-qa-lint space-' . bin2hex(random_bytes(8));
(new Filesystem())->mkdir($this->workspace);
file_put_contents($this->workspace . '/composer.json', '{"name":"sympress/fixture"}');
}

protected function tearDown(): void
{
(new Filesystem())->remove($this->workspace);
}

public function testChecksPublicEntrypointsWithoutExecutingThemAndExcludesDependencies(): void
{
foreach (['src', 'public', 'vendor', 'node_modules', 'var', 'build'] as $directory) {
(new Filesystem())->mkdir($this->workspace . '/' . $directory);
$php = in_array($directory, ['src', 'public'], true) ? '<?php throw new Exception("Must not execute");' : '<?php syntax error';
file_put_contents($this->workspace . '/' . $directory . '/index.php', $php);
}
$tester = new CommandTester(ApplicationFactory::create()->find('lint:php'));

self::assertSame(0, $tester->execute(['--package' => $this->workspace]));
self::assertStringContainsString('PHP syntax checked: 2 files.', $tester->getDisplay());
}

public function testReturnsTheInterpreterExitCodeForSyntaxErrors(): void
{
$file = $this->workspace . '/broken.php';
file_put_contents($file, '<?php syntax error');
$expected = new Process([PHP_BINARY, '-l', $file]);
$expected->run();
$tester = new CommandTester(ApplicationFactory::create()->find('lint:php'));

self::assertNotSame(0, $expected->getExitCode());
self::assertSame($expected->getExitCode(), $tester->execute(['--package' => $this->workspace]));
self::assertStringContainsString('broken.php', $tester->getDisplay());
self::assertStringNotContainsString('PHP syntax checked:', $tester->getDisplay());
}

public function testExcludesOnlyTheRequestedRelativeDirectory(): void
{
(new Filesystem())->mkdir($this->workspace . '/tests/site/public');
file_put_contents($this->workspace . '/tests/site/public/wordpress.php', '<?php syntax error');
file_put_contents($this->workspace . '/tests/site/router.php', '<?php return true;');
$tester = new CommandTester(ApplicationFactory::create()->find('lint:php'));

self::assertSame(0, $tester->execute(['--package' => $this->workspace, '--exclude' => ['tests/site/public']]));
self::assertStringContainsString('PHP syntax checked: 1 files.', $tester->getDisplay());
}

public function testRejectsInvalidExclusions(): void
{
foreach (['', '/tmp', '../src'] as $path) {
$tester = new CommandTester(ApplicationFactory::create()->find('lint:php'));
self::assertSame(2, $tester->execute(['--package' => $this->workspace, '--exclude' => [$path]]));
}
}

public function testDoesNotFollowSymlinksOutsideThePackage(): void
{
$external = $this->workspace . '-external';
(new Filesystem())->mkdir($external);
file_put_contents($external . '/broken.php', '<?php syntax error');
try {
symlink($external, $this->workspace . '/linked');
symlink($external . '/broken.php', $this->workspace . '/linked.php');
$tester = new CommandTester(ApplicationFactory::create()->find('lint:php'));
self::assertSame(0, $tester->execute(['--package' => $this->workspace]));
self::assertStringContainsString('PHP syntax checked: 0 files.', $tester->getDisplay());
} finally {
(new Filesystem())->remove($external);
}
}
}
Loading