Passed
Push — master ( ae3156...6fb22a )
by Esteban De La Fuente
03:24
created

AbstractWorker::getHandlers()   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 0
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\Foundation\Abstract;
26
27
use Derafu\Lib\Core\Common\Trait\ConfigurableTrait;
28
use Derafu\Lib\Core\Common\Trait\OptionsAwareTrait;
29
use Derafu\Lib\Core\Foundation\Contract\HandlerInterface;
30
use Derafu\Lib\Core\Foundation\Contract\JobInterface;
31
use Derafu\Lib\Core\Foundation\Contract\StrategyInterface;
32
use Derafu\Lib\Core\Foundation\Contract\WorkerInterface;
33
use Derafu\Lib\Core\Foundation\Exception\HandlerException;
34
use Derafu\Lib\Core\Foundation\Exception\JobException;
35
use Derafu\Lib\Core\Foundation\Exception\StrategyException;
36
use Derafu\Lib\Core\Support\Store\Contract\DataContainerInterface;
37
38
/**
39
 * Clase base para los workers de la aplicación.
40
 */
41
abstract class AbstractWorker extends AbstractService implements WorkerInterface
42
{
43
    use ConfigurableTrait {
44
        setConfiguration as setTraitConfiguration;
45
    }
46
    use OptionsAwareTrait;
47
48
    /**
49
     * Trabajos que el worker implementa.
50
     *
51
     * @var JobInterface[]
52
     */
53
    protected array $jobs;
54
55
    /**
56
     * Handlers que el worker implementa.
57
     *
58
     * @var HandlerInterface[]
59
     */
60
    protected array $handlers;
61
62
    /**
63
     * Estrategias que el worker implementa.
64
     *
65
     * @var StrategyInterface[]
66
     */
67
    protected array $strategies;
68
69
    /**
70
     * Constructor del worker.
71
     *
72
     * @param array $jobs Jobs que este worker implementa.
73
     * @param array $handlers Handlers que este worker implementa.
74
     * @param array $strategies Estrategias que este worker implementa.
75
     */
76 87
    public function __construct(
77
        iterable $jobs = [],
78
        iterable $handlers = [],
79
        iterable $strategies = []
80
    ) {
81 87
        $this->jobs = is_array($jobs)
82 87
            ? $jobs
83
            : iterator_to_array($jobs)
84 87
        ;
85
86 87
        $this->handlers = is_array($handlers)
87 87
            ? $handlers
88
            : iterator_to_array($handlers)
89 87
        ;
90
91 87
        $this->strategies = is_array($strategies)
92 87
            ? $strategies
93
            : iterator_to_array($strategies)
94 87
        ;
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100 1
    public function getName(): string
101
    {
102 1
        $regex = "/\\\\Package\\\\([A-Za-z0-9_]+)\\\\Component\\\\([A-Za-z0-9_]+)\\\\Worker\\\\([A-Za-z0-9_]+)Worker/";
103
104 1
        $class = (string) $this;
105 1
        if (preg_match($regex, $class, $matches)) {
106 1
            return $matches[1] . ' ' . $matches[2] . ' ' . $matches[3];
107
        }
108
109
        return parent::getName();
110
    }
111
112
    /**
113
     * Sobrecarga del método setConfiguration() para poder asignar
114
     * automáticamente las opciones del worker que estén en la configuración del
115
     * worker.
116
     *
117
     * @param array|DataContainerInterface $configuration
118
     * @return static
119
     */
120 38
    public function setConfiguration(
121
        array|DataContainerInterface $configuration
122
    ): static {
123 38
        $this->setTraitConfiguration($configuration);
124
125 38
        $options = $this->getConfiguration()->get('options');
126 38
        if ($options) {
127
            $this->setOptions($options);
128
        }
129
130 38
        return $this;
131
    }
132
133
    /**
134
     * {@inheritdoc}
135
     */
136
    public function getJob(string $job): JobInterface
137
    {
138
        if (!isset($this->jobs[$job])) {
139
            throw new JobException(sprintf(
140
                'No se encontró el trabajo %s en el worker %s (%s).',
141
                $job,
142
                $this->getName(),
143
                $this->getId(),
144
            ));
145
        }
146
147
        return $this->jobs[$job];
148
    }
149
150
    /**
151
     * {@inheritdoc}
152
     */
153
    public function getJobs(): array
154
    {
155
        return $this->jobs;
156
    }
157
158
    /**
159
     * {@inheritdoc}
160
     */
161
    public function getHandler(string $handler): HandlerInterface
162
    {
163
        if (!isset($this->handlers[$handler])) {
164
            throw new HandlerException(sprintf(
165
                'No se encontró el manejador (handler) %s en el worker %s (%s).',
166
                $handler,
167
                $this->getName(),
168
                $this->getId(),
169
            ));
170
        }
171
172
        return $this->handlers[$handler];
173
    }
174
175
    /**
176
     * {@inheritdoc}
177
     */
178
    public function getHandlers(): array
179
    {
180
        return $this->handlers;
181
    }
182
183
    /**
184
     * {@inheritdoc}
185
     */
186
    public function getStrategy(string $strategy): StrategyInterface
187
    {
188
        if (!str_contains($strategy, '.')) {
189
            $strategy = 'default.' . $strategy;
190
        }
191
192
        if (!isset($this->strategies[$strategy])) {
193
            throw new StrategyException(sprintf(
194
                'No se encontró la estrategia %s en el worker %s (%s).',
195
                $strategy,
196
                $this->getName(),
197
                $this->getId(),
198
            ));
199
        }
200
201
        return $this->strategies[$strategy];
202
    }
203
204
    /**
205
     * {@inheritdoc}
206
     */
207
    public function getStrategies(): array
208
    {
209
        return $this->strategies;
210
    }
211
}
212