Entity   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 174
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 15
eloc 32
c 3
b 0
f 0
dl 0
loc 174
ccs 0
cts 44
cp 0
rs 10

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __toString() 0 3 1
A __callStatic() 0 7 1
A getAttribute() 0 11 2
A __unset() 0 3 1
A hasAttribute() 0 3 1
A unsetAttribute() 0 3 1
A setAttribute() 0 5 1
A __set() 0 3 1
A __call() 0 19 3
A __get() 0 3 1
A toArray() 0 3 1
A __isset() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Derafu: Biblioteca PHP (Núcleo).
7
 * Copyright (C) Derafu <https://www.derafu.org>
8
 *
9
 * Este programa es software libre: usted puede redistribuirlo y/o modificarlo
10
 * bajo los términos de la Licencia Pública General Affero de GNU publicada por
11
 * la Fundación para el Software Libre, ya sea la versión 3 de la Licencia, o
12
 * (a su elección) cualquier versión posterior de la misma.
13
 *
14
 * Este programa se distribuye con la esperanza de que sea útil, pero SIN
15
 * GARANTÍA ALGUNA; ni siquiera la garantía implícita MERCANTIL o de APTITUD
16
 * PARA UN PROPÓSITO DETERMINADO. Consulte los detalles de la Licencia Pública
17
 * General Affero de GNU para obtener una información más detallada.
18
 *
19
 * Debería haber recibido una copia de la Licencia Pública General Affero de GNU
20
 * junto a este programa.
21
 *
22
 * En caso contrario, consulte <http://www.gnu.org/licenses/agpl.html>.
23
 */
24
25
namespace Derafu\Lib\Core\Package\Prime\Component\Entity\Entity;
26
27
use Derafu\Lib\Core\Package\Prime\Component\Entity\Contract\EntityInterface;
28
use LogicException;
29
30
/**
31
 * Clase genérica para el manejo de entidades de repositorios.
32
 *
33
 * Esta clase es útil cuando no se desea crear explícitamente cada clase de cada
34
 * entidad. Sin embargo, es desaconsejado su uso y se recomienda crear clases
35
 * para cada entidad que se requiera.
36
 */
37
class Entity implements EntityInterface
38
{
39
    /**
40
     * Atributos de la entidad.
41
     *
42
     * @var array
43
     */
44
    private array $attributes = [];
45
46
    /**
47
     * {@inheritDoc}
48
     */
49
    public function __toString(): string
50
    {
51
        return static::class . '@' . spl_object_id($this);
52
    }
53
54
    /**
55
     * {@inheritDoc}
56
     */
57
    public function toArray(): array
58
    {
59
        return $this->attributes;
60
    }
61
62
    /**
63
     * {@inheritDoc}
64
     */
65
    public function setAttribute(string $name, mixed $value): static
66
    {
67
        $this->attributes[$name] = $value;
68
69
        return $this;
70
    }
71
72
    /**
73
     * {@inheritDoc}
74
     */
75
    public function getAttribute(string $name): mixed
76
    {
77
        if (!$this->hasAttribute($name)) {
78
            throw new LogicException(sprintf(
79
                'No existe el atributo %s en la entidad %s.',
80
                $name,
81
                static::class
82
            ));
83
        }
84
85
        return $this->attributes[$name];
86
    }
87
88
    /**
89
     * {@inheritDoc}
90
     */
91
    public function hasAttribute(string $name): bool
92
    {
93
        return array_key_exists($name, $this->attributes);
94
    }
95
96
    /**
97
     * {@inheritDoc}
98
     */
99
    public function unsetAttribute(string $name): void
100
    {
101
        unset($this->attributes[$name]);
102
    }
103
104
    /**
105
     * Método mágico para asignar el valor de un atributo como si estuviese
106
     * definido en la clase.
107
     *
108
     * Se ejecuta al escribir datos sobre propiedades inaccesibles (protegidas
109
     * o privadas) o inexistentes.
110
     *
111
     * @param string $name
112
     * @param mixed $value
113
     * @return void
114
     */
115
    public function __set(string $name, mixed $value): void
116
    {
117
        $this->setAttribute($name, $value);
118
    }
119
120
    /**
121
     * Método mágico para obtener el valor de un atributo como si estuviese
122
     * definido en la clase.
123
     *
124
     * Se utiliza para consultar datos a partir de propiedades inaccesibles
125
     * (protegidas o privadas) o inexistentes.
126
     *
127
     * @param string $name
128
     * @return mixed
129
     */
130
    public function __get(string $name): mixed
131
    {
132
        return $this->getAttribute($name);
133
    }
134
135
    /**
136
     * Método mágico para saber si un atributo existe, y tiene valor, como si
137
     * estuviese definido en la clase.
138
     *
139
     * Se lanza al llamar a isset() o a empty() sobre propiedades inaccesibles
140
     * (protegidas o privadas) o inexistentes.
141
     *
142
     * @param string $name
143
     * @return boolean
144
     */
145
    public function __isset(string $name): bool
146
    {
147
        return $this->hasAttribute($name);
148
    }
149
150
    /**
151
     * Método mágico para desasignar el valor de un atributo como si estuviese
152
     * definido en la clase.
153
     *
154
     * Se invoca cuando se usa unset() sobre propiedades inaccesibles
155
     * (protegidas o privadas) o inexistentes.
156
     *
157
     * @param string $name
158
     * @return void
159
     */
160
    public function __unset(string $name): void
161
    {
162
        $this->setAttribute($name, null);
163
    }
164
165
    /**
166
     * Es lanzado al invocar un método inaccesible en un contexto de objeto.
167
     *
168
     * Específicamente procesa las llamadas a los "accessors" ("getters") y
169
     * "mutators" ("setters").
170
     *
171
     * @param string $name
172
     * @param array $arguments
173
     * @return mixed
174
     */
175
    public function __call(string $name, array $arguments)
176
    {
177
        // Si es un "accessor" getXyz() se procesa.
178
        $pattern = '/^get([A-Z][a-zA-Z0-9]*)$/';
179
        if (preg_match($pattern, $name, $matches)) {
180
            return $this->getAttribute(lcfirst($matches[1]));
181
        }
182
183
        // Si es un "mutator" setXyz() se procesa.
184
        $pattern = '/^set([A-Z][a-zA-Z0-9]*)$/';
185
        if (preg_match($pattern, $name, $matches)) {
186
            return $this->setAttribute(lcfirst($matches[1]), ...$arguments);
0 ignored issues
show
Bug introduced by
$arguments is expanded, but the parameter $value of Derafu\Lib\Core\Package\...\Entity::setAttribute() does not expect variable arguments. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

186
            return $this->setAttribute(lcfirst($matches[1]), /** @scrutinizer ignore-type */ ...$arguments);
Loading history...
187
        }
188
189
        // Si el método no existe se genera una excepción.
190
        throw new LogicException(sprintf(
191
            'El método %s::%s() no existe.',
192
            get_debug_type($this),
193
            $name,
194
        ));
195
    }
196
197
    /**
198
     * Es lanzado al invocar un método inaccesible en un contexto estático.
199
     *
200
     * @param string $name
201
     * @param array $arguments
202
     * @return mixed
203
     */
204
    public static function __callStatic(string $name, array $arguments)
205
    {
206
        // Si el método no existe se genera una excepción.
207
        throw new LogicException(sprintf(
208
            'El método %s::%s() no existe.',
209
            static::class,
210
            $name,
211
        ));
212
    }
213
}
214