Passed
Push — main ( 16f015...55d18a )
by Sebastian
03:39
created

Factory::extractConditions()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 1
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 3
ccs 2
cts 2
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/captainhookphp/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 $maxIncludeLevel = 1;
37
38
    /**
39
     * Current level of inclusion
40
     *
41
     * @var int
42
     */
43
    private $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 56
    public function createConfig(string $path = '', array $settings = []): Config
54
    {
55 56
        $path     = $path ?: getcwd() . DIRECTORY_SEPARATOR . CH::CONFIG;
56 56
        $file     = new Json($path);
57 56
        $settings = $this->combineArgumentsAndSettingFile($file, $settings);
58
59 56
        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 56
    private function combineArgumentsAndSettingFile(Json $file, array $settings): array
80
    {
81 56
        $settingsFile = new Json(dirname($file->getPath()) . '/captainhook.config.json');
82 56
        if ($settingsFile->exists()) {
83 1
            $fileSettings = $settingsFile->readAssoc();
84 1
            $settings     = array_merge($fileSettings, $settings);
85
        }
86 56
        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 56
    private function setupConfig(Json $file, array $settings = []): Config
114
    {
115 56
        return $file->exists()
116 50
            ? $this->loadConfigFromFile($file, $settings)
117 54
            : 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 50
    private function loadConfigFromFile(Json $file, array $settings): Config
129
    {
130 50
        $json = $file->readAssoc();
131 50
        Util::validateJsonConfiguration($json);
132
133 50
        $settings = Util::mergeSettings($this->extractSettings($json), $settings);
134 50
        $config   = new Config($file->getPath(), true, $settings);
135 50
        if (!empty($settings)) {
136 42
            $json['config'] = $settings;
137
        }
138
139 50
        $this->appendIncludedConfigurations($config, $json);
140
141 49
        foreach (HookUtil::getValidHooks() as $hook => $class) {
142 49
            if (isset($json[$hook])) {
143 49
                $this->configureHook($config->getHookConfig($hook), $json[$hook]);
144
            }
145
        }
146
147 49
        $this->validatePhpPath($config);
148 48
        return $config;
149
    }
150
151
    /**
152
     * Return the `config` section of some json
153
     *
154
     * @param  array<string, mixed> $json
155
     * @return array<string, mixed>
156
     */
157 50
    private function extractSettings(array $json): array
158
    {
159 50
        return isset($json['config']) && is_array($json['config']) ? $json['config'] : [];
160
    }
161
162
    /**
163
     * Returns the `conditions` section of an actionJson
164
     *
165
     * @param array<string, mixed> $json
166
     * @return array<string, mixed>
167
     */
168 42
    private function extractConditions(mixed $json): array
169
    {
170 42
        return isset($json['conditions']) && is_array($json['conditions']) ? $json['conditions'] : [];
171
    }
172
173
    /**
174
     * Returns the `options` section af some json
175
     *
176
     * @param array<string, mixed> $json
177
     * @return array<string, string>
178
     */
179 42
    private function extractOptions(mixed $json): array
180
    {
181 42
        return isset($json['options']) && is_array($json['options']) ? $json['options'] : [];
182
    }
183
184
    /**
185
     * Set up a hook configuration by json data
186
     *
187
     * @param  \CaptainHook\App\Config\Hook $config
188
     * @param  array<string, mixed>         $json
189
     * @return void
190
     * @throws \Exception
191
     */
192 49
    private function configureHook(Config\Hook $config, array $json): void
193
    {
194 49
        $config->setEnabled($json['enabled']);
195 49
        foreach ($json['actions'] as $actionJson) {
196 42
            $options    = $this->extractOptions($actionJson);
197 42
            $conditions = $this->extractConditions($actionJson);
198 42
            $settings   = $this->extractSettings($actionJson);
199 42
            $config->addAction(new Config\Action($actionJson['action'], $options, $conditions, $settings));
200
        }
201
    }
202
203
    /**
204
     * Makes sure the configured PHP executable exists
205
     *
206
     * @param  \CaptainHook\App\Config $config
207
     * @return void
208
     */
209 49
    private function validatePhpPath(Config $config): void
210
    {
211 49
        if (empty($config->getPhpPath())) {
212 47
            return;
213
        }
214 2
        $foundPHP    = false;
215 2
        $pathToCheck = [$config->getPhpPath()];
216 2
        $parts       = explode(' ', $config->getPhpPath());
217
        // if there are spaces in the php-path and they are not escaped
218
        // it looks like an executable is used to find the PHP binary
219
        // so at least check if the executable exists
220 2
        if (count($parts) > 1 && substr($parts[0], -1) !== '\\') {
221 1
            $pathToCheck[] = $parts[0];
222
        }
223
224 2
        foreach ($pathToCheck as $path) {
225 2
            if (file_exists($path)) {
226 1
                $foundPHP = true;
227 1
                break;
228
            }
229
        }
230
231 2
        if (!$foundPHP) {
232 1
            throw new RuntimeException('The configured php-path is wrong: ' . $config->getPhpPath());
233
        }
234
    }
235
236
    /**
237
     * Append all included configuration to the current configuration
238
     *
239
     * @param  \CaptainHook\App\Config $config
240
     * @param  array<string, mixed>    $json
241
     * @throws \Exception
242
     */
243 50
    private function appendIncludedConfigurations(Config $config, array $json): void
244
    {
245 50
        $this->readMaxIncludeLevel($json);
246
247 50
        if ($this->includeLevel < $this->maxIncludeLevel) {
248 50
            $this->includeLevel++;
249 50
            $includes = $this->loadIncludedConfigs($json, $config->getPath());
250 49
            foreach (HookUtil::getValidHooks() as $hook => $class) {
251 49
                $this->mergeHookConfigFromIncludes($config->getHookConfig($hook), $includes);
252
            }
253 49
            $this->includeLevel--;
254
        }
255
    }
256
257
    /**
258
     * Check config section for 'includes-level' setting
259
     *
260
     * @param array<string, mixed> $json
261
     */
262 50
    private function readMaxIncludeLevel(array $json): void
263
    {
264
        // read the include-level setting only for the actual configuration
265 50
        if ($this->includeLevel === 0 && isset($json['config'][Config::SETTING_INCLUDES_LEVEL])) {
266 2
            $this->maxIncludeLevel = (int) $json['config'][Config::SETTING_INCLUDES_LEVEL];
267
        }
268
    }
269
270
    /**
271
     * Merge a given hook config with the corresponding hook configs from a list of included configurations
272
     *
273
     * @param  \CaptainHook\App\Config\Hook $hook
274
     * @param  \CaptainHook\App\Config[]    $includes
275
     * @return void
276
     */
277 49
    private function mergeHookConfigFromIncludes(Hook $hook, array $includes): void
278
    {
279 49
        foreach ($includes as $includedConfig) {
280 6
            $includedHook = $includedConfig->getHookConfig($hook->getName());
281 6
            if ($includedHook->isEnabled()) {
282 6
                $hook->setEnabled(true);
283
                // This `setEnable` is solely to overwrite the main configuration in the special case that the hook
284
                // is not configured at all. In this case the empty config is disabled by default, and adding an
285
                // empty hook config just to enable the included actions feels a bit dull.
286
                // Since the main hook is processed last (if one is configured) the enabled flag will be overwritten
287
                // once again by the main config value. This is to make sure that if somebody disables a hook in its
288
                // main configuration no actions will get executed, even if we have enabled hooks in any include file.
289 6
                $this->copyActionsFromTo($includedHook, $hook);
290
            }
291
        }
292
    }
293
294
    /**
295
     * Return list of included configurations to add them to the main configuration afterwards
296
     *
297
     * @param  array<string, mixed> $json
298
     * @param  string               $path
299
     * @return \CaptainHook\App\Config[]
300
     * @throws \Exception
301
     */
302 50
    protected function loadIncludedConfigs(array $json, string $path): array
303
    {
304 50
        $includes  = [];
305 50
        $directory = dirname($path);
306 50
        $files     = isset($json['config'][Config::SETTING_INCLUDES])
307 50
                     && is_array($json['config'][Config::SETTING_INCLUDES])
308 7
                   ? $json['config'][Config::SETTING_INCLUDES]
309 43
                   : [];
310
311 50
        foreach ($files as $file) {
312 7
            $includes[] = $this->includeConfig($directory . DIRECTORY_SEPARATOR . $file);
313
        }
314 49
        return $includes;
315
    }
316
317
    /**
318
     * Copy action from a given configuration to the second given configuration
319
     *
320
     * @param \CaptainHook\App\Config\Hook $sourceConfig
321
     * @param \CaptainHook\App\Config\Hook $targetConfig
322
     */
323 6
    private function copyActionsFromTo(Hook $sourceConfig, Hook $targetConfig): void
324
    {
325 6
        foreach ($sourceConfig->getActions() as $action) {
326 6
            $targetConfig->addAction($action);
327
        }
328
    }
329
330
    /**
331
     * Config factory method
332
     *
333
     * @param  string               $path
334
     * @param  array<string, mixed> $settings
335
     * @return \CaptainHook\App\Config
336
     * @throws \Exception
337
     */
338 56
    public static function create(string $path = '', array $settings = []): Config
339
    {
340 56
        $factory = new static();
341 56
        return $factory->createConfig($path, $settings);
342
    }
343
}
344