1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Yii\Gii\Validator; |
6
|
|
|
|
7
|
|
|
use InvalidArgumentException; |
8
|
|
|
use Yiisoft\Aliases\Aliases; |
9
|
|
|
use Yiisoft\Validator\Exception\UnexpectedRuleException; |
10
|
|
|
use Yiisoft\Validator\Result; |
11
|
|
|
use Yiisoft\Validator\RuleHandlerInterface; |
12
|
|
|
use Yiisoft\Validator\ValidationContext; |
13
|
|
|
|
14
|
|
|
final class NewClassHandler implements RuleHandlerInterface |
15
|
|
|
{ |
16
|
3 |
|
public function __construct( |
17
|
|
|
private readonly Aliases $aliases, |
18
|
|
|
) { |
19
|
3 |
|
} |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* An inline validator that checks if the attribute value refers to a valid namespaced class name. |
23
|
|
|
* The validator will check if the directory containing the new class file exist or not. |
24
|
|
|
* |
25
|
|
|
* @param mixed $value being validated |
26
|
|
|
*/ |
27
|
3 |
|
public function validate(mixed $value, object $rule, ValidationContext $context): Result |
28
|
|
|
{ |
29
|
3 |
|
if (!$rule instanceof NewClassRule) { |
30
|
|
|
throw new UnexpectedRuleException(NewClassRule::class, $rule); |
31
|
|
|
} |
32
|
|
|
|
33
|
3 |
|
$result = new Result(); |
34
|
3 |
|
$class = ltrim($value, '\\'); |
35
|
3 |
|
if (($pos = strrpos($class, '\\')) !== false) { |
36
|
|
|
$ns = substr($class, 0, $pos); |
37
|
|
|
try { |
38
|
|
|
$path = $this->aliases->get('@' . str_replace('\\', '/', $ns)); |
39
|
|
|
if (!is_dir($path)) { |
40
|
|
|
$result->addError("Please make sure the directory containing this class exists: $path"); |
41
|
|
|
} |
42
|
|
|
} catch (InvalidArgumentException) { |
43
|
|
|
$result->addError("The class namespace is invalid: $ns"); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
3 |
|
return $result; |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|