Skip to content

Commit

Permalink
Add tests for strict types expectation
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
midnite81 committed Sep 28, 2024
1 parent 5fe79d9 commit b8a1b7e
Show file tree
Hide file tree
Showing 5 changed files with 49 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Expectation.php
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,7 @@ public function toUseStrictTypes(): ArchExpectation
{
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, '<?php')),
);
Expand Down
18 changes: 18 additions & 0 deletions tests/Features/Expect/toUseStrictTypes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

use Pest\Arch\Exceptions\ArchExpectationFailedException;
use Tests\Fixtures\Arch\ToUseStrictTypes\HasNoStrictType;
use Tests\Fixtures\Arch\ToUseStrictTypes\HasStrictType;
use Tests\Fixtures\Arch\ToUseStrictTypes\HasStrictTypeWithCommentsAbove;

test('pass', function () {
expect(HasStrictType::class)->toUseStrictTypes()
->and(HasStrictTypeWithCommentsAbove::class)->toUseStrictTypes();
});

test('failures', function () {
expect(HasNoStrictType::class)->toUseStrictTypes();
})->throws(ArchExpectationFailedException::class);

8 changes: 8 additions & 0 deletions tests/Fixtures/Arch/ToUseStrictTypes/HasNoStrictType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Tests\Fixtures\Arch\ToUseStrictTypes;

class HasNoStrictType
{

}
10 changes: 10 additions & 0 deletions tests/Fixtures/Arch/ToUseStrictTypes/HasStrictType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

namespace Tests\Fixtures\Arch\ToUseStrictTypes;

class HasStrictType
{

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php /** @noinspection PhpUnused */

// some other comment

declare(strict_types=1);

namespace Tests\Fixtures\Arch\ToUseStrictTypes;

class HasStrictTypeWithCommentsAbove
{

}

0 comments on commit b8a1b7e

Please sign in to comment.