Lines 100.00% 12 / 12
Methods 100.00% 2 / 2
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 create 100.00% 6 / 6 100.00% 1 / 1 6
 resolveCustom 100.00% 6 / 6 100.00% 1 / 1 3
22class CacheFactory
23{
24    /**
25     * Create a cache driver by name.
26     *
27     * @param string $name Driver name (`array`, `file`, `null`, or a container identifier)
28     * @param Container $container The application container, used to resolve custom drivers
29     * @param string $path Cache directory for the file driver (relative to root)
30     * @return CacheInterface The resolved driver
31     * @throws CacheDriverException If the driver name is unknown and cannot be resolved
32     */
33    public static function create(string $name, Container $container, string $path = 'storage/cache'): CacheInterface
34    {
35        return match ($name) {
36            'array' => new ArrayDriver(),
37            'file' => new FileDriver($path),
38            'null' => new NullDriver(),
39            'apcu' => new ApcuDriver(),
40            default => self::resolveCustom($name, $container),
41        };
42    }
43
44    /**
45     * Resolve a custom driver from the container.
46     *
47     * @param string $name Container identifier for the driver
48     * @param Container $container The application container
49     * @return CacheInterface The resolved driver
50     * @throws CacheDriverException If the container cannot resolve the name, or the result is not a cache driver
51     */
52    private static function resolveCustom(string $name, Container $container): CacheInterface
53    {
54        if (!$container->has($name)) {
55            throw new CacheDriverException($name);
56        }
57
58        $driver = $container->get($name);
59
60        if (!$driver instanceof CacheInterface) {
61            throw new CacheDriverException($name);
62        }
63
64        return $driver;
65    }
66}