Skip to content

Commit 58061c9

Browse files
authored
Merge pull request #96 from WalterWoshid/feat/regex-advice-patterns
Support explicit regex patterns in advice attributes
2 parents 0d0fbba + 0bc1fc5 commit 58061c9

10 files changed

Lines changed: 237 additions & 8 deletions

File tree

‎README.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,31 @@ class PaymentProcessorAspect
307307
```
308308

309309

310+
### Regular-expression patterns
311+
312+
`class` and `method` accept either wildcard strings or explicit
313+
`Okapi\Wildcards\Regex` objects. Each argument can use a different pattern type:
314+
315+
```php
316+
use Okapi\Aop\Attributes\After;
317+
use Okapi\Wildcards\Regex;
318+
319+
#[After(
320+
class: 'App\\Http\\Controllers\\*',
321+
method: new Regex('/^[a-z][a-z0-9_]*$/i'),
322+
)]
323+
```
324+
325+
This matches controller methods whose names start with a letter, excluding
326+
constructors and other magic methods. Regex objects can also be used for `class`.
327+
The same arguments are supported by `Before`, `Around`, and `After`.
328+
329+
Pass a complete PHP regular expression, including delimiters and any modifiers.
330+
Regex patterns are used as written: add `^` and `$` when you want to match the
331+
whole name. Plain strings always retain wildcard semantics, even if they look
332+
like `/regex/`. Invalid explicit regex patterns throw `InvalidArgumentException`
333+
when the advice attribute is instantiated, identifying the affected argument.
334+
310335
### Target Classes
311336

312337
```php

‎src/Core/Attributes/AdviceType/MethodAdvice.php‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,22 @@ abstract class MethodAdvice extends BaseAdvice
2525
/**
2626
* MethodAdvice constructor.
2727
*
28-
* @param string|null $class Wildcard pattern for the class name.
29-
* @param string|null $method Wildcard pattern for the method name.
28+
* @param string|Regex|null $class Wildcard string or explicit regular expression for the class name.
29+
* @param string|Regex|null $method Wildcard string or explicit regular expression for the method name.
3030
* @param int $order The order of the advice.
3131
* @param bool $interceptTraitMethods If {@see true}, trait methods will be intercepted.
3232
* [Default: {@see true}]
3333
* @param bool $onlyPublicMethods If {@see true}, only public methods will be intercepted.
3434
* [Default: {@see false}]
3535
*/
3636
public function __construct(
37-
?string $class = null,
38-
?string $method = null,
37+
string|Regex|null $class = null,
38+
string|Regex|null $method = null,
3939
int $order = 0,
4040
public bool $interceptTraitMethods = true,
4141
public bool $onlyPublicMethods = false,
4242
) {
4343
parent::__construct($class, $order);
44-
$this->method = $method ? Regex::fromWildcard($method) : null;
44+
$this->method = self::resolvePattern($method, 'method');
4545
}
4646
}

‎src/Core/Attributes/Base/BaseAdvice.php‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
namespace Okapi\Aop\Core\Attributes\Base;
44

5+
use InvalidArgumentException;
56
use Okapi\Aop\Core\Attributes\AdviceType\MethodAdvice;
7+
use Okapi\Wildcards\Exceptions\WildcardException;
68
use Okapi\Wildcards\Regex;
79

