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

Repository   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 93
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 37
c 1
b 0
f 0
dl 0
loc 93
ccs 0
cts 38
cp 0
rs 10
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A loadSource() 0 31 5
A __construct() 0 14 2
A normalizeData() 0 12 2
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\Repository;
26
27
use Derafu\Lib\Core\Package\Prime\Component\Entity\Contract\RepositoryInterface;
28
use Derafu\Lib\Core\Support\Store\Repository as StoreRepository;
29
use LogicException;
30
use Symfony\Component\Yaml\Yaml;
31
32
/**
33
 * Clase para repositorios de entidades.
34
 *
35
 * Proporciona métodos estándar para acceder y buscar entidades desde una fuente
36
 * de datos.
37
 */
38
class Repository extends StoreRepository implements RepositoryInterface
39
{
40
    /**
41
     * {@inheritdoc}
42
     */
43
    protected string $entityClass;
44
45
    /**
46
     * Nombre por defecto del índice del nombre cuando los datos de la entidad
47
     * no están normalizados y se debe crear el atributo.
48
     */
49
    protected string $normalizationName = 'name';
50
51
    /**
52
     * Constructor del repositorio.
53
     *
54
     * @param string $entityClass
55
     * @param string|string $source
56
     */
57
    public function __construct(
58
        string $entityClass,
59
        string|array $source,
60
        ?string $normalizationName = null
61
    ) {
62
        $this->entityClass = $entityClass;
63
64
        if (!is_array($source)) {
0 ignored issues
show
introduced by
The condition is_array($source) is always true.
Loading history...
65
            $source = $this->loadSource($source);
66
        }
67
68
        $source = $this->normalizeData($source, $normalizationName);
69
70
        parent::__construct($source);
71
    }
72
73
    /**
74
     * Carga el archivo de datos desde diferentes formatos de archivo.
75
     *
76
     * @param string $source
77
     * @return array
78
     */
79
    protected function loadSource(string $source): array
80
    {
81
        $extension = strtolower(pathinfo($source, PATHINFO_EXTENSION));
0 ignored issues
show
Bug introduced by
It seems like pathinfo($source, Derafu...ory\PATHINFO_EXTENSION) can also be of type array; however, parameter $string of strtolower() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

81
        $extension = strtolower(/** @scrutinizer ignore-type */ pathinfo($source, PATHINFO_EXTENSION));
Loading history...
82
83
        switch ($extension) {
84
            case 'php':
85
                $data = require $source;
86
                break;
87
            case 'json':
88
                $data = json_decode(file_get_contents($source), true);
89
                break;
90
            case 'yaml':
91
                $data = Yaml::parseFile(file_get_contents($source));
92
                break;
93
            default:
94
                throw new LogicException(sprintf(
95
                    'Formato de archivo %s de %s no soportado para la carga de repositorios.',
96
                    $extension,
97
                    basename($source)
98
                ));
99
        }
100
101
        if (!is_array($data)) {
102
            throw new LogicException(sprintf(
103
                'Los datos del repositorio de %s usando el origen %s no ha podido ser convertido a un arreglo válido para ser cargado en el repositorio.',
104
                $this->entityClass,
105
                $source
106
            ));
107
        }
108
109
        return $data;
110
    }
111
112
    /**
113
     * Normaliza los datos en caso que sea un arreglo de valores y no un arreglo
114
     * de arreglos.
115
     *
116
     * @param array $data
117
     * @return array
118
     */
119
    protected function normalizeData(array $data, ?string $normalizationName): array
120
    {
121
        $normalizationName = $normalizationName ?? $this->normalizationName;
122
123
        return array_map(function ($entity) use ($normalizationName) {
124
            if (!is_array($entity)) {
125
                return [
126
                    $normalizationName => $entity,
127
                ];
128
            }
129
            return $entity;
130
        }, $data);
131
    }
132
}
133