|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the SexyField package. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Dion Snoeijen <[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
|
|
|
declare (strict_types = 1); |
|
13
|
|
|
|
|
14
|
|
|
namespace Tardigrades\SectionField\Generator\Writer; |
|
15
|
|
|
|
|
16
|
|
|
use Composer\Autoload\ClassLoader; |
|
17
|
|
|
use Symfony\Component\Filesystem\Exception\FileNotFoundException; |
|
18
|
|
|
|
|
19
|
|
|
class GeneratorFileWriter |
|
20
|
|
|
{ |
|
21
|
|
|
public static function write( |
|
22
|
|
|
Writable $writable |
|
23
|
|
|
) { |
|
24
|
|
|
$path = self::getPsr4AutoloadDirectoryForNamespace($writable->getNamespace()); |
|
25
|
|
|
$store = $path . $writable->getFilename(); |
|
26
|
|
|
|
|
27
|
|
|
if (!\file_exists($path)) { |
|
28
|
|
|
\mkdir($path, 0755, true); |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
try { |
|
32
|
|
|
if (\file_exists($store)) { |
|
33
|
|
|
if (!$writable->shouldClobber()) { |
|
34
|
|
|
return; |
|
35
|
|
|
} |
|
36
|
|
|
$segments = explode( |
|
37
|
|
|
'/', |
|
38
|
|
|
$store |
|
39
|
|
|
); |
|
40
|
|
|
$filename = end($segments); |
|
41
|
|
|
$backupFilename = '~' . $filename . '.bak'; |
|
42
|
|
|
$backupStore = str_replace($filename, $backupFilename, $store); |
|
43
|
|
|
\copy($store, $backupStore); |
|
44
|
|
|
} |
|
45
|
|
|
\file_put_contents( |
|
46
|
|
|
$store, |
|
47
|
|
|
$writable->getTemplate() |
|
48
|
|
|
); |
|
49
|
|
|
} catch (\Exception $exception) { |
|
50
|
|
|
echo $exception->getMessage(); |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
public static function getPsr4AutoloadDirectoryForNamespace(string $namespace) |
|
55
|
|
|
{ |
|
56
|
|
|
$find = explode('\\', $namespace)[0]; |
|
57
|
|
|
$reflector = new \ReflectionClass(ClassLoader::class); |
|
58
|
|
|
$vendorDir = \dirname(\dirname($reflector->getFileName())); |
|
59
|
|
|
$vendorFile = $vendorDir . '/composer/autoload_psr4.php'; |
|
60
|
|
|
if (\is_file($vendorFile)) { |
|
61
|
|
|
$namespaces = include $vendorFile; |
|
62
|
|
|
if (is_array($namespaces)) { |
|
63
|
|
|
foreach ($namespaces as $key => $value) { |
|
64
|
|
|
if (strpos($key, $find) === 0) { |
|
65
|
|
|
return str_replace( |
|
66
|
|
|
'\\', |
|
67
|
|
|
'/', |
|
68
|
|
|
$value[0] . str_replace($find, '', $namespace) |
|
69
|
|
|
); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
throw new \InvalidArgumentException('No path found for ' . $namespace); |
|
75
|
|
|
} |
|
76
|
|
|
throw new FileNotFoundException(); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|