Passed
Pull Request — master (#1928)
by Corey
03:52 queued 01:10
created

Config::getEnvironment()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 6

Importance

Changes 0
Metric Value
eloc 12
dl 0
loc 22
c 0
b 0
f 0
ccs 8
cts 8
cp 1
rs 9.2222
cc 6
nc 5
nop 1
crap 6
1
<?php
2
3
/**
4
 * MIT License
5
 * For full license information, please view the LICENSE file that was distributed with this source code.
6
 */
7
8
namespace Phinx\Config;
9
10
use Closure;
11
use InvalidArgumentException;
12
use Phinx\Db\Adapter\SQLiteAdapter;
13
use Phinx\Util\Util;
14
use RuntimeException;
15
use Symfony\Component\Yaml\Yaml;
16
use UnexpectedValueException;
17
18
/**
19
 * Phinx configuration class.
20
 *
21
 * @package Phinx
22
 * @author Rob Morgan
23
 */
24
class Config implements ConfigInterface, NamespaceAwareInterface
25
{
26
    use NamespaceAwareTrait;
27
28
    /**
29
     * The value that identifies a version order by creation time.
30
     */
31
    public const VERSION_ORDER_CREATION_TIME = 'creation';
32
33
    /**
34
     * The value that identifies a version order by execution time.
35
     */
36
    public const VERSION_ORDER_EXECUTION_TIME = 'execution';
37
38
    /**
39
     * @var array
40
     */
41
    protected $values = [];
42
43
    /**
44
     * @var string
45
     */
46
    protected $configFilePath;
47
48
    /**
49
     * @param array $configArray Config array
50
     * @param string|null $configFilePath Config file path
51
     */
52
    public function __construct(array $configArray, $configFilePath = null)
53
    {
54
        $this->configFilePath = $configFilePath;
55
        $this->values = $this->replaceTokens($configArray);
56
    }
57
58
    /**
59
     * Create a new instance of the config class using a Yaml file path.
60
     *
61
     * @param string $configFilePath Path to the Yaml File
62
     *
63
     * @throws \RuntimeException
64
     *
65
     * @return \Phinx\Config\Config
66 448
     */
67
    public static function fromYaml($configFilePath)
68 448
    {
69 448
        if (!class_exists('Symfony\\Component\\Yaml\\Yaml', true)) {
70 448
            // @codeCoverageIgnoreStart
71
            throw new RuntimeException('Missing yaml parser, symfony/yaml package is not installed.');
72
            // @codeCoverageIgnoreEnd
73
        }
74
75
        $configFile = file_get_contents($configFilePath);
76
        $configArray = Yaml::parse($configFile);
77
78
        if (!is_array($configArray)) {
79 2
            throw new RuntimeException(sprintf(
80
                'File \'%s\' must be valid YAML',
81 2
                $configFilePath
82 2
            ));
83
        }
84 2
85 1
        return new static($configArray, $configFilePath);
86 1
    }
87
88 1
    /**
89
     * Create a new instance of the config class using a JSON file path.
90 1
     *
91
     * @param string $configFilePath Path to the JSON File
92
     *
93
     * @throws \RuntimeException
94
     *
95
     * @return \Phinx\Config\Config
96
     */
97
    public static function fromJson($configFilePath)
98
    {
99
        if (!function_exists('json_decode')) {
100 2
            // @codeCoverageIgnoreStart
101
            throw new RuntimeException("Need to install JSON PHP extension to use JSON config");
102 2
            // @codeCoverageIgnoreEnd
103 2
        }
104 1
105 1
        $configArray = json_decode(file_get_contents($configFilePath), true);
106
        if (!is_array($configArray)) {
107 1
            throw new RuntimeException(sprintf(
108
                'File \'%s\' must be valid JSON',
109 1
                $configFilePath
110
            ));
111
        }
112
113
        return new static($configArray, $configFilePath);
114
    }
115
116
    /**
117
     * Create a new instance of the config class using a PHP file path.
118
     *
119 3
     * @param string $configFilePath Path to the PHP File
120
     *
121 3
     * @throws \RuntimeException
122
     *
123 3
     * @return \Phinx\Config\Config
124
     */
125
    public static function fromPhp($configFilePath)
126 3
    {
127
        ob_start();
128 3
        /** @noinspection PhpIncludeInspection */
129 2
        $configArray = include($configFilePath);
130 2
131
        // Hide console output
132 2
        ob_end_clean();
133
134
        if (!is_array($configArray)) {
135 1
            throw new RuntimeException(sprintf(
136
                'PHP file \'%s\' must return an array',
137
                $configFilePath
138
            ));
139
        }
140
141 25
        return new static($configArray, $configFilePath);
142
    }
143 25
144 24
    /**
145 24
     * @inheritDoc
146 24
     */
147 24
    public function getEnvironments()
148 24
    {
149 24
        if (isset($this->values) && isset($this->values['environments'])) {
150
            $environments = [];
151 24
            foreach ($this->values['environments'] as $key => $value) {
152
                if (is_array($value)) {
153
                    $environments[$key] = $value;
154 1
                }
155
            }
156
157
            return $environments;
158
        }
159
160 25
        return null;
161
    }
162 25
163
    /**
164 25
     * @inheritDoc
165 21
     */
166 21
    public function getEnvironment($name)
167 21
    {
168 21
        $environments = $this->getEnvironments();
169
170 21
        if (isset($environments[$name])) {
171
            if (isset($this->values['environments']['default_migration_table'])) {
172
                $environments[$name]['default_migration_table'] =
173 5
                    $this->values['environments']['default_migration_table'];
174
            }
175
176
            if (
177
                isset($environments[$name]['adapter'])
178
                && $environments[$name]['adapter'] === 'sqlite'
179 9
                && !empty($environments[$name]['memory'])
180
            ) {
181 9
                $environments[$name]['name'] = SQLiteAdapter::MEMORY;
182
            }
183
184
            return $this->parseAgnosticDsn($environments[$name]);
185
        }
186
187 20
        return null;
188
    }
189
190 20
    /**
191 20
     * @inheritDoc
192 2
     */
193 1
    public function hasEnvironment($name)
194
    {
195
        return ($this->getEnvironment($name) !== null);
196 1
    }
197 1
198
    /**
199 1
     * @inheritDoc
200
     */
201
    public function getDefaultEnvironment()
202
    {
203
        // The $PHINX_ENVIRONMENT variable overrides all other default settings
204 19
        $env = getenv('PHINX_ENVIRONMENT');
205 17
        if (!empty($env)) {
206 16
            if ($this->hasEnvironment($env)) {
207
                return $env;
208
            }
209 1
210 1
            throw new RuntimeException(sprintf(
211 1
                'The environment configuration (read from $PHINX_ENVIRONMENT) for \'%s\' is missing',
212 1
                $env
213
            ));
214
        }
215
216 2
        // deprecated: to be removed 0.13
217 1
        if (isset($this->values['environments']['default_database'])) {
218 1
            $this->values['environments']['default_environment'] = $this->values['environments']['default_database'];
219
        }
220
221 1
        // if the user has configured a default environment then use it,
222
        // providing it actually exists!
223
        if (isset($this->values['environments']['default_environment'])) {
224
            if ($this->getEnvironment($this->values['environments']['default_environment'])) {
225
                return $this->values['environments']['default_environment'];
226
            }
227 7
228
            throw new RuntimeException(sprintf(
229 7
                'The environment configuration for \'%s\' is missing',
230
                $this->values['environments']['default_environment']
231
            ));
232
        }
233
234
        // else default to the first available one
235 448
        if (is_array($this->getEnvironments()) && count($this->getEnvironments()) > 0) {
236
            $names = array_keys($this->getEnvironments());
237 448
238
            return $names[0];
239
        }
240
241
        throw new RuntimeException('Could not find a default environment');
242
    }
243 423
244
    /**
245 423
     * @inheritDoc
246 1
     */
247
    public function getAlias($alias)
248
    {
249 422
        return !empty($this->values['aliases'][$alias]) ? $this->values['aliases'][$alias] : null;
250 219
    }
251 219
252
    /**
253 422
     * @inheritDoc
254
     */
255
    public function getAliases()
256
    {
257
        return !empty($this->values['aliases']) ? $this->values['aliases'] : [];
258
    }
259
260
    /**
261
     * @inheritDoc
262 14
     */
263
    public function getConfigFilePath()
264 14
    {
265
        return $this->configFilePath;
266 14
    }
267
268
    /**
269
     * @inheritDoc
270
     *
271
     * @throws \UnexpectedValueException
272 48
     */
273
    public function getMigrationPaths()
274 48
    {
275 28
        if (!isset($this->values['paths']['migrations'])) {
276
            throw new UnexpectedValueException('Migrations path missing from config file');
277
        }
278 20
279 13
        if (is_string($this->values['paths']['migrations'])) {
280 13
            $this->values['paths']['migrations'] = [$this->values['paths']['migrations']];
281
        }
282 20
283
        return $this->values['paths']['migrations'];
284
    }
285
286
    /**
287
     * Gets the base class name for migrations.
288
     *
289
     * @param bool $dropNamespace Return the base migration class name without the namespace.
290 14
     *
291
     * @return string
292 14
     */
293 13
    public function getMigrationBaseClassName($dropNamespace = true)
294
    {
295
        $className = !isset($this->values['migration_base_class']) ? 'Phinx\Migration\AbstractMigration' : $this->values['migration_base_class'];
296 1
297
        return $dropNamespace ? substr(strrchr($className, '\\'), 1) ?: $className : $className;
298
    }
299
300
    /**
301
     * @inheritDoc
302
     *
303
     * @throws \UnexpectedValueException
304 14
     */
305
    public function getSeedPaths()
306 14
    {
307 10
        if (!isset($this->values['paths']['seeds'])) {
308
            throw new UnexpectedValueException('Seeds path missing from config file');
309
        }
310 4
311
        if (is_string($this->values['paths']['seeds'])) {
312
            $this->values['paths']['seeds'] = [$this->values['paths']['seeds']];
313
        }
314
315
        return $this->values['paths']['seeds'];
316
    }
317
318 384
    /**
319
     * Gets the base class name for seeders.
320 384
     *
321 162
     * @param bool $dropNamespace Return the base seeder class name without the namespace.
322
     * @return string
323
     */
324 222
    public function getSeedBaseClassName($dropNamespace = true)
325
    {
326
        $className = !isset($this->values['seed_base_class']) ? 'Phinx\Seed\AbstractSeed' : $this->values['seed_base_class'];
327
328
        return $dropNamespace ? substr(strrchr($className, '\\'), 1) : $className;
329
    }
330
331
    /**
332 357
     * Get the template file name.
333
     *
334 357
     * @return string|false
335
     */
336 357
    public function getTemplateFile()
337
    {
338
        if (!isset($this->values['templates']['file'])) {
339
            return false;
340
        }
341
342
        return $this->values['templates']['file'];
343
    }
344
345
    /**
346
     * Get the template class name.
347 448
     *
348
     * @return string|false
349
     */
350
    public function getTemplateClass()
351 448
    {
352 448
        if (!isset($this->values['templates']['class'])) {
353 448
            return false;
354 2
        }
355 2
356 448
        return $this->values['templates']['class'];
357
    }
358
359 448
    /**
360 448
     * {@inheritdoc}
361
     */
362
    public function getDataDomain()
363 448
    {
364
        if (!isset($this->values['data_domain'])) {
365
            return [];
366
        }
367
368
        return $this->values['data_domain'];
369
    }
370
371
    /**
372
     * @inheritDoc
373 448
     */
374
    public function getContainer()
375 448
    {
376 448
        if (!isset($this->values['container'])) {
377 447
            return null;
378 446
        }
379 446
380
        return $this->values['container'];
381 446
    }
382 446
383 446
    /**
384 446
     * Get the version order.
385 446
     *
386 446
     * @return string
387
     */
388 43
    public function getVersionOrder()
389 448
    {
390 448
        if (!isset($this->values['version_order'])) {
391
            return self::VERSION_ORDER_CREATION_TIME;
392
        }
393
394
        return $this->values['version_order'];
395
    }
396 213
397
    /**
398 213
     * Is version order creation time?
399 213
     *
400
     * @return bool
401
     */
402
    public function isVersionOrderCreationTime()
403
    {
404 2
        $versionOrder = $this->getVersionOrder();
405
406 2
        return $versionOrder == self::VERSION_ORDER_CREATION_TIME;
407 1
    }
408
409
    /**
410 1
     * Get the bootstrap file path
411
     *
412
     * @return string|false
413
     */
414
    public function getBootstrapFile()
415
    {
416 1
        if (!isset($this->values['paths']['bootstrap'])) {
417
            return false;
418 1
        }
419
420
        return $this->values['paths']['bootstrap'];
421
    }
422
423
    /**
424 1
     * Replace tokens in the specified array.
425
     *
426 1
     * @param array $arr Array to replace
427 1
     *
428
     * @return array
429
     */
430
    protected function replaceTokens(array $arr)
431
    {
432
        // Get environment variables
433
        // Depending on configuration of server / OS and variables_order directive,
434
        // environment variables either end up in $_SERVER (most likely) or $_ENV,
435
        // so we search through both
436
        $tokens = [];
437
        foreach (array_merge($_ENV, $_SERVER) as $varname => $varvalue) {
438
            if (strpos($varname, 'PHINX_') === 0) {
439
                $tokens['%%' . $varname . '%%'] = $varvalue;
440
            }
441
        }
442
443
        // Phinx defined tokens (override env tokens)
444
        $tokens['%%PHINX_CONFIG_PATH%%'] = $this->getConfigFilePath();
445
        $tokens['%%PHINX_CONFIG_DIR%%'] = dirname($this->getConfigFilePath());
446
447
        // Recurse the array and replace tokens
448
        return $this->recurseArrayForTokens($arr, $tokens);
449
    }
450
451
    /**
452
     * Recurse an array for the specified tokens and replace them.
453
     *
454
     * @param array $arr Array to recurse
455
     * @param string[] $tokens Array of tokens to search for
456
     *
457
     * @return array
458
     */
459
    protected function recurseArrayForTokens($arr, $tokens)
460
    {
461
        $out = [];
462
        foreach ($arr as $name => $value) {
463
            if (is_array($value)) {
464
                $out[$name] = $this->recurseArrayForTokens($value, $tokens);
465
                continue;
466
            }
467
            if (is_string($value)) {
468
                foreach ($tokens as $token => $tval) {
469
                    $value = str_replace($token, $tval, $value);
470
                }
471
                $out[$name] = $value;
472
                continue;
473
            }
474
            $out[$name] = $value;
475
        }
476
477
        return $out;
478
    }
479
480
    /**
481
     * Parse a database-agnostic DSN into individual options.
482
     *
483
     * @param array $options Options
484
     *
485
     * @return array
486
     */
487
    protected function parseAgnosticDsn(array $options)
488
    {
489
        $parsed = Util::parseDsn($options['dsn'] ?? '');
490
        if ($parsed) {
491
            unset($options['dsn']);
492
        }
493
494
        $options = array_merge($parsed, $options);
495
496
        return $options;
497
    }
498
499
    /**
500
     * {@inheritDoc}
501
     *
502
     * @param mixed $id
503
     * @param mixed $value
504
     *
505
     * @return void
506
     */
507
    public function offsetSet($id, $value)
508
    {
509
        $this->values[$id] = $value;
510
    }
511
512
    /**
513
     * {@inheritDoc}
514
     *
515
     * @param mixed $id
516
     *
517
     * @throws \InvalidArgumentException
518
     *
519
     * @return mixed
520
     */
521
    public function offsetGet($id)
522
    {
523
        if (!array_key_exists($id, $this->values)) {
524
            throw new InvalidArgumentException(sprintf('Identifier "%s" is not defined.', $id));
525
        }
526
527
        return $this->values[$id] instanceof Closure ? $this->values[$id]($this) : $this->values[$id];
528
    }
529
530
    /**
531
     * {@inheritDoc}
532
     *
533
     * @param mixed $id
534
     *
535
     * @return bool
536
     */
537
    public function offsetExists($id)
538
    {
539
        return isset($this->values[$id]);
540
    }
541
542
    /**
543
     * {@inheritDoc}
544
     *
545
     * @param mixed $id
546
     *
547
     * @return void
548
     */
549
    public function offsetUnset($id)
550
    {
551
        unset($this->values[$id]);
552
    }
553
}
554