Factory::appendIncludedConfigurations()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 7
c 0
b 0
f 0
nc 3
nop 2
dl 0
loc 11
ccs 8
cts 8
cp 1
crap 3
rs 10
1
<?php
2
3
/**
4
 * This file is part of CaptainHook
5
 *
6
 * (c) Sebastian Feldmann <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace CaptainHook\App\Config;
13
14
use CaptainHook\App\CH;
15
use CaptainHook\App\Config;
16
use CaptainHook\App\Hook\Util as HookUtil;
17
use CaptainHook\App\Storage\File\Json;
18
use RuntimeException;
19
20
/**
21
 * Class Factory
22
 *
23
 * @package CaptainHook
24
 * @author  Sebastian Feldmann <[email protected]>
25
 * @link    https://github.com/captainhook-git/captainhook
26
 * @since   Class available since Release 0.9.0
27
 * @internal
28
 */
29
final class Factory
30
{
31
    /**
32
     * Maximal level in including config files
33
     *
34
     * @var int
35
     */
36
    private int $maxIncludeLevel = 1;
37
38
    /**
39
     * Current level of inclusion
40
     *
41
     * @var int
42
     */
43
    private int $includeLevel = 0;
44
45
    /**
46
     * Create a CaptainHook configuration
47
     *
48
     * @param  string               $path     Path to the configuration file
49
     * @param  array<string, mixed> $settings Settings passed as options on the command line
50
     * @return \CaptainHook\App\Config
51
     * @throws \Exception
52
     */
53 64
    public function createConfig(string $path = '', array $settings = []): Config
54
    {
55 64
        $path     = $path ?: getcwd() . DIRECTORY_SEPARATOR . CH::CONFIG;
56 64
        $file     = new Json($path);
57 64
        $settings = $this->combineArgumentsAndSettingFile($file, $settings);
58
59 64
        return $this->setupConfig($file, $settings);
60
    }
61
62
    /**
63
     * Read settings from a local 'config' file
64
     *
65
     * If you prefer a different verbosity or use a different run mode locally then your teammates do.
66
     * You can create a 'captainhook.config.json' in the same directory as your captainhook
67
     * configuration file and use it to overwrite the 'config' settings of that configuration file.
68
     * Exclude the 'captainhook.config.json' from version control, and you don't have to edit the
69
     * version controlled configuration for your local specifics anymore.
70
     *
71
     * Settings provided as arguments still overrule config file settings:
72
     *
73
     * ARGUMENTS > SETTINGS_FILE > CONFIGURATION
74
     *
75
     * @param  \CaptainHook\App\Storage\File\Json $file
76
     * @param  array<string, mixed>               $settings
77
     * @return array<string, mixed>
78
     */
79 64
    private function combineArgumentsAndSettingFile(Json $file, array $settings): array
80
    {
81 64
        $settingsFile = new Json(dirname($file->getPath()) . '/captainhook.config.json');
82 64
        if ($settingsFile->exists()) {
83 1
            $fileSettings = $settingsFile->readAssoc();
84 1
            $settings     = array_merge($fileSettings, $settings);
85
        }
86 64
        return $settings;
87
    }
88
89
    /**
90
     * Includes an external captainhook configuration
91
     *
92
     * @param  string $path
93
     * @return \CaptainHook\App\Config
94
     * @throws \Exception
95
     */
96 7
    private function includeConfig(string $path): Config
97
    {
98 7
        $file = new Json($path);
99 7
        if (!$file->exists()) {
100 1
            throw new RuntimeException('Config to include not found: ' . $path);
101
        }
102 6
        return $this->setupConfig($file);
103
    }
104
105
    /**
106
     * Return a configuration with data loaded from json file if it exists
107
     *
108
     * @param  \CaptainHook\App\Storage\File\Json $file
109
     * @param  array<string, mixed>               $settings
110
     * @return \CaptainHook\App\Config
111
     * @throws \Exception
112
     */
113 64
    private function setupConfig(Json $file, array $settings = []): Config
114
    {
115 64
        return $file->exists()
116 56
            ? $this->loadConfigFromFile($file, $settings)
117 62
            : new Config($file->getPath(), false, $settings);
118
    }
119
120
    /**
121
     * Loads a given file into given the configuration
122
     *
123
     * @param  \CaptainHook\App\Storage\File\Json $file
124
     * @param  array<string, mixed>               $settings
125
     * @return \CaptainHook\App\Config
126
     * @throws \Exception
127
     */
128 56
    private function loadConfigFromFile(Json $file, array $settings): Config
129
    {
130 56
        $json = $file->readAssoc();
131 56
        Util::validateJsonConfiguration($json);
132
133 56
        $settings = Util::mergeSettings($this->extractSettings($json), $settings);
134 56
        $config   = new Config($file->getPath(), true, $settings);
135 56
        if (!empty($settings)) {
136 44
            $json['config'] = $settings;
137
        }
138
139 56
        $this->appendIncludedConfigurations($config, $json);
140
141
        // fallback to $json->HOOK_NAME if $json->HOOKS->HOOK_NAME does not exist
142 55
        $hooks = $json['hooks'] ?? $json;
143
144 55
        foreach (HookUtil::getValidHooks() as $hook => $class) {
145 55
            if (isset($hooks[$hook])) {
146 55
                $this->configureHook($config->getHookConfig($hook), $hooks[$hook]);
147
            }
148
        }
149
150 55
        $this->validatePhpPath($config);
151 54
        return $config;
152
    }
153
154
    /**
155
     * Return the `config` section of some json
156
     *
157
     * @param  array<string, mixed> $json
158
     * @return array<string, mixed>
159
     */
160 56
    private function extractSettings(array $json): array
161
    {
162 56
        return Util::extractListFromJson($json, 'config');
163
    }
164
165
    /**
166
     * Returns the `conditions` section of an actionJson
167
     *
168
     * @param array<string, mixed> $json
169
     * @return array<string, mixed>
170
     */
171 47
    private function extractConditions(mixed $json): array
172
    {
173 47
        return Util::extractListFromJson($json, 'conditions');
174
    }
175
176
    /**
177
     * Returns the `options` section af some json
178
     *
179
     * @param array<string, mixed> $json
180
     * @return array<string, string>
181
     */
182 47
    private function extractOptions(mixed $json): array
183
    {
184 47
        return Util::extractListFromJson($json, 'options');
185
    }
186
187
    /**
188
     * Set up a hook configuration by json data
189
     *
190
     * @param  \CaptainHook\App\Config\Hook $config
191
     * @param  array<string, mixed>         $json
192
     * @return void
193
     * @throws \Exception
194
     */
195 55
    private function configureHook(Config\Hook $config, array $json): void
196
    {
197 55
        $config->setEnabled($json['enabled'] ?? true);
198 55
        foreach ($json['actions'] as $actionJson) {
199 47
            $options    = $this->extractOptions($actionJson);
200 47
            $conditions = $this->extractConditions($actionJson);
201 47
            $settings   = $this->extractSettings($actionJson);
202 47
            $config->addAction(new Config\Action($actionJson['action'], $options, $conditions, $settings));
203
        }
204
    }
205
206
    /**
207
     * Makes sure the configured PHP executable exists
208
     *
209
     * @param  \CaptainHook\App\Config $config
210
     * @return void
211
     */
212 55
    private function validatePhpPath(Config $config): void
213
    {
214 55
        if (empty($config->getPhpPath())) {
215 53
            return;
216
        }
217 2
        $pathToCheck = [$config->getPhpPath()];
218 2
        $parts       = explode(' ', $config->getPhpPath());
219
        // if there are spaces in the php-path and they are not escaped
220
        // it looks like an executable is used to find the PHP binary
221
        // so at least check if the executable exists
222 2
        if ($this->usesPathResolver($parts)) {
223 1
            $pathToCheck[] = $parts[0];
224
        }
225
226 2
        foreach ($pathToCheck as $path) {
227 2
            if (file_exists($path)) {
228 1
                return;
229
            }
230
        }
231 1
        throw new RuntimeException('The configured php-path is wrong: ' . $config->getPhpPath());
232
    }
233
234
    /**
235
     * Is a binary used to resolve the php path
236
     *
237
     * @param array<int, string> $parts
238
     * @return bool
239
     */
240 2
    private function usesPathResolver(array $parts): bool
241
    {
242 2
        return count($parts) > 1 && !str_ends_with($parts[0], '\\');
243
    }
244
245
    /**
246
     * Append all included configuration to the current configuration
247
     *
248
     * @param  \CaptainHook\App\Config $config
249
     * @param  array<string, mixed>    $json
250
     * @throws \Exception
251
     */
252 56
    private function appendIncludedConfigurations(Config $config, array $json): void
253
    {
254 56
        $this->readMaxIncludeLevel($json);
255
256 56
        if ($this->includeLevel < $this->maxIncludeLevel) {
257 56
            $this->includeLevel++;
258 56
            $includes = $this->loadIncludedConfigs($json, $config->getPath());
259 55
            foreach (HookUtil::getValidHooks() as $hook => $class) {
260 55
                $this->mergeHookConfigFromIncludes($config->getHookConfig($hook), $includes);
261
            }
262 55
            $this->includeLevel--;
263
        }
264
    }
265
266
    /**
267
     * Check config section for 'includes-level' setting
268
     *
269
     * @param array<string, mixed> $json
270
     */
271 56
    private function readMaxIncludeLevel(array $json): void
272
    {
273
        // read the include-level setting only for the actual configuration
274 56
        if ($this->includeLevel === 0 && isset($json['config'][Config::SETTING_INCLUDES_LEVEL])) {
275 2
            $this->maxIncludeLevel = (int) $json['config'][Config::SETTING_INCLUDES_LEVEL];
276
        }
277
    }
278
279
    /**
280
     * Merge a given hook config with the corresponding hook configs from a list of included configurations
281
     *
282
     * @param  \CaptainHook\App\Config\Hook $hook
283
     * @param  \CaptainHook\App\Config[]    $includes
284
     * @return void
285
     */
286 55
    private function mergeHookConfigFromIncludes(Hook $hook, array $includes): void
287
    {
288 55
        foreach ($includes as $includedConfig) {
289 6
            $includedHook = $includedConfig->getHookConfig($hook->getName());
290 6
            if ($includedHook->isEnabled()) {
291 6
                $hook->setEnabled(true);
292
                // This `setEnable` is solely to overwrite the main configuration in the special case that the hook
293
                // is not configured at all. In this case the empty config is disabled by default, and adding an
294
                // empty hook config just to enable the included actions feels a bit dull.
295
                // Since the main hook is processed last (if one is configured) the enabled flag will be overwritten
296
                // once again by the main config value. This is to make sure that if somebody disables a hook in its
297
                // main configuration, no actions will get executed, even if we have enabled hooks in any include file.
298 6
                $this->copyActionsFromTo($includedHook, $hook);
299
            }
300
        }
301
    }
302
303
    /**
304
     * Return list of included configurations to add them to the main configuration afterwards
305
     *
306
     * @param  array<string, mixed> $json
307
     * @param  string               $path
308
     * @return \CaptainHook\App\Config[]
309
     * @throws \Exception
310
     */
311 56
    protected function loadIncludedConfigs(array $json, string $path): array
312
    {
313 56
        $includes  = [];
314 56
        $directory = dirname($path);
315 56
        $files     = Util::extractListFromJson(Util::extractListFromJson($json, 'config'), Config::SETTING_INCLUDES);
316
317 56
        foreach ($files as $file) {
318 7
            $includes[] = $this->includeConfig($directory . DIRECTORY_SEPARATOR . $file);
319
        }
320 55
        return $includes;
321
    }
322
323
    /**
324
     * Copy action from a given configuration to the second given configuration
325
     *
326
     * @param \CaptainHook\App\Config\Hook $sourceConfig
327
     * @param \CaptainHook\App\Config\Hook $targetConfig
328
     */
329 6
    private function copyActionsFromTo(Hook $sourceConfig, Hook $targetConfig): void
330
    {
331 6
        foreach ($sourceConfig->getActions() as $action) {
332 6
            $action->markIncluded();
333 6
            $targetConfig->addAction($action);
334
        }
335
    }
336
337
    /**
338
     * Config factory method
339
     *
340
     * @param  string               $path
341
     * @param  array<string, mixed> $settings
342
     * @return \CaptainHook\App\Config
343
     * @throws \Exception
344
     */
345 64
    public static function create(string $path = '', array $settings = []): Config
346
    {
347 64
        $factory = new static();
348 64
        return $factory->createConfig($path, $settings);
349
    }
350
}
351