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
|
|
|
try { |
28
|
|
|
if (\file_exists($store)) { |
29
|
|
|
$segments = explode( |
30
|
|
|
'/', |
31
|
|
|
$store |
32
|
|
|
); |
33
|
|
|
$filename = end($segments); |
34
|
|
|
$backupFilename = '~' . $filename . '.bak'; |
35
|
|
|
$backupStore = str_replace($filename, $backupFilename, $store); |
36
|
|
|
\copy($store, $backupStore); |
37
|
|
|
} |
38
|
|
|
\file_put_contents( |
39
|
|
|
$store, |
40
|
|
|
$writable->getTemplate() |
41
|
|
|
); |
42
|
|
|
} catch (\Exception $exception) { |
43
|
|
|
echo $exception->getMessage(); |
44
|
|
|
} |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
public static function getPsr4AutoloadDirectoryForNamespace(string $namespace) |
48
|
|
|
{ |
49
|
|
|
$find = explode('\\', $namespace)[0]; |
50
|
|
|
$reflector = new \ReflectionClass(ClassLoader::class); |
51
|
|
|
$vendorDir = \dirname(\dirname($reflector->getFileName())); |
52
|
|
|
$vendorFile = $vendorDir . '/composer/autoload_psr4.php'; |
53
|
|
|
if (\is_file($vendorFile)) { |
54
|
|
|
$namespaces = include $vendorFile; |
55
|
|
|
if (is_array($namespaces)) { |
56
|
|
|
foreach ($namespaces as $key => $value) { |
57
|
|
|
if (strpos($key, $find) === 0) { |
58
|
|
|
return str_replace( |
59
|
|
|
'\\', |
60
|
|
|
'/', |
61
|
|
|
$value[0] . str_replace($find, '', $namespace) |
62
|
|
|
); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
throw new \InvalidArgumentException('No path found for ' . $namespace); |
68
|
|
|
} |
69
|
|
|
throw new FileNotFoundException(); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|