Skip to content

Commit

Permalink
bypassed keywords are configurable
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Sep 16, 2023
1 parent 8ad37fb commit 12ef25e
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 5 deletions.
6 changes: 6 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ preferably right after `vendor/autoload.php` is loaded.

Note that final internal PHP classes like `Closure` cannot be mocked.

The removal of `readonly` keywords can be disabled using the parameter:

```php
DG\BypassFinals::enable(bypassReadOnly: false);
```

You can choose to only bypass keywords in specific files or directories:

```php
Expand Down
11 changes: 6 additions & 5 deletions src/BypassFinals.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,17 @@ class BypassFinals
private static $cacheDir;

/** @var array */
private static $tokens = [
T_FINAL => 'final',
];
private static $tokens = [];


public static function enable(): void
public static function enable(bool $bypassReadOnly = true, bool $bypassFinal = true): void
{
if (PHP_VERSION_ID >= 80100) {
if ($bypassReadOnly && PHP_VERSION_ID >= 80100) {
self::$tokens[T_READONLY] = 'readonly';
}
if ($bypassFinal) {
self::$tokens[T_FINAL] = 'final';
}

$wrapper = stream_get_meta_data(fopen(__FILE__, 'r'))['wrapper_data'] ?? null;
if ($wrapper instanceof self) {
Expand Down
21 changes: 21 additions & 0 deletions tests/BypassFinals/BypassFinals.no-readonly.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php

/** @phpVersion 8.2 */

declare(strict_types=1);

use Tester\Assert;

require __DIR__ . '/../../vendor/autoload.php';

Tester\Environment::setup();


DG\BypassFinals::enable(bypassReadOnly: false);

require __DIR__ . '/fixtures/final.readonly.class.php';

$rc = new ReflectionClass('FinalReadonlyClass');
Assert::true($rc->isReadOnly());
Assert::false($rc->isFinal());
Assert::true($rc->getProperty('foo')->isReadOnly());
1 change: 1 addition & 0 deletions tests/BypassFinals/BypassFinals.readonly+final.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,6 @@ $rc = new ReflectionClass('FinalReadonlyClass');
Assert::false($rc->isReadOnly());
Assert::false($rc->isFinal());
Assert::false($rc->getMethod('finalMethod')->isFinal());
Assert::false($rc->getProperty('foo')->isReadOnly());
Assert::same(123, FinalReadonlyClass::FINAL);
Assert::same(456, (new FinalReadonlyClass)->final());
1 change: 1 addition & 0 deletions tests/BypassFinals/fixtures/final.readonly.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
final readonly class FinalReadonlyClass
{
const FINAL = 123;
public readonly int $foo;

final function finalMethod()
{
Expand Down

0 comments on commit 12ef25e

Please sign in to comment.