AbstractTemplateDataHandler   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 84
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 27
c 1
b 0
f 0
dl 0
loc 84
ccs 0
cts 29
cp 0
rs 10
wmc 9

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getHandler() 0 30 6
A handle() 0 18 3
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\Template\Abstract;
26
27
use Closure;
28
use Derafu\Lib\Core\Package\Prime\Component\Entity\Contract\RepositoryInterface;
29
use Derafu\Lib\Core\Package\Prime\Component\Template\Contract\DataHandlerInterface;
30
use Derafu\Lib\Core\Package\Prime\Component\Template\Exception\TemplateException;
31
use Derafu\Lib\Core\Package\Prime\Component\Template\Service\DataHandler;
32
33
/**
34
 * Base para las implementaciones del servicio que maneja y formatea los datos
35
 * de una plantilla.
36
 */
37
abstract class AbstractTemplateDataHandler implements DataHandlerInterface
38
{
39
    /**
40
     * Mapa de handlers.
41
     *
42
     * @var array
43
     */
44
    protected array $handlers;
45
46
    /**
47
     * Handler por defecto para manejar los casos.
48
     *
49
     * @var DataHandlerInterface
50
     */
51
    protected DataHandlerInterface $handler;
52
53
    /**
54
     * @inheritDoc
55
     */
56
    public function handle(string $id, mixed $data): string
57
    {
58
        // Si no hay valor asignado en los datos se entrega un string vacio.
59
        if (!$data) {
60
            return '';
61
        }
62
63
        // Buscar el handler del dato según su ID.
64
        $handler = $this->getHandler($id);
65
66
        // Corroborar que exista el handler global.
67
        if (!isset($this->handler)) {
68
            $this->handler = new DataHandler();
69
        }
70
        assert($this->handler instanceof DataHandler);
71
72
        // Ejecutar el handler sobre los datos para formatearlos.
73
        return $this->handler->handle($id, $data, $handler);
0 ignored issues
show
Unused Code introduced by
The call to Derafu\Lib\Core\Package\...dlerInterface::handle() has too many arguments starting with $handler. ( Ignorable by Annotation )

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

73
        return $this->handler->/** @scrutinizer ignore-call */ handle($id, $data, $handler);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
74
    }
75
76
    /**
77
     * Obtiene el handler de un campo a partir de su ID.
78
     *
79
     * @param string $id
80
     * @return string|array|callable|Closure|DataHandlerInterface|RepositoryInterface
81
     */
82
    protected function getHandler(string $id): string|array|callable|Closure|DataHandlerInterface|RepositoryInterface
83
    {
84
        if (!isset($this->handlers)) {
85
            $this->handlers = $this->createHandlers();
86
        }
87
88
        if (!isset($this->handlers[$id])) {
89
            throw new TemplateException(sprintf(
90
                'El formato para %s no está definido. Los disponibles son: %s.',
91
                $id,
92
                implode(', ', array_keys($this->handlers))
93
            ));
94
        }
95
96
        if (is_string($this->handlers[$id]) && str_starts_with($this->handlers[$id], 'alias:')) {
97
            [$alias, $handler] = explode(':', $this->handlers[$id], 2);
98
99
            if (!isset($this->handlers[$handler])) {
100
                throw new TemplateException(sprintf(
101
                    'El alias %s del formato para %s no está definido. Los disponibles son: %s.',
102
                    $handler,
103
                    $id,
104
                    implode(', ', array_keys($this->handlers))
105
                ));
106
            }
107
108
            return $this->handlers[$handler];
109
        }
110
111
        return $this->handlers[$id];
112
    }
113
114
    /**
115
     * Crea el mapa de campos a handlers para la plantilla que usará este
116
     * manejador de datos para su formateo.
117
     *
118
     * @return array
119
     */
120
    abstract protected function createHandlers(): array;
121
}
122