Skip to content
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

feat: add support for PHP 8.4 #567

Merged
merged 2 commits into from
Nov 4, 2024
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: 2 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ jobs:
- "8.1"
- "8.2"
- "8.3"
- "8.4"

env:
php-extensions: ds,yaml
Expand All @@ -33,6 +34,7 @@ jobs:
- uses: "ramsey/composer-install@v2"
with:
dependency-versions: ${{ matrix.dependencies }}
composer-options: "--ignore-platform-reqs" # Remove when Psalm supports PHP 8.4 / @see https://github.com/vimeo/psalm/pull/10928

- name: Running unit tests
run: php vendor/bin/phpunit --testsuite=unit
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
}
],
"require": {
"php": "~8.1.0 || ~8.2.0 || ~8.3.0",
"php": "~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0",
"composer-runtime-api": "^2.0",
"psr/simple-cache": "^1.0 || ^2.0 || ^3.0"
},
Expand Down
12 changes: 6 additions & 6 deletions composer.lock

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

Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

use function array_map;
use function str_ends_with;
use function str_starts_with;

/** @internal */
final class ReflectionFunctionDefinitionRepository implements FunctionDefinitionRepository
Expand Down Expand Up @@ -57,7 +58,8 @@ public function for(callable $function): FunctionDefinition
$class = $reflection->getClosureScopeClass();
$returnType = $returnTypeResolver->resolveReturnTypeFor($reflection);
$nativeReturnType = $returnTypeResolver->resolveNativeReturnTypeFor($reflection);
$isClosure = $name === '{closure}' || str_ends_with($name, '\\{closure}');
// PHP8.2 use `ReflectionFunction::isAnonymous()`
$isClosure = $name === '{closure}' || str_ends_with($name, '\\{closure}') || str_starts_with($name, '{closure:');

