From b8a1b7e5cc376d821abb8782d9331a62b3cba6cc Mon Sep 17 00:00:00 2001 From: Simon Rogers Date: Sat, 28 Sep 2024 17:31:33 +0100 Subject: [PATCH] Add tests for strict types expectation Introduced new test cases to ensure strict type declaration handling. Files with and without strict types are tested, including scenarios with comments preceding the declaration. Updated the regex in `Expectation.php` to accommodate comments and whitespaces before the `declare(strict_types=1)` statement. --- src/Expectation.php | 2 +- tests/Features/Expect/toUseStrictTypes.php | 18 ++++++++++++++++++ .../Arch/ToUseStrictTypes/HasNoStrictType.php | 8 ++++++++ .../Arch/ToUseStrictTypes/HasStrictType.php | 10 ++++++++++ .../HasStrictTypeWithCommentsAbove.php | 12 ++++++++++++ 5 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 tests/Features/Expect/toUseStrictTypes.php create mode 100644 tests/Fixtures/Arch/ToUseStrictTypes/HasNoStrictType.php create mode 100644 tests/Fixtures/Arch/ToUseStrictTypes/HasStrictType.php create mode 100644 tests/Fixtures/Arch/ToUseStrictTypes/HasStrictTypeWithCommentsAbove.php diff --git a/src/Expectation.php b/src/Expectation.php index 57843616..ebfd6302 100644 --- a/src/Expectation.php +++ b/src/Expectation.php @@ -509,7 +509,7 @@ final class Expectation { return Targeted::make( $this, - fn (ObjectDescription $object): bool => (bool) preg_match('/^<\?php\s+declare\(.*?strict_types\s?=\s?1.*?\);/', (string) file_get_contents($object->path)), + fn (ObjectDescription $object): bool => (bool) preg_match('/^<\?php\s*(\/\*[\s\S]*?\*\/|\/\/[^\r\n]*(?:\r?\n|$)|\s)*declare\s*\(\s*strict_types\s*=\s*1\s*\)\s*;/m', (string) file_get_contents($object->path)), 'to use strict types', FileLineFinder::where(fn (string $line): bool => str_contains($line, 'toUseStrictTypes() + ->and(HasStrictTypeWithCommentsAbove::class)->toUseStrictTypes(); +}); + +test('failures', function () { + expect(HasNoStrictType::class)->toUseStrictTypes(); +})->throws(ArchExpectationFailedException::class); + diff --git a/tests/Fixtures/Arch/ToUseStrictTypes/HasNoStrictType.php b/tests/Fixtures/Arch/ToUseStrictTypes/HasNoStrictType.php new file mode 100644 index 00000000..ce87bf9a --- /dev/null +++ b/tests/Fixtures/Arch/ToUseStrictTypes/HasNoStrictType.php @@ -0,0 +1,8 @@ +