Skip to content

Commit

Permalink
Update to PHPUnit 11
Browse files Browse the repository at this point in the history
  • Loading branch information
jasny committed Aug 28, 2024
1 parent ec48eef commit 3c00b89
Show file tree
Hide file tree
Showing 22 changed files with 275 additions and 182 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/vendor/
composer.lock
.phpunit.cache
.phpunit.result.cache
.idea
infection.log
10 changes: 6 additions & 4 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,12 @@
},
"require-dev": {
"ext-json": "*",
"jasny/php-code-quality": "~3.0.0",
"mikey179/vfsstream": "^1.6.11",
"phpstan/phpstan": "~1.12.0",
"phpunit/phpunit": "^9.6",
"phpunit/phpunit": "^11.0",
"nyholm/psr7": "^1.1",
"relay/relay": "^2.0"
"relay/relay": "^2.0",
"squizlabs/php_codesniffer": "^3.10"
},
"suggest": {
"ext-zend-opcache": "May prevent filesystem reads"
Expand All @@ -40,14 +41,15 @@
},
"autoload-dev": {
"psr-4": {
"Jasny\\SwitchRoute\\Tests\\Utils\\": "tests/Utils/",
"Jasny\\SwitchRoute\\Tests\\": "tests/unit/",
"Jasny\\SwitchRoute\\FunctionalTests\\": "tests/functional/"
}
},
"scripts": {
"test": [
"phpstan analyse",
"phpunit --testdox --colors=always",
"XDEBUG_MODE=coverage phpunit --testdox --colors=always --coverage-text",
"phpcs -p src"
]
},
Expand Down
12 changes: 3 additions & 9 deletions phpcs.xml
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
<?xml version="1.0"?>
<ruleset name="Jasny">
<description>The Jasny coding standard.</description>

<!-- Include the whole PSR-1 standard -->
<rule ref="PSR1"/>
<!-- Include the whole PSR-2 standard -->
<rule ref="PSR2"/>

<!-- TODO: Add own rules -->
<ruleset name="Coding standard">
<description>PSR-12 coding standard</description>
<rule ref="PSR12"/>
</ruleset>

3 changes: 1 addition & 2 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,4 @@ parameters:
level: 3
paths:
- src
includes:
- vendor/phpstan/phpstan-strict-rules/rules.neon

40 changes: 15 additions & 25 deletions phpunit.xml.dist
Original file line number Diff line number Diff line change
@@ -1,27 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>

<phpunit
colors="true"
bootstrap="vendor/autoload.php"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
>
<testsuites>
<testsuite name="unit">
<directory>tests/unit</directory>
</testsuite>
<testsuite name="functional">
<directory>tests/functional</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">src</directory>
</whitelist>
</filter>
<logging>
<log type="coverage-text" target="php://stdout"/>
</logging>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" colors="true" bootstrap="vendor/autoload.php" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/11.3/phpunit.xsd" cacheDirectory=".phpunit.cache">
<testsuites>
<testsuite name="unit">
<directory>tests/unit</directory>
</testsuite>
<testsuite name="functional">
<directory>tests/functional</directory>
</testsuite>
</testsuites>
<logging/>
<source>
<include>
<directory suffix=".php">src</directory>
</include>
</source>
</phpunit>

23 changes: 15 additions & 8 deletions src/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,31 +53,38 @@ public function generate(string $name, string $file, callable $getRoutes, bool $
throw new \LogicException("Expected code as string, got " . gettype($code));
}

if (!is_dir(dirname($file))) {
$this->tryFs('mkdir', dirname($file), self::DIR_MODE, true);
$dir = dirname($file);

if (!file_exists($dir)) {
$this->tryFs(fn () => mkdir($dir, self::DIR_MODE, true));
} elseif (!is_dir($dir)) {
throw new \RuntimeException("'$dir' exists and is not a directory");
}

$this->tryFs('file_put_contents', $file, $code);
$this->tryFs(fn () => file_put_contents($file, $code));
}

