1<?php
2
3declare(strict_types=1);
4
5namespace Metadata\Driver;
6
7use Metadata\ClassMetadata;
8
9/**
10 * Base file driver implementation.
11 *
12 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
13 */
14abstract class AbstractFileDriver implements AdvancedDriverInterface
15{
16    /**
17     * @var FileLocatorInterface|FileLocator
18     */
19    private $locator;
20
21    public function __construct(FileLocatorInterface $locator)
22    {
23        $this->locator = $locator;
24    }
25
26    public function loadMetadataForClass(\ReflectionClass $class): ?ClassMetadata
27    {
28        if (null === $path = $this->locator->findFileForClass($class, $this->getExtension())) {
29            return null;
30        }
31
32        return $this->loadMetadataFromFile($class, $path);
33    }
34
35    /**
36     * {@inheritDoc}
37     */
38    public function getAllClassNames(): array
39    {
40        if (!$this->locator instanceof AdvancedFileLocatorInterface) {
41            throw new \RuntimeException(sprintf('Locator "%s" must be an instance of "AdvancedFileLocatorInterface".', get_class($this->locator)));
42        }
43
44        return $this->locator->findAllClasses($this->getExtension());
45    }
46
47    /**
48     * Parses the content of the file, and converts it to the desired metadata.
49     */
50    abstract protected function loadMetadataFromFile(\ReflectionClass $class, string $file): ?ClassMetadata;
51
52    /**
53     * Returns the extension of the file.
54     */
55    abstract protected function getExtension(): string;
56}
57