Skip to content
Draft
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
9 changes: 7 additions & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"phpstan/phpstan-strict-rules": "^2.0",
"phpunit/phpunit": "^10.5.58",
"shipmonk/coding-standard": "^0.2.0",
"shipmonk/coverage-guard": "dev-master",
"shipmonk/name-collision-detector": "^2.1.1"
},
"autoload": {
Expand Down Expand Up @@ -64,7 +65,7 @@
"@check:ec",
"@check:cs",
"@check:types",
"@check:tests",
"@check:coverage",
"@check:self",
"@check:collisions",
"@check:scripts"
Expand All @@ -74,11 +75,15 @@
"composer normalize --dry-run --no-check-lock --no-update-lock",
"composer validate --strict"
],
"check:coverage": [
"XDEBUG_MODE=coverage phpunit --coverage-clover cache/clover.xml",
"coverage-guard check cache/clover.xml"
],
"check:cs": "phpcs",
"check:ec": "ec src tests",
"check:scripts": "phpstan analyse -vv --ansi --level=6 scripts/*.php",
"check:self": "bin/composer-dependency-analyser",
"check:tests": "phpunit tests",
"check:tests": "phpunit",
"check:types": "phpstan analyse -vv --ansi",
"fix:cs": "phpcbf"
}
Expand Down
67 changes: 65 additions & 2 deletions composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

66 changes: 66 additions & 0 deletions coverage-guard.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php declare(strict_types=1);

use ShipMonk\ComposerDependencyAnalyser\Analyser;
use ShipMonk\ComposerDependencyAnalyser\Cli;
use ShipMonk\ComposerDependencyAnalyser\ComposerJson;
use ShipMonk\ComposerDependencyAnalyser\Initializer;
use ShipMonk\ComposerDependencyAnalyser\UsedSymbolExtractor;
use ShipMonk\CoverageGuard\Config;
use ShipMonk\CoverageGuard\Hierarchy\ClassMethodBlock;
use ShipMonk\CoverageGuard\Hierarchy\CodeBlock;
use ShipMonk\CoverageGuard\Rule\CoverageError;
use ShipMonk\CoverageGuard\Rule\CoverageRule;
use ShipMonk\CoverageGuard\Rule\InspectionContext;

$config = new Config();
$config->addRule(new class implements CoverageRule {

public function inspect(
CodeBlock $codeBlock,
InspectionContext $context
): ?CoverageError
{
if (!$codeBlock instanceof ClassMethodBlock) {
return null;
}

if ($codeBlock->getExecutableLinesCount() < 5) {
return null;
}

$coverage = $codeBlock->getCoveragePercentage();
$classReflection = $codeBlock->getMethodReflection()->getDeclaringClass();
$requiredCoverage = $this->getRequiredCoverage($classReflection);

if ($codeBlock->getCoveragePercentage() < $requiredCoverage) {
return CoverageError::create("Method <white>{$codeBlock->getMethodName()}</white> requires $requiredCoverage% coverage, but has only $coverage%.");
}

return null;
}

/**
* @param ReflectionClass<object> $classReflection
*/
private function getRequiredCoverage(ReflectionClass $classReflection): int
{
$isPoor = in_array($classReflection->getName(), [
Initializer::class,
], true);

$isCore = in_array($classReflection->getName(), [
Cli::class,
Analyser::class,
UsedSymbolExtractor::class,
], true);

return match (true) {
$isCore => 80,
$isPoor => 40,
default => 60,
};
}

});

return $config;
47 changes: 33 additions & 14 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,17 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
colors="true"
bootstrap="vendor/autoload.php"
beStrictAboutOutputDuringTests="true"
beStrictAboutChangesToGlobalState="true"
beStrictAboutCoversAnnotation="true"
beStrictAboutTodoAnnotatedTests="true"
failOnRisky="true"
failOnWarning="true"
cacheResultFile="cache/phpunit.result.cache"
<phpunit
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
beStrictAboutChangesToGlobalState="true"
beStrictAboutOutputDuringTests="true"
bootstrap="vendor/autoload.php"
cacheDirectory="cache/phpunit"
colors="true"
displayDetailsOnIncompleteTests="true"
displayDetailsOnPhpunitDeprecations="true"
displayDetailsOnSkippedTests="true"
displayDetailsOnTestsThatTriggerDeprecations="true"
displayDetailsOnTestsThatTriggerErrors="true"
displayDetailsOnTestsThatTriggerNotices="true"
displayDetailsOnTestsThatTriggerWarnings="true"
executionOrder="depends,defects"
failOnDeprecation="true"
failOnIncomplete="true"
failOnNotice="true"
failOnPhpunitDeprecation="true"
failOnRisky="true"
failOnWarning="true"
>
<php>
<ini name="error_reporting" value="-1"/>
</php>
<testsuites>
<testsuite name="default">
<directory>tests</directory>
</testsuite>
</testsuites>

<source restrictNotices="true" restrictWarnings="true">
<include>
<directory>src</directory>
</include>
</source>
</phpunit>
27 changes: 27 additions & 0 deletions tests/ConfigurationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,33 @@ public function testOverlappingUnusedIgnoresOfUnknownClass(): void
], $ignoreList3->getUnusedIgnores());
}

