Failed Conditions
Push — master ( cdc595...f2bb18 )
by Adrien
02:12
created

ModelResource   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 47
ccs 12
cts 12
cp 1
rs 10
wmc 5

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getInstance() 0 3 1
A getName() 0 5 2
A __construct() 0 10 2
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
class ModelResource extends GenericResource
22
{
23
    /**
24
     * Unique id of the instance of resource
25
     *
26
     * @var null|Model
27
     */
28
    private $instance;
29
30
    /**
31
     * Sets the Resource identifier
32
     *
33
     * @param string $class must be a model class name
34
     * @param Model $instance the instance itself
35
     */
36 3
    public function __construct(string $class, ?Model $instance = null)
37
    {
38 3
        if (!is_subclass_of($class, Model::class)) {
39 1
            throw new InvalidArgumentException('The class name must be an implementation of Model but given: ' . $class);
40
        }
41
42 2
        $class = ClassUtils::getRealClass($class);
43
44 2
        parent::__construct($class);
45 2
        $this->instance = $instance;
46 2
    }
47
48
    /**
49
     * Returns the specific instance of resource found by its type and id.
50
     *
51
     * @return null|Model
52
     */
53 2
    public function getInstance(): ?Model
54
    {
55 2
        return $this->instance;
56
    }
57
58
    /**
59
     * Returns a name identifying this resource for exception messages for developers
60
     *
61
     * @return string
62
     */
63 2
    public function getName(): string
64
    {
65 2
        $instance = $this->getInstance();
66
67 2
        return Utility::getShortClassName($this->resourceId) . '#' . ($instance ? $instance->getId() ?? 'null' : 'null');
68
    }
69
}
70