-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathACLModuleBuilder.php
More file actions
82 lines (68 loc) · 2.82 KB
/
ACLModuleBuilder.php
File metadata and controls
82 lines (68 loc) · 2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
namespace App\Security;
use Nette\PhpGenerator\ClassType;
use Nette\PhpGenerator\Literal;
use Nette\Utils\Strings;
use ReflectionClass;
use ReflectionMethod;
use ReflectionNamedType;
class ACLModuleBuilder
{
public function getClassName($interfaceName, $uniqueId)
{
$interfaceName = Strings::after($interfaceName, '\\', -1) ?: $interfaceName;
if (str_starts_with($interfaceName, "I")) {
$rest = Strings::after($interfaceName, "I");
if (Strings::firstUpper($rest) === $rest) {
$interfaceName = $rest;
}
}
return $interfaceName . "Impl_" . $uniqueId;
}
/**
* @param string $interfaceName
* @param string $name
* @param string $uniqueId
* @return ClassType the newly created class
*/
public function build($interfaceName, $name, $uniqueId): ClassType
{
$class = new ClassType($this->getClassName($interfaceName, $uniqueId));
$class->addImplement($interfaceName);
$class->setExtends(ACLModule::class);
$interface = new ReflectionClass($interfaceName);
$class->addMethod("getResourceName")->addBody('return ?;', [$name]);
foreach ($interface->getMethods(ReflectionMethod::IS_ABSTRACT) as $method) {
$isNameCorrect = str_starts_with($method->getName(), "can");
/** @var ?ReflectionNamedType $methodReturnType */
$methodReturnType = $method->getReturnType();
$isBoolean = $methodReturnType !== null ? $methodReturnType->getName() === "bool" : false;
if (!($isNameCorrect && $isBoolean)) {
throw new \LogicException(sprintf('Method %s cannot be implemented automatically', $method->getName()));
}
$action = lcfirst(Strings::after($method->getName(), "can"));
$methodImpl = $class->addMethod($method->getName());
$methodImpl->setReturnType("bool");
$contextStrings = [];
foreach ($method->getParameters() as $parameter) {
$contextStrings[] = sprintf('"%s" => $%s', $parameter->getName(), $parameter->getName());
/** @var ?ReflectionNamedType $parameterType */
$parameterType = $parameter->getType();
$newParameter = $methodImpl->addParameter($parameter->getName())->setType(
$parameterType !== null ? $parameterType->getName() : null
);
if ($parameter->allowsNull()) {
$newParameter->setNullable();
}
}
$methodImpl->addBody(
'return $this->check(?, ?);',
[
$action,
new Literal("[" . implode(", ", $contextStrings) . "]")
]
);
}
return $class;
}
}