Passed
Push — master ( 73bfc2...a878a7 )
by Adrien
13:45 queued 10:48
created

ModelResource::getName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 2
rs 10
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 6
    public function __construct(
30
        string $class,
31
        private readonly ?Model $instance = null
32
    ) {
33 6
        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 5
        $class = ClassUtils::getRealClass($class);
38
39 5
        parent::__construct($class);
40
    }
41
42
    /**
43
     * Returns the specific instance of resource found by its type and id.
44
     */
45 4
    public function getInstance(): ?Model
46
    {
47 4
        return $this->instance;
48
    }
49
50
    /**
51
     * Returns a name identifying this resource for exception messages for developers.
52
     */
53 4
    public function getName(): string
54
    {
55 4
        $instance = $this->getInstance();
56
57 4
        return Utility::getShortClassName($this->resourceId) . '#' . ($instance ? $instance->getId() ?? 'null' : 'null');
58
    }
59
}
60