Ecodev /
felix
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace Ecodev\Felix\Acl; |
||
| 6 | |||
| 7 | use Doctrine\Common\Util\ClassUtils; |
||
| 8 | use Ecodev\Felix\Model\Model; |
||
| 9 | use Ecodev\Felix\Utility; |
||
| 10 | use InvalidArgumentException; |
||
| 11 | use Laminas\Permissions\Acl\Resource\GenericResource; |
||
| 12 | |||
| 13 | /** |
||
| 14 | * An ACL resource linked to a specific instance of a Model. |
||
| 15 | * |
||
| 16 | * Usage: |
||
| 17 | * |
||
| 18 | * $r = new ModelResource(Question::class, $question); |
||
| 19 | * $question = $r->getInstance(); |
||
| 20 | */ |
||
| 21 | final class ModelResource extends GenericResource |
||
| 22 | { |
||
| 23 | /** |
||
| 24 | * Sets the Resource identifier. |
||
| 25 | * |
||
| 26 | * @param string $class must be a model class name |
||
| 27 | * @param Model $instance the instance itself |
||
| 28 | */ |
||
| 29 | 4 | public function __construct( |
|
| 30 | string $class, |
||
| 31 | private readonly ?Model $instance = null |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 32 | ) { |
||
| 33 | 4 | if (!is_subclass_of($class, Model::class)) { |
|
| 34 | 1 | throw new InvalidArgumentException('The class name must be an implementation of Model but given: ' . $class); |
|
| 35 | } |
||
| 36 | |||
| 37 | 3 | $class = ClassUtils::getRealClass($class); |
|
| 38 | |||
| 39 | 3 | parent::__construct($class); |
|
| 40 | 3 | } |
|
| 41 | |||
| 42 | /** |
||
| 43 | * Returns the specific instance of resource found by its type and id. |
||
| 44 | */ |
||
| 45 | 3 | public function getInstance(): ?Model |
|
| 46 | { |
||
| 47 | 3 | return $this->instance; |
|
| 48 | } |
||
| 49 | |||
| 50 | /** |
||
| 51 | * Returns a name identifying this resource for exception messages for developers. |
||
| 52 | */ |
||
| 53 | 3 | public function getName(): string |
|
| 54 | { |
||
| 55 | 3 | $instance = $this->getInstance(); |
|
| 56 | |||
| 57 | 3 | return Utility::getShortClassName($this->resourceId) . '#' . ($instance ? $instance->getId() ?? 'null' : 'null'); |
|
| 58 | } |
||
| 59 | } |
||
| 60 |