1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace nystudio107\crafttwigsandbox\helpers; |
4
|
|
|
|
5
|
|
|
use Craft; |
6
|
|
|
use craft\helpers\ArrayHelper; |
7
|
|
|
use nystudio107\crafttwigsandbox\twig\BaseSecurityPolicy; |
8
|
|
|
use function is_array; |
9
|
|
|
|
10
|
|
|
class SecurityPolicy |
11
|
|
|
{ |
12
|
|
|
// Static Methods |
13
|
|
|
// ========================================================================= |
14
|
|
|
|
15
|
|
|
public static function createFromFile(string $filePath, ?string $alias = null): BaseSecurityPolicy |
16
|
|
|
{ |
17
|
|
|
$config = self::getConfigFromFile($filePath, $alias); |
18
|
|
|
|
19
|
|
|
return Craft::createObject($config); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Loads a config file from, trying @craft/config first, then falling back on |
24
|
|
|
* the provided $alias, if any |
25
|
|
|
* |
26
|
|
|
* @param string $filePath |
27
|
|
|
* @param string|null $alias |
28
|
|
|
* |
29
|
|
|
* @return array |
30
|
|
|
*/ |
31
|
|
|
public static function getConfigFromFile(string $filePath, ?string $alias = null): array |
32
|
|
|
{ |
33
|
|
|
// Try craft/config first |
34
|
|
|
$path = self::getConfigFilePath('@config', $filePath); |
35
|
|
|
if (!file_exists($path)) { |
36
|
|
|
if (!$alias) { |
37
|
|
|
return []; |
38
|
|
|
} |
39
|
|
|
// Now the additional alias config |
40
|
|
|
$path = self::getConfigFilePath($alias, $filePath); |
41
|
|
|
if (!file_exists($path)) { |
42
|
|
|
return []; |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
if (!is_array($config = @include $path)) { |
47
|
|
|
return []; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
// If it's not a multi-environment config, return the whole thing |
51
|
|
|
if (!array_key_exists('*', $config)) { |
52
|
|
|
return $config; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
$mergedConfig = []; |
56
|
|
|
/** @var array $config */ |
57
|
|
|
foreach ($config as $env => $envConfig) { |
58
|
|
|
if ($env === '*') { |
59
|
|
|
$mergedConfig = ArrayHelper::merge($mergedConfig, $envConfig); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return $mergedConfig; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
// Private Methods |
67
|
|
|
// ========================================================================= |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Return a path from an alias and a partial path |
71
|
|
|
* |
72
|
|
|
* @param string $alias |
73
|
|
|
* @param string $filePath |
74
|
|
|
* |
75
|
|
|
* @return string |
76
|
|
|
*/ |
77
|
|
|
private static function getConfigFilePath(string $alias, string $filePath): string |
78
|
|
|
{ |
79
|
|
|
$path = DIRECTORY_SEPARATOR . ltrim($filePath, DIRECTORY_SEPARATOR); |
80
|
|
|
$path = Craft::getAlias($alias) |
|
|
|
|
81
|
|
|
. DIRECTORY_SEPARATOR |
82
|
|
|
. str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path) |
83
|
|
|
. '.php'; |
84
|
|
|
|
85
|
|
|
return $path; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|