if ($returnType instanceof UnresolvableType) {
$returnType = $returnType->forFunctionReturnType($signature);
Expand All @@ -83,7 +85,8 @@ public function for(callable $function): FunctionDefinition
*/
private function signature(ReflectionFunction $reflection): string
{
if (str_contains($reflection->name, '{closure}')) {
// PHP8.2 use `ReflectionFunction::isAnonymous()`
if ($reflection->name === '{closure}' || str_ends_with($reflection->name, '\\{closure}') || str_starts_with($reflection->name, '{closure:')) {
$startLine = $reflection->getStartLine();
$endLine = $reflection->getEndLine();

Expand Down
10 changes: 8 additions & 2 deletions src/Type/Parser/Factory/Specifications/AliasSpecification.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,17 @@
}
}

if (! $reflection->inNamespace()) {
if ($reflection->inNamespace()) {
$namespace = $reflection->getNamespaceName();
} elseif ($reflection instanceof ReflectionFunction) {

Check warning on line 93 in src/Type/Parser/Factory/Specifications/AliasSpecification.php

View workflow job for this annotation

GitHub Actions / Mutation tests

Escaped Mutant for Mutator "InstanceOf_": --- Original +++ New @@ @@ } if ($reflection->inNamespace()) { $namespace = $reflection->getNamespaceName(); - } elseif ($reflection instanceof ReflectionFunction) { + } elseif (false) { $namespace = PhpParser::parseNamespace($reflection); } if (!isset($namespace)) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could guard this against closures to not unnecessarily tokenize the file for top-level functions in non-namespaced code.

$namespace = PhpParser::parseNamespace($reflection);
}

if (! isset($namespace)) {
return $symbol;
}

$full = $reflection->getNamespaceName() . '\\' . $symbol;
$full = "$namespace\\$symbol";

if (Reflection::classOrInterfaceExists($full)) {
return $full;
Expand Down
34 changes: 34 additions & 0 deletions src/Utility/Reflection/NamespaceFinder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace CuyZ\Valinor\Utility\Reflection;

use PhpToken;

/** @internal */
final class NamespaceFinder
{
public function findNamespace(string $content): ?string
{
$tokens = PhpToken::tokenize($content);
$tokensCount = count($tokens);
/* @infection-ignore-all Unneeded because of the nature of namespace-related token */
$pointer = $tokensCount - 1;

while (! $tokens[$pointer]->is(T_NAMESPACE)) {
/* @infection-ignore-all Unneeded because of the nature of namespace-related token */
if ($pointer === 0) {
return null;
}

$pointer--;
}

while (! $tokens[$pointer]->is([T_NAME_QUALIFIED, T_STRING])) {
$pointer++;
}

return (string)$tokens[$pointer];
}
}
45 changes: 31 additions & 14 deletions src/Utility/Reflection/PhpParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,23 +24,31 @@ final class PhpParser
* @param ReflectionClass<object>|ReflectionFunction|ReflectionMethod $reflection
* @return array<string, string>
*/
public static function parseUseStatements(\ReflectionClass|\ReflectionFunction|\ReflectionMethod $reflection): array
public static function parseUseStatements(ReflectionClass|ReflectionFunction|ReflectionMethod $reflection): array
{
$signature = "{$reflection->getFileName()}:{$reflection->getStartLine()}";

// @infection-ignore-all
return self::$statements[$signature] ??= self::fetchUseStatements($reflection);
}

public static function parseNamespace(ReflectionFunction $reflection): ?string
{
$content = self::getFileContent($reflection);

if ($content === null) {
return null;
}

return (new NamespaceFinder())->findNamespace($content);
}

/**
* @param ReflectionClass<object>|ReflectionFunction|ReflectionMethod $reflection
* @return array<string, string>
*/
private static function fetchUseStatements(\ReflectionClass|\ReflectionFunction|\ReflectionMethod $reflection): array
private static function fetchUseStatements(ReflectionClass|ReflectionFunction|ReflectionMethod $reflection): array
{
$filename = $reflection->getFileName();
$startLine = $reflection->getStartLine();

if ($reflection instanceof ReflectionMethod) {
$namespaceName = $reflection->getDeclaringClass()->getNamespaceName();
} elseif ($reflection instanceof ReflectionFunction && $reflection->getClosureScopeClass()) {
Expand All @@ -49,29 +57,38 @@ private static function fetchUseStatements(\ReflectionClass|\ReflectionFunction|
$namespaceName = $reflection->getNamespaceName();
}

// @infection-ignore-all these values will never be `true`
if ($filename === false || $startLine === false) {
return [];
}
$content = self::getFileContent($reflection);

if (! is_file($filename)) {
if ($content === null) {
return [];
}

$content = self::getFileContent($filename, $startLine);

return (new TokenParser($content))->parseUseStatements($namespaceName);
}

private static function getFileContent(string $filename, int $lineNumber): string
/**
* @param ReflectionClass<object>|ReflectionFunction|ReflectionMethod $reflection
*/ private static function getFileContent(ReflectionClass|ReflectionFunction|ReflectionMethod $reflection): ?string
{
$filename = $reflection->getFileName();
$startLine = $reflection->getStartLine();

// @infection-ignore-all these values will never be `true`
if ($filename === false || $startLine === false) {
return null;
}

if (! is_file($filename)) {
return null;
}

// @infection-ignore-all no need to test with `-1`
$lineCnt = 0;
$content = '';
$file = new SplFileObject($filename);

while (! $file->eof()) {
if ($lineCnt++ === $lineNumber) {
if ($lineCnt++ === $startLine) {
break;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ public function test_function_data_can_be_retrieved(): void
$function = $this->repository->for($callback);
$parameters = $function->parameters;

self::assertSame(__NAMESPACE__ . '\{closure}', $function->name);
if (PHP_VERSION_ID < 8_04_00) {
self::assertSame(__NAMESPACE__ . '\{closure}', $function->name);
} else {
self::assertSame('{closure:' . self::class . '::' . __FUNCTION__ . '():37}', $function->name);
}
self::assertInstanceOf(NativeStringType::class, $function->returnType);

self::assertTrue($parameters->has('foo'));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public static function native_type_is_resolved_properly_data_provider(): iterabl
}

// PHP8.2 move to data provider
#[RequiresPhp('8.2')]
#[RequiresPhp('>=8.2')]
public function test_disjunctive_normal_form_type_is_resolved_properly(): void
{
$reflectionType = (new ReflectionProperty(ObjectWithPropertyWithNativeDisjunctiveNormalFormType::class, 'someProperty'))->getType();
Expand All @@ -109,7 +109,7 @@ public function test_disjunctive_normal_form_type_is_resolved_properly(): void
}

// PHP8.2 move to data provider
#[RequiresPhp('8.2')]
#[RequiresPhp('>=8.2')]
public function test_native_null_type_is_resolved_properly(): void
{
$reflectionType = (new ReflectionProperty(ObjectWithPropertyWithNativePhp82StandaloneTypes::class, 'nativeNull'))->getType();
Expand All @@ -120,7 +120,7 @@ public function test_native_null_type_is_resolved_properly(): void
}

// PHP8.2 move to data provider
#[RequiresPhp('8.2')]
#[RequiresPhp('>=8.2')]
public function test_native_true_type_is_resolved_properly(): void
{
$reflectionType = (new ReflectionProperty(ObjectWithPropertyWithNativePhp82StandaloneTypes::class, 'nativeTrue'))->getType();
Expand All @@ -131,7 +131,7 @@ public function test_native_true_type_is_resolved_properly(): void
}

// PHP8.2 move to data provider
#[RequiresPhp('8.2')]
#[RequiresPhp('>=8.2')]
public function test_native_false_type_is_resolved_properly(): void
{
$reflectionType = (new ReflectionProperty(ObjectWithPropertyWithNativePhp82StandaloneTypes::class, 'nativeFalse'))->getType();
Expand Down
34 changes: 34 additions & 0 deletions tests/Functional/Utility/Reflection/PhpParserTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

declare(strict_types=1);

namespace CuyZ\Valinor\Tests\Functional\Utility\Reflection;

use CuyZ\Valinor\Utility\Reflection\PhpParser;
use PHPUnit\Framework\TestCase;
use ReflectionFunction;

final class PhpParserTest extends TestCase
{
public function test_can_parse_namespace_for_closure_with_one_level_namespace(): void
{
$function = require_once 'closure-with-one-level-namespace.php';

$reflection = new ReflectionFunction($function);

$namespace = PhpParser::parseNamespace($reflection);

self::assertSame('OneLevelNamespace', $namespace);
}

public function test_can_parse_namespace_for_closure_with_qualified_namespace(): void
{
$function = require_once 'closure-with-qualified-namespace.php';

$reflection = new ReflectionFunction($function);

$namespace = PhpParser::parseNamespace($reflection);

self::assertSame('Root\QualifiedNamespace', $namespace);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

namespace OneLevelNamespace;

return function () {};
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

namespace Root\QualifiedNamespace;

return function () {};
Loading