Issues (27)

src/Parametres.php (4 issues)

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
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
73 2
                return $data;
74
            }
75
        }
76
77
        // Si aucune valeur contextuelle n'a été trouvée, on revient à la valeur générale.
78
        if ($context !== null) {
79
            return $this->get($key);
80
        }
81
82
        return Arr::getRecursive($config, $dotProperty);
0 ignored issues
show
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

82
        return Arr::getRecursive(/** @scrutinizer ignore-type */ $config, $dotProperty);
Loading history...
83
    }
84
85
    /**
86
     * Sauvegarde d'une valeur dans le gestionnaire d'écriture pour récupération ultérieure.
87
     */
88
    public function set(string $key, mixed $value = null, ?string $context = null): void
89
    {
90 2
        [$file, $property] = $this->prepareFileAndProperty($key);
91
92
        foreach ($this->getWriteHandlers() as $handler) {
93 2
            $handler->set($file, $property, $value, $context);
94
        }
95
    }
96
97
    /**
98
     * Supprime un paramètre de la mémoire persistante,
99
     * en ramenant la valeur à la valeur par défaut trouvée dans le fichier de configuration, s'il y en a un.
100
     */
101
    public function forget(string $key, ?string $context = null): void
102
    {
103
        [$file, $property] = $this->prepareFileAndProperty($key);
104
105
        foreach ($this->getWriteHandlers() as $handler) {
106
            $handler->forget($file, $property, $context);
107
        }
108
    }
109
110
    /**
111
     * Supprime tous les paramètres de la mémoire permanente, utile lors des tests.
112
     * A utiliser avec précaution.
113
     */
114
    public function flush(): void
115
    {
116
        foreach ($this->getWriteHandlers() as $handler) {
117
            $handler->flush();
118
        }
119
    }
120
121
    /**
122
     * Renvoie les gestionnaires qui ont été défini pour stocker les valeurs.
123
     *
124
     * @return list<BaseHandler>
125
     *
126
     * @throws RuntimeException
127
     */
128
    private function getWriteHandlers(): array
129
    {
130 2
        $handlers = [];
131
132
        foreach ($this->options as $handler => $options) {
133
            if (! empty($options['writeable'])) {
134 2
                $handlers[] = $this->handlers[$handler];
135
            }
136
        }
137
138
        if ($handlers === []) {
139 2
            throw new RuntimeException('Impossible de trouver un gestionnaire de paramètres capable de stocker des valeurs.');
140
        }
141
142 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...
143
    }
144
145
    /**
146
     * Analyse la clé donnée et la décompose en parties fichier.champ.
147
     *
148
     * @return list<string>
149
     *
150
     * @throws InvalidArgumentException
151
     */
152
    private function parseDotSyntax(string $key): array
153
    {
154
        // Analyse le nom du champ pour fichier.champ
155 2
        $parts = explode('.', $key);
156
157
        if (count($parts) === 1) {
158 2
            throw new InvalidArgumentException('$key doit contenir à la fois le nom du fichier et celui du champ, exp. foo.bar');
159
        }
160
161 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...
162
    }
163
164
    /**
165
     * Étant donné une clé dans la syntaxe fichier.champ,
166
     * divise les valeurs et détermine le nom du fichier.
167
     *
168
     * @return list<mixed|string>
169
     */
170
    private function prepareFileAndProperty(string $key): array
171
    {
172 2
        $parts    = $this->parseDotSyntax($key);
173 2
        $file     = array_shift($parts);
174 2
        $property = $parts[0];
175
176 2
        $config = config($file);
177
178 2
        return [$file, $property, $config, implode('.', $parts)];
179
    }
180
}
181