810
/**
@@ -20,13 +22,33 @@ abstract class BaseAdvice extends BaseAttribute
2022
/**
2123
* Base advice constructor.
2224
*
23-
* @param string|null $class Wildcard pattern for the class name.
25+
* @param string|Regex|null $class Wildcard string or explicit regular expression for the class name.
2426
* @param int $order The order of the advice.
2527
*/
2628
public function __construct(
27-
?string $class = null,
29+
string|Regex|null $class = null,
2830
public int $order = 0,
2931
) {
30-
$this->class = $class ? Regex::fromWildcard($class) : null;
32+
$this->class = self::resolvePattern($class, 'class');
33+
}
34+
35+
/** @throws InvalidArgumentException If an explicit regular expression is invalid. */
36+
protected static function resolvePattern(string|Regex|null $pattern, string $parameter): ?Regex
37+
{
38+
if (!$pattern instanceof Regex) {
39+
return $pattern ? Regex::fromWildcard($pattern) : null;
40+
}
41+
42+
try {
43+
// Compile the explicit expression now, before any class or method is matched.
44+
$pattern->matches('');
45+
} catch (WildcardException $exception) {
46+
throw new InvalidArgumentException(
47+
sprintf('Invalid %s regex "%s": %s', $parameter, $pattern->getRegex(), $exception->getMessage()),
48+
previous: $exception,
49+
);
50+
}
51+
52+
return $pattern;
3153
}
3254
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
namespace Okapi\Aop\Tests\Functional\AspectMatching\RegexPatterns;
4+
5+
use Okapi\Aop\AopKernel;
6+
use Okapi\Aop\Tests\Util;
7+
8+
class Kernel extends AopKernel
9+
{
10+
protected ?string $cacheDir = Util::CACHE_DIR;
11+
12+
/** @var array<array-key, class-string> */
13+
protected array $aspects = [PatternAspect::class];
14+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
namespace Okapi\Aop\Tests\Functional\AspectMatching\RegexPatterns;
4+
5+
use Okapi\Aop\Attributes\Aspect;
6+
use Okapi\Aop\Attributes\Before;
7+
use Okapi\Aop\Tests\Stubs\Etc\StackTrace;
8+
use Okapi\Wildcards\Regex;
9+
10+
#[Aspect]
11+
class PatternAspect
12+
{
13+
#[Before(class: new Regex('~\\\\RegexPatterns\\\\Target\\\\Selected$~'), method: new Regex('~^SAVE$~i'))]
14+
public function record(): void
15+
{
16+
StackTrace::getInstance()->addTrace('matched');
17+
}
18+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
3+
namespace Okapi\Aop\Tests\Functional\AspectMatching\RegexPatterns;
4+
5+
use Okapi\Aop\Tests\Functional\AspectMatching\RegexPatterns\Target\Other;
6+
use Okapi\Aop\Tests\Functional\AspectMatching\RegexPatterns\Target\Selected;
7+
use Okapi\Aop\Tests\Stubs\Etc\StackTrace;
8+
use Okapi\Aop\Tests\Util;
9+
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;
10+
use PHPUnit\Framework\TestCase;
11+
12+
#[RunTestsInSeparateProcesses]
13+
class RegexWeavingTest extends TestCase
14+
{
15+
public function testRegexSelectsClassesAndMethodsDuringWeaving(): void
16+
{
17+
Util::clearCache();
18+
Kernel::init();
19+
20+
$selected = new Selected();
21+
static::assertSame([], StackTrace::getInstance()->getStackTrace());
22+
static::assertSame('saved', $selected->save());
23+
static::assertSame(['matched'], StackTrace::getInstance()->getStackTrace());
24+
static::assertSame('skipped', $selected->skip());
25+
static::assertSame('other', (new Other())->save());
26+
static::assertSame(['matched'], StackTrace::getInstance()->getStackTrace());
27+
}
28+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
namespace Okapi\Aop\Tests\Functional\AspectMatching\RegexPatterns\Target;
4+
5+
class Other
6+
{
7+
public function save(): string
8+
{
9+
return 'other';
10+
}
11+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
<?php
2+
3+
namespace Okapi\Aop\Tests\Functional\AspectMatching\RegexPatterns\Target;
4+
5+
class Selected
6+
{
7+
public function __construct() {}
8+
9+
public function save(): string
10+
{
11+
return 'saved';
12+
}
13+
14+
public function skip(): string
15+
{
16+
return 'skipped';
17+
}
18+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<?php
2+
3+
namespace Okapi\Aop\Tests\Integration\RegexPatterns;
4+
5+
use Okapi\Aop\Attributes\After;
6+
use Okapi\Wildcards\Regex;
7+
8+
class AttributeFixture
9+
{
10+
#[After(class: new Regex('~^App\\\\Controller$~'), method: new Regex('~^[a-z]+$~'))]
11+
public function advice(): void {}
12+
}
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
<?php
2+
3+
namespace Okapi\Aop\Tests\Integration\RegexPatterns;
4+
5+
use InvalidArgumentException;
6+
use Okapi\Aop\Attributes\After;
7+
use Okapi\Aop\Attributes\Around;
8+
use Okapi\Aop\Attributes\Before;
9+
use Okapi\Wildcards\Regex;
10+
use PHPUnit\Framework\TestCase;
11+
use ReflectionMethod;
12+
13+
class RegexPatternsTest extends TestCase
14+
{
15+
public function testAllAdviceTypesAcceptRegexObjects(): void
16+
{
17+
$class = new Regex('~^App\\\\Controller$~');
18+
$method = new Regex('~^[a-z][a-z0-9_]*$~i');
19+
foreach ([new Before($class, $method), new Around($class, $method), new After($class, $method)] as $advice) {
20+
static::assertSame($class, $advice->class);
21+
static::assertSame($method, $advice->method);
22+
static::assertTrue($class->matches('App\\Controller'));
23+
static::assertTrue($method->matches('SAVE'));
24+
static::assertFalse($method->matches('__construct'));
25+
}
26+
}
27+
28+
public function testRegexAndWildcardPatternsCanBeMixed(): void
29+
{
30+
$wildcardClass = new After(class: 'App\\*', method: new Regex('~^save$~'));
31+
static::assertNotNull($wildcardClass->class);
32+
static::assertTrue($wildcardClass->class->matches('App\\Controller'));
33+
$wildcardMethod = new After(class: new Regex('~Controller$~'), method: 'save*');
34+
static::assertNotNull($wildcardMethod->method);
35+
static::assertTrue($wildcardMethod->method->matches('saveAll'));
36+
static::assertNotNull($wildcardMethod->class);
37+
static::assertTrue($wildcardMethod->class->matches('App\\Controller'));
38+
}
39+
40+
public function testRegexLookingStringsRemainWildcards(): void
41+
{
42+
$advice = new After(class: 'App\\*', method: '/^save$/');
43+
static::assertNotNull($advice->method);
44+
static::assertTrue($advice->method->matches('/^save$/'));
45+
static::assertFalse($advice->method->matches('save'));
46+
}
47+
48+
public function testAbsentPatternsRemainAbsent(): void
49+
{
50+
foreach ([new After(), new After('', ''), new After('0', '0')] as $advice) {
51+
static::assertNull($advice->class);
52+
static::assertNull($advice->method);
53+
}
54+
}
55+
56+
public function testInvalidClassRegexFailsDuringConstruction(): void
57+
{
58+
$this->expectException(InvalidArgumentException::class);
59+
$this->expectExceptionMessage('Invalid class regex');
60+
new After(class: new Regex('/[/'), method: '*');
61+
}
62+
63+
public function testInvalidMethodRegexFailsDuringConstruction(): void
64+
{
65+
$this->expectException(InvalidArgumentException::class);
66+
$this->expectExceptionMessage('Invalid method regex');
67+
new After(class: '*', method: new Regex('missing delimiters'));
68+
}
69+
70+
public function testRegexObjectsCanBeUsedInPhpAttributes(): void
71+
{
72+
$reflection = new ReflectionMethod(AttributeFixture::class, 'advice');
73+
$attribute = $reflection->getAttributes(After::class)[0]->newInstance();
74+
static::assertInstanceOf(After::class, $attribute);
75+
static::assertNotNull($attribute->class);
76+
static::assertNotNull($attribute->method);
77+
static::assertTrue($attribute->class->matches('App\\Controller'));
78+
static::assertTrue($attribute->method->matches('save'));
79+
static::assertFalse($attribute->method->matches('__construct'));
80+
}
81+
}

0 commit comments

Comments
 (0)