|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Vasoft\VersionIncrement\Changelog\Interpreter; |
|
6
|
|
|
|
|
7
|
|
|
use Vasoft\VersionIncrement\Contract\ScopeInterpreterInterface; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Regular expression-based scope interpreter. |
|
11
|
|
|
* |
|
12
|
|
|
* This interpreter uses PCRE patterns to match and transform scope strings from git commits |
|
13
|
|
|
* into formatted output for changelog generation. It supports both simple validation |
|
14
|
|
|
* (when template is empty) and pattern-based substitution. |
|
15
|
|
|
* |
|
16
|
|
|
* Usage examples: |
|
17
|
|
|
* - Transform task identifiers into URLs: |
|
18
|
|
|
* pattern: '#^task(\d+)$#', template: '[task](https://example.com/task/$1) ' |
|
19
|
|
|
* input: 'task123' → output: '[task](https://example.com/task/123) ' |
|
20
|
|
|
* |
|
21
|
|
|
* - Validate scope format (empty template): |
|
22
|
|
|
* pattern: '#^task\d+$#', template: '' |
|
23
|
|
|
* input: 'task123' → output: 'task123' |
|
24
|
|
|
* input: 'invalid' → output: null |
|
25
|
|
|
*/ |
|
26
|
|
|
class RegexpScopeInterpreter implements ScopeInterpreterInterface |
|
27
|
|
|
{ |
|
28
|
|
|
/** |
|
29
|
|
|
* @param string $pattern PCRE-compatible regular expression pattern |
|
30
|
|
|
* @param string $template Replacement template using $1, $2, etc. for captured groups |
|
31
|
|
|
* When empty, acts as a validator - returns original scope on match |
|
32
|
|
|
*/ |
|
33
|
11 |
|
public function __construct(private readonly string $pattern, private readonly string $template = '') {} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* Interprets a scope string by applying regular expression matching and substitution. |
|
37
|
|
|
* |
|
38
|
|
|
* If template is empty: |
|
39
|
|
|
* - Returns the original scope when pattern matches |
|
40
|
|
|
* - Returns null when pattern doesn't match |
|
41
|
|
|
* |
|
42
|
|
|
* If template is provided: |
|
43
|
|
|
* - Returns transformed string when pattern matches and substitution occurs |
|
44
|
|
|
* - Returns null when pattern doesn't match (no substitution occurs) |
|
45
|
|
|
* |
|
46
|
|
|
* @param string $scope The scope string from git commit (e.g., 'task123', 'database') |
|
47
|
|
|
* |
|
48
|
|
|
* @return null|string Transformed scope or original scope on validation, null if no match |
|
49
|
|
|
*/ |
|
50
|
11 |
|
public function interpret(string $scope): ?string |
|
51
|
|
|
{ |
|
52
|
11 |
|
if ('' === $this->template) { |
|
53
|
1 |
|
return preg_match($this->pattern, $scope) ? $scope : null; |
|
54
|
|
|
} |
|
55
|
10 |
|
$result = preg_replace($this->pattern, $this->template, $scope); |
|
56
|
|
|
|
|
57
|
10 |
|
return $result !== $scope ? $result : null; |
|
58
|
|
|
} |
|
59
|
|
|
} |
|
60
|
|
|
|