|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Crell\Serde\Analyzer; |
| 6 | + |
| 7 | +use Crell\AttributeUtils\Analyzer; |
| 8 | +use Crell\AttributeUtils\ClassAnalyzer; |
| 9 | +use Crell\Serde\Serde; |
| 10 | +use Crell\Serde\SerdeCommon; |
| 11 | +use Symfony\Component\Yaml\Yaml; |
| 12 | + |
| 13 | +/** |
| 14 | + * @todo Instead of a cache-style directory, let callers specify the exact file to read. |
| 15 | + * The intent isn't to use as a cache, but to let people hand-write YAML files instead of |
| 16 | + * using attributes. |
| 17 | + */ |
| 18 | +class YamlFileAnalyzer implements ClassAnalyzer |
| 19 | +{ |
| 20 | + private readonly string $directory; |
| 21 | + |
| 22 | + public function __construct( |
| 23 | + string $directory, |
| 24 | + private readonly Serde $serde = new SerdeCommon(new Analyzer()), |
| 25 | + ) { |
| 26 | + $this->directory = rtrim($directory, '/\\'); |
| 27 | + } |
| 28 | + |
| 29 | + public function save(object $data, string $class, string $attribute, array $scopes = []): void |
| 30 | + { |
| 31 | + $yaml = $this->serde->serialize($data, format: 'yaml'); |
| 32 | + |
| 33 | + $filename = $this->getFileName($class, $attribute, $scopes); |
| 34 | + |
| 35 | + $this->ensureDirectory($filename); |
| 36 | + |
| 37 | + file_put_contents($filename, $yaml); |
| 38 | + } |
| 39 | + |
| 40 | + private function ensureDirectory(string $filename): void |
| 41 | + { |
| 42 | + $dir = dirname($filename); |
| 43 | + if (!is_dir($dir)) { |
| 44 | + if (!mkdir($dir, 0777, true) && !is_dir($dir)) { |
| 45 | + throw new \RuntimeException(sprintf('Directory "%s" was not created', $dir)); |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + private function getFileName(string $class, string $attribute, array $scopes): string |
| 51 | + { |
| 52 | + return $this->directory |
| 53 | + . DIRECTORY_SEPARATOR |
| 54 | + . str_replace('\\', '_', $attribute) |
| 55 | + . DIRECTORY_SEPARATOR |
| 56 | + . str_replace('\\', '_', $class) |
| 57 | + . DIRECTORY_SEPARATOR |
| 58 | + . (implode('_', $scopes) ?: 'all_scopes') |
| 59 | + . '.yaml'; |
| 60 | + } |
| 61 | + |
| 62 | + public function analyze(object|string $class, string $attribute, array $scopes = []): object |
| 63 | + { |
| 64 | + // Everything is easier if we normalize to a class first. |
| 65 | + // Because anon classes have generated internal class names, they work, too. |
| 66 | + $class = is_string($class) ? $class : $class::class; |
| 67 | + |
| 68 | + $classFile = $this->getFileName($class, $attribute, $scopes); |
| 69 | + |
| 70 | + $yaml = Yaml::parseFile($classFile); |
| 71 | + |
| 72 | + $result = $this->serde->deserialize($yaml, from: 'array', to: $attribute); |
| 73 | + |
| 74 | + return $result; |
| 75 | + } |
| 76 | +} |
0 commit comments