1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SilverLeague\Console\Framework\Utility; |
4
|
|
|
|
5
|
|
|
use ReflectionClass; |
6
|
|
|
use ReflectionException; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Utility methods for handling SilverStripe Objects |
10
|
|
|
* |
11
|
|
|
* @package silverstripe-console |
12
|
|
|
* @author Robbie Averill <[email protected]> |
13
|
|
|
*/ |
14
|
|
|
trait ObjectUtilities |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* Get a ReflectionClass from the given class name |
18
|
|
|
* |
19
|
|
|
* @param string $className |
20
|
|
|
* @return ReflectionClass |
21
|
|
|
*/ |
22
|
|
|
public function getReflection($className) |
23
|
|
|
{ |
24
|
|
|
try { |
25
|
|
|
return new ReflectionClass($className); |
26
|
|
|
} catch (ReflectionException $ex) { |
27
|
|
|
return false; |
28
|
|
|
} |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Given a class name, find and return which module it belongs to |
33
|
|
|
* |
34
|
|
|
* @param string $className |
35
|
|
|
* @return string |
36
|
|
|
*/ |
37
|
|
|
public function getModuleName($className) |
38
|
|
|
{ |
39
|
|
|
$class = $this->getReflection($className); |
40
|
|
|
if (!$class) { |
41
|
|
|
return ''; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$relativePath = ltrim(substr($class->getFileName(), strlen(SILVERSTRIPE_ROOT_DIR)), '/'); |
45
|
|
|
$folders = explode('/', $relativePath); |
46
|
|
|
if (empty($folder = array_shift($folders))) { |
47
|
|
|
return ''; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$composerConfig = $this->getModuleComposerConfiguration($folder); |
51
|
|
|
return !empty($composerConfig['name']) ? $composerConfig['name'] : ''; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Given a folder name, load a possible composer.json configuration from inside it. This method will handle |
56
|
|
|
* the main project folder e.g. "mysite" by looking in the root folder rather than the folder itself. |
57
|
|
|
* |
58
|
|
|
* @param string $folderName |
59
|
|
|
* @return array |
60
|
|
|
*/ |
61
|
|
|
public function getModuleComposerConfiguration($folderName) |
62
|
|
|
{ |
63
|
|
|
global $project; |
|
|
|
|
64
|
|
|
if (!empty($project) && $project === $folderName) { |
65
|
|
|
$folderName = '.'; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
$filePath = $folderName . '/composer.json'; |
69
|
|
|
if (!file_exists($filePath) || !is_readable($filePath)) { |
70
|
|
|
return []; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
$composerConfig = file_get_contents($filePath); |
74
|
|
|
if (!$composerConfig) { |
75
|
|
|
return []; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return json_decode($composerConfig, true) ?: []; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
Instead of relying on
global
state, we recommend one of these alternatives:1. Pass all data via parameters
2. Create a class that maintains your state