public function testShouldIgnoreUnknownFunction(): void
{
$configuration = new Configuration();
$configuration->ignoreUnknownFunctions(['unknown_function']);
$configuration->ignoreErrorsOnPath(__DIR__ . '/data/../', [ErrorType::UNKNOWN_FUNCTION]);

$ignoreList = $configuration->getIgnoreList();

self::assertTrue($ignoreList->shouldIgnoreUnknownFunction('unknown_function', __DIR__));
self::assertTrue($ignoreList->shouldIgnoreUnknownFunction('unknown_function', __DIR__ . '/app'));
self::assertTrue($ignoreList->shouldIgnoreUnknownFunction('any_function', __DIR__));
self::assertTrue($ignoreList->shouldIgnoreUnknownFunction('any_function', __DIR__ . DIRECTORY_SEPARATOR . 'app'));
self::assertFalse($ignoreList->shouldIgnoreUnknownFunction('any_function', '/other/path'));
}

public function testShouldIgnoreUnknownFunctionByRegex(): void
{
$configuration = new Configuration();
$configuration->ignoreUnknownFunctionsRegex('~^opcache_~');

$ignoreList = $configuration->getIgnoreList();

self::assertTrue($ignoreList->shouldIgnoreUnknownFunction('opcache_reset', __DIR__));
self::assertTrue($ignoreList->shouldIgnoreUnknownFunction('opcache_invalidate', __DIR__));
self::assertFalse($ignoreList->shouldIgnoreUnknownFunction('other_function', __DIR__));
}

/**
* @param callable(Configuration): void $configure
*/
Expand Down
50 changes: 49 additions & 1 deletion tests/ConsoleFormatterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,55 @@ public function testPrintResult(): void

self::assertSame($this->normalizeEol($expectedRegularOutput), $regularOutput);
self::assertSame($this->normalizeEol($expectedVerboseOutput), $verboseOutput);
// editorconfig-checker-enable
}

public function testPrintResultUsages(): void
{
$analysisResult = new AnalysisResult(
scannedFilesCount: 5,
elapsedTime: 0.456,
usages: [
'symfony/console' => [
'Symfony\Component\Console\Application' => [
new SymbolUsage('/app/src/Application.php', 5, SymbolKind::CLASSLIKE),
],
'Symfony\Component\Console\Command\Command' => [
new SymbolUsage('/app/src/MyCommand.php', 10, SymbolKind::CLASSLIKE),
new SymbolUsage('/app/src/AnotherCommand.php', 15, SymbolKind::CLASSLIKE),
],
],
],
unknownClassErrors: [],
unknownFunctionErrors: [],
shadowDependencyErrors: [],
devDependencyInProductionErrors: [],
prodDependencyOnlyInDevErrors: [],
unusedDependencyErrors: [],
unusedIgnores: [],
);

$output = $this->getFormatterNormalizedOutput(static function ($formatter) use ($analysisResult): void {
$options = new CliOptions();
$options->dumpUsages = 'symfony/console';
$formatter->format($analysisResult, $options, new Configuration());
});

$expectedOutput = <<<'OUT'

Dumping sample usages of symfony/console
(3 usages of 2 symbols in total)

• symfony/console
Symfony\Component\Console\Application
src/Application.php:5
Symfony\Component\Console\Command\Command
src/MyCommand.php:10
src/AnotherCommand.php:15


OUT;

self::assertSame($this->normalizeEol($expectedOutput), $output);
}

protected function createFormatter(Printer $printer): ResultFormatter
Expand Down
25 changes: 25 additions & 0 deletions tests/InitializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use ShipMonk\ComposerDependencyAnalyser\Exception\InvalidConfigException;
use ShipMonk\ComposerDependencyAnalyser\Result\ConsoleFormatter;
use ShipMonk\ComposerDependencyAnalyser\Result\JunitFormatter;
use function count;
use function dirname;
use function strtr;
use const DIRECTORY_SEPARATOR;
Expand Down Expand Up @@ -120,6 +121,30 @@ public function testInitCliOptionsHelp(): void
$initializer->initCliOptions(__DIR__, ['script.php', '--help']);
}

public function testInitCliOptionsVersion(): void
{
$printer = $this->createMock(Printer::class);
$printer->expects(self::once())
->method('printLine')
->with(self::stringStartsWith('Composer Dependency Analyser'));

$initializer = new Initializer(__DIR__, $printer, $printer);

$this->expectException(AbortException::class);
$initializer->initCliOptions(__DIR__, ['script.php', '--version']);
}

public function testInitComposerClassLoaders(): void
{
$stdOutPrinter = $this->createMock(Printer::class);
$stdErrPrinter = $this->createMock(Printer::class);

$initializer = new Initializer(__DIR__, $stdOutPrinter, $stdErrPrinter);
$loaders = $initializer->initComposerClassLoaders();

self::assertGreaterThan(0, count($loaders));
}

public function testInitFormatter(): void
{
$printer = $this->createMock(Printer::class);
Expand Down