| 1: | <?php |
| 2: | |
| 3: | namespace LaravelUi5\Core\Infrastructure; |
| 4: | |
| 5: | use Illuminate\Support\Facades\File; |
| 6: | use Illuminate\Support\Str; |
| 7: | use LaravelUi5\Core\Infrastructure\Contracts\Ui5SourceOverrideStoreInterface; |
| 8: | |
| 9: | class Ui5SourceOverrideStore implements Ui5SourceOverrideStoreInterface |
| 10: | { |
| 11: | protected string $path; |
| 12: | |
| 13: | |
| 14: | |
| 15: | |
| 16: | protected array $overrides = []; |
| 17: | |
| 18: | public function __construct(string $path = '.ui5-sources.php') |
| 19: | { |
| 20: | $this->path = $path; |
| 21: | |
| 22: | $this->loadSourceOverrides(); |
| 23: | } |
| 24: | |
| 25: | protected function loadSourceOverrides(): void |
| 26: | { |
| 27: | $path = base_path($this->path); |
| 28: | |
| 29: | if (!is_file($path)) { |
| 30: | return; |
| 31: | } |
| 32: | |
| 33: | $config = require $path; |
| 34: | |
| 35: | $modules = $config['modules'] ?? []; |
| 36: | |
| 37: | $overrides = []; |
| 38: | |
| 39: | foreach ($modules as $moduleClass => $relativePath) { |
| 40: | if (!is_string($moduleClass) || !is_string($relativePath)) { |
| 41: | continue; |
| 42: | } |
| 43: | |
| 44: | $absolutePath = base_path($relativePath); |
| 45: | |
| 46: | if (is_dir($absolutePath)) { |
| 47: | $overrides[$moduleClass] = $absolutePath; |
| 48: | } |
| 49: | } |
| 50: | |
| 51: | $this->overrides = $overrides; |
| 52: | } |
| 53: | |
| 54: | public function all(): array |
| 55: | { |
| 56: | return $this->overrides; |
| 57: | } |
| 58: | |
| 59: | public function get(string $moduleClass): ?string |
| 60: | { |
| 61: | if (isset($this->overrides[$moduleClass])) { |
| 62: | return $this->overrides[$moduleClass]; |
| 63: | } |
| 64: | |
| 65: | return null; |
| 66: | } |
| 67: | |
| 68: | public function put(string $moduleClass, string $srcPath): void |
| 69: | { |
| 70: | $path = base_path($this->path); |
| 71: | |
| 72: | $config = File::exists($path) |
| 73: | ? require $path |
| 74: | : ['modules' => []]; |
| 75: | |
| 76: | $config['modules'][$moduleClass] = $this->relativePath($srcPath); |
| 77: | |
| 78: | File::put($path, $this->export($config)); |
| 79: | } |
| 80: | |
| 81: | private function export(array $config): string |
| 82: | { |
| 83: | $data = preg_replace( |
| 84: | ['/array \(/', '/\)(,?)/'], |
| 85: | ['[', ']$1'], |
| 86: | var_export($config, true) |
| 87: | ); |
| 88: | return <<<PHP |
| 89: | <?php |
| 90: | return {$data}; |
| 91: | PHP; |
| 92: | } |
| 93: | |
| 94: | private function relativePath(string $path): string |
| 95: | { |
| 96: | return Str::after($path, base_path() . DIRECTORY_SEPARATOR); |
| 97: | } |
| 98: | } |
| 99: | |