Test Failed
Pull Request — main (#8)
by Dimitri
01:58
created

Parametres::flush()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 2
eloc 2
c 2
b 1
f 0
nc 2
nop 0
dl 0
loc 4
ccs 0
cts 1
cp 0
crap 6
rs 10
1
<?php
2
3
/**
4
 * This file is part of BlitzPHP Parametres.
5
 *
6
 * (c) 2025 Dimitri Sitchet Tomkeu <[email protected]>
7
 *
8
 * For the full copyright and license information, please view
9
 * the LICENSE file that was distributed with this source code.
10
 */
11
12
namespace BlitzPHP\Parametres;
13
14
use BlitzPHP\Parametres\Handlers\BaseHandler;
15
use BlitzPHP\Utilities\Iterable\Arr;
16
use InvalidArgumentException;
17
use RuntimeException;
18
19
/**
20
 * Permet aux développeurs de stocker et de récupérer en un seul endroit
21
 * les paramètres définis à l'origine dans les fichiers de configuration de
22
 * l'application principale ou d'un module tiers.
23
 */
24
class Parametres
25
{
26
    /**
27
     * Un tableau de gestionnaires permettant d'obtenir ou de définir les valeurs.
28
     *
29
     * @var list<BaseHandler>
0 ignored issues
show
Bug introduced by
The type BlitzPHP\Parametres\list was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
30
     */
31
    private array $handlers = [];
32
33
    /**
34
     * Un tableau d'options de configuration pour chaque gestionnaire.
35
     *
36
     * @var array<string,array<string,mixed>>
37
     */
38
    private ?array $options = null;
39
40
    /**
41
     * Saisit les instances de nos gestionnaires.
42
     *
43
     * @param array<string, mixed> $config
44
     */
45
    public function __construct(array $config)
46
    {
47
        foreach ($config['handlers'] as $handler) {
48 2
            $class = $config[$handler]['class'] ?? null;
49
50
            if ($class === null) {
51
                continue;
52
            }
53
54 2
            $this->handlers[$handler] = new $class($config[$handler]);
55 2
            $this->options[$handler]  = $config[$handler];
56
        }
57
    }
58
59
    /**
60
     * Récupère une valeur de n'importe quel gestionnaire ou d'un fichier de configuration correspondant au nom file.arg.optionalArg
61
     */
62
    public function get(string $key, ?string $context = null): mixed
63
    {
64 2
        [$file, $property, $config, $dotProperty] = $this->prepareFileAndProperty($key);
65
66
        // Vérifier chacun de nos gestionnaires
67
        foreach ($this->handlers as $handler) {
68
            if ($handler->has($file, $property, $context)) {
69
                if (is_array($data = $handler->get($file, $property, $context)) && $property !== $dotProperty) {
70 2
					return Arr::getRecursive($data, str_replace($property . '.', '', $dotProperty));
71
				}
72 2
				return $data;
73
            }
74
        }
75
76
        // Si aucune valeur contextuelle n'a été trouvée, on revient à la valeur générale.
77
        if ($context !== null) {
78
            return $this->get($key);
79
        }
80
81
        return Arr::getRecursive($config, $dotProperty);
0 ignored issues
show
Bug introduced by
It seems like $config can also be of type BlitzPHP\Config\Config; however, parameter $data of BlitzPHP\Utilities\Iterable\Arr::getRecursive() does only seem to accept array|null, 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
        return Arr::getRecursive(/** @scrutinizer ignore-type */ $config, $dotProperty);
Loading history...
82
    }
83
84
    /**
85
     * Sauvegarde d'une valeur dans le gestionnaire d'écriture pour récupération ultérieure.
86
     */
87
    public function set(string $key, mixed $value = null, ?string $context = null): void
88
    {
89 2
        [$file, $property] = $this->prepareFileAndProperty($key);
90
91
        foreach ($this->getWriteHandlers() as $handler) {
92 2
            $handler->set($file, $property, $value, $context);
93
        }
94
    }
95
96
    /**
97
     * Supprime un paramètre de la mémoire persistante,
98
     * en ramenant la valeur à la valeur par défaut trouvée dans le fichier de configuration, s'il y en a un.
99
     */
100
    public function forget(string $key, ?string $context = null): void
101
    {
102
        [$file, $property] = $this->prepareFileAndProperty($key);
103
104
        foreach ($this->getWriteHandlers() as $handler) {
105
            $handler->forget($file, $property, $context);
106
        }
107
    }
108
109
    /**
110
     * Supprime tous les paramètres de la mémoire permanente, utile lors des tests.
111
     * A utiliser avec précaution.
112
     */
113
    public function flush(): void
114
    {
115
        foreach ($this->getWriteHandlers() as $handler) {
116
            $handler->flush();
117
        }
118
    }
119
120
    /**
121
     * Renvoie les gestionnaires qui ont été défini pour stocker les valeurs.
122
     *
123
     * @return list<BaseHandler>
124
     *
125
     * @throws RuntimeException
126
     */
127
    private function getWriteHandlers(): array
128
    {
129 2
        $handlers = [];
130
131
        foreach ($this->options as $handler => $options) {
132
            if (! empty($options['writeable'])) {
133 2
                $handlers[] = $this->handlers[$handler];
134
            }
135
        }
136
137
        if ($handlers === []) {
138 2
            throw new RuntimeException('Impossible de trouver un gestionnaire de paramètres capable de stocker des valeurs.');
139
        }
140
141 2
        return $handlers;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $handlers returns the type array which is incompatible with the documented return type BlitzPHP\Parametres\list.
Loading history...
142
    }
143
144
    /**
145
     * Analyse la clé donnée et la décompose en parties fichier.champ.
146
     *
147
     * @return list<string>
148
     *
149
     * @throws InvalidArgumentException
150
     */
151
    private function parseDotSyntax(string $key): array
152
    {
153
        // Analyse le nom du champ pour fichier.champ
154 2
        $parts = explode('.', $key);
155
156
        if (count($parts) === 1) {
157 2
            throw new InvalidArgumentException('$key doit contenir à la fois le nom du fichier et celui du champ, exp. foo.bar');
158
        }
159
160 2
        return $parts;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $parts returns the type string[] which is incompatible with the documented return type BlitzPHP\Parametres\list.
Loading history...
161
    }
162
163
    /**
164
     * Étant donné une clé dans la syntaxe fichier.champ,
165
     * divise les valeurs et détermine le nom du fichier.
166
     *
167
     * @return list<mixed|string>
168
     */
169
    private function prepareFileAndProperty(string $key): array
170
    {
171 2
		$parts    = $this->parseDotSyntax($key);
172 2
		$file     = array_shift($parts);
173 2
		$property = $parts[0];
174
175 2
        $config = config($file);
176
177 2
        return [$file, $property, $config, implode('.', $parts)];
178
    }
179
}
180