/**
* Try a file system function and throw a \RuntimeException on failure.
*
* @param callable $fn
* @param mixed ...$args
* @return mixed
*/
protected function tryFs(callable $fn, ...$args)
protected function tryFs(callable $fn)
{
$level = error_reporting();
error_reporting($level ^ (E_WARNING | E_USER_WARNING | E_NOTICE | E_USER_NOTICE));
error_reporting($level ^ ~(E_WARNING | E_USER_WARNING | E_NOTICE | E_USER_NOTICE));

error_clear_last();

$ret = null;

try {
$ret = $fn(...$args);
$ret = $fn();
} finally {
error_reporting($level);
if ($ret !== false) {
error_reporting($level);
}
}

if ($ret === false) {
Expand Down
2 changes: 1 addition & 1 deletion src/Generator/GenerateFunction.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ protected function generateRoute(string $key, array $route, array $vars, ?callab

$invocation = $this->invoker->generateInvocation($route, $genArg, $new);
} catch (ReflectionException $exception) {
throw new InvalidRouteException("Invalid route for '$key'. ". $exception->getMessage(), 0, $exception);
throw new InvalidRouteException("Invalid route for '$key'. " . $exception->getMessage(), 0, $exception);
}

return "return $invocation;";
Expand Down
2 changes: 1 addition & 1 deletion src/Generator/GenerateInvokeMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ function ($name, $type, $default) {
);
} catch (ReflectionException $exception) {
$key = preg_replace('/{.*?}/', '*', $key);
throw new InvalidRouteException("Invalid route for '$key'. ". $exception->getMessage(), 0, $exception);
throw new InvalidRouteException("Invalid route for '$key'. " . $exception->getMessage(), 0, $exception);
}

return "return $invocation;";
Expand Down
84 changes: 84 additions & 0 deletions tests/Utils/CallbackMockTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
<?php

declare(strict_types=1);

namespace Jasny\SwitchRoute\Tests\Utils;

use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\MockObject\MockBuilder;
use PHPUnit\Framework\MockObject\Rule\InvocationOrder;

/**
* Trait to create a mock for a callback.
*/
trait CallbackMockTrait
{
/**
* Returns a builder object to create mock objects using a fluent interface.
*
* @param string $className
* @return MockBuilder
*/
abstract public function getMockBuilder(string $className): MockBuilder;

/**
* Create mock for next callback.
*
* <code>
* $callback = $this->createCallbackMock($this->once(), ['abc'], 10);
* </code>
*
* OR
*
* <code>
* $callback = $this->createCallbackMock(
* $this->once(),
* function(InvocationMocker $invoke) {
* $invoke->with('abc')->willReturn(10);
* }
* );
* </code>
*
* @param InvocationOrder $matcher
* @param \Closure|array|null $assert
* @param mixed $return
* @return MockObject|callable
*/
protected function createCallbackMock($matcher, $assert = null, $return = null): MockObject
{
if (isset($assert) && !is_array($assert) && !$assert instanceof \Closure) {
$type = (is_object($assert) ? get_class($assert) . ' ' : '') . gettype($assert);
throw new \InvalidArgumentException("Expected an array or Closure, got a $type");
}

$callback = $this->getMockBuilder(DummyCallback::class)
->setMockClassName('CallbackMock_' . \substr(\md5((string) \mt_rand()), 0, 8))
->getMock();
$invoke = $callback->expects($matcher)->method('__invoke');

if ($assert instanceof \Closure) {
$assert($invoke);
} elseif (is_array($assert)) {
$invoke->with(...$assert)->willReturn($return);
}

return $callback;
}
}

/**
* @internal
* @codeCoverageIgnore
*/
class DummyCallback
{
/**
* Invoke object.
*
* @return mixed
*/
public function __invoke()
{
return null;
}
}
69 changes: 69 additions & 0 deletions tests/Utils/Consecutive.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

/**
Usage: ->with(...Consecutive::create(...$withCodes))
*/

declare(strict_types=1);

namespace Jasny\SwitchRoute\Tests\Utils;

use PHPUnit\Framework\Assert;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\Constraint\IsEqual;
use RuntimeException;

class Consecutive
{
public static function create(...$parameterGroups): array
{
$result = [];
$parametersCount = null;
$groups = [];
$values = [];

foreach ($parameterGroups as $index => $parameters) {
// initial
$parametersCount ??= count($parameters);

// compare
if ($parametersCount !== count($parameters)) {
throw new RuntimeException('Parameters count max much in all groups');
}

// prepare parameters
foreach ($parameters as $parameter) {
if (!$parameter instanceof Constraint) {
$parameter = new IsEqual($parameter);
}

$groups[$index][] = $parameter;
}
}

// collect values
foreach ($groups as $parameters) {
foreach ($parameters as $index => $parameter) {
$values[$index][] = $parameter;
}
}

// build callback
for ($index = 0; $index < $parametersCount; ++$index) {
$result[$index] = Assert::callback(static function ($value) use ($values, $index) {
static $map = null;
$map ??= $values[$index];

$expectedArg = array_shift($map);
if ($expectedArg === null) {
throw new RuntimeException('No more expected calls');
}
$expectedArg->evaluate($value);

return true;
});
}

return $result;
}
}
15 changes: 5 additions & 10 deletions tests/functional/FunctionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,13 @@
use Jasny\SwitchRoute\Invoker;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamDirectory;
use PHPUnit\Framework\Attributes\CoversNothing;
use PHPUnit\Framework\Attributes\DataProvider;

/**
* @coversNothing
*/
#[CoversNothing]
class FunctionTest extends TestCase
{
/**
* @var vfsStreamDirectory
*/
protected static $root;
protected static ?vfsStreamDirectory $root;

public static function setUpBeforeClass(): void
{
Expand Down Expand Up @@ -46,9 +43,7 @@ public static function tearDownAfterClass(): void
self::$root = null;
}

/**
* @dataProvider provider
*/
#[DataProvider('provider')]
public function test(string $method, string $path, $expected)
{
$fn = \Closure::fromCallable(__NAMESPACE__ . '\\route');
Expand Down
Loading

0 comments on commit 3c00b89

Please sign in to comment.