Passed
Push — master ( 6af461...005087 )
by Esteban De La Fuente
04:26
created

Entity::unsetAttribute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
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 setAttribute(string $name, int|float|string|bool|null $value): static
58
    {
59
        $this->attributes[$name] = $value;
60
61
        return $this;
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function getAttribute(string $name): int|float|string|bool|null
68
    {
69
        if (!$this->hasAttribute($name)) {
70
            throw new LogicException(sprintf(
71
                'No existe el atributo %s en la entidad %s.',
72
                $name,
73
                static::class
74
            ));
75
        }
76
77
        return $this->attributes[$name];
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83
    public function hasAttribute(string $name): bool
84
    {
85
        return array_key_exists($name, $this->attributes);
86
    }
87
88
    /**
89
     * {@inheritdoc}
90
     */
91
    public function unsetAttribute(string $name): void
92
    {
93
        unset($this->attributes[$name]);
94
    }
95
96
    /**
97
     * Método mágico para asignar el valor de un atributo como si estuviese
98
     * definido en la clase.
99
     *
100
     * Se ejecuta al escribir datos sobre propiedades inaccesibles (protegidas
101
     * o privadas) o inexistentes.
102
     *
103
     * @param string $name
104
     * @param int|float|string|bool|null $value
105
     * @return void
106
     */
107
    public function __set(string $name, int|float|string|bool|null $value): void
108
    {
109
        $this->setAttribute($name, $value);
110
    }
111
112
    /**
113
     * Método mágico para obtener el valor de un atributo como si estuviese
114
     * definido en la clase.
115
     *
116
     * Se utiliza para consultar datos a partir de propiedades inaccesibles
117
     * (protegidas o privadas) o inexistentes.
118
     *
119
     * @param string $name
120
     * @return int|float|string|bool|null
121
     */
122
    public function __get(string $name): int|float|string|bool|null
123
    {
124
        return $this->getAttribute($name);
125
    }
126
127
    /**
128
     * Método mágico para saber si un atributo existe, y tiene valor, como si
129
     * estuviese definido en la clase.
130
     *
131
     * Se lanza al llamar a isset() o a empty() sobre propiedades inaccesibles
132
     * (protegidas o privadas) o inexistentes.
133
     *
134
     * @param string $name
135
     * @return boolean
136
     */
137
    public function __isset(string $name): bool
138
    {
139
        return $this->hasAttribute($name);
140
    }
141
142
    /**
143
     * Método mágico para desasignar el valor de un atributo como si estuviese
144
     * definido en la clase.
145
     *
146
     * Se invoca cuando se usa unset() sobre propiedades inaccesibles
147
     * (protegidas o privadas) o inexistentes.
148
     *
149
     * @param string $name
150
     * @return void
151
     */
152
    public function __unset(string $name): void
153
    {
154
        $this->setAttribute($name, null);
155
    }
156
157
    /**
158
     * Es lanzado al invocar un método inaccesible en un contexto de objeto.
159
     *
160
     * Específicamente procesa las llamadas a los "accessors" ("getters") y
161
     * "mutators" ("setters").
162
     *
163
     * @param string $name
164
     * @param array $arguments
165
     * @return mixed
166
     */
167
    public function __call(string $name, array $arguments)
168
    {
169
        // Si es un "accessor" getXyz() se procesa.
170
        $pattern = '/^get([A-Z][a-zA-Z0-9]*)$/';
171
        if (preg_match($pattern, $name, $matches)) {
172
            return $this->getAttribute(lcfirst($matches[1]));
173
        }
174
175
        // Si es un "mutator" setXyz() se procesa.
176
        $pattern = '/^set([A-Z][a-zA-Z0-9]*)$/';
177
        if (preg_match($pattern, $name, $matches)) {
178
            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

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