Completed
Push — master ( 3b855f...5b0fc9 )
by Oscar
02:15
created

Container::create()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
rs 9.4285
cc 3
eloc 6
nc 3
nop 2
1
<?php
2
3
namespace FlyCrud;
4
5
use League\Flysystem\FilesystemInterface;
6
7
class Container
8
{
9
    protected $repositories = [];
10
11
    /**
12
     * Create a container with various repositories.
13
     * 
14
     * @param string $name
15
     * @param array  $args
16
     */
17
    public static function __callStatic($name, $args)
18
    {
19
        $class = __NAMESPACE__.'\\'.ucfirst($name);
20
21
        if (!class_exists($class)) {
22
            throw new BadMethodCallException(sprintf('The repository "%s" does not exists', $class));
23
        }
24
25
        return self::create(array_shift($args), $class);
26
    }
27
28
    /**
29
     * Creates a container with a repository for each subdirectory.
30
     * 
31
     * @param FilesystemInterface $filesystem
32
     * @param string              $class
33
     * 
34
     * @return static
35
     */
36
    private static function create(FilesystemInterface $filesystem, $class)
37
    {
38
        $container = new static();
39
40
        foreach ($filesystem->listContents() as $info) {
41
            if ($info['type'] === 'dir') {
42
                $container->{$info['filename']} = new $class($filesystem, $info['filename']);
43
            }
44
        }
45
46
        return $container;
47
    }
48
49
    /**
50
     * Returns a repository.
51
     * 
52
     * @param string $name
53
     * 
54
     * @return Repository
55
     */
56
    public function __get($name)
57
    {
58
        if (!isset($this->repositories[$name])) {
59
            throw new \InvalidArgumentException(sprintf('The repository %s does not exist', $name));
60
        }
61
62
        return $this->repositories[$name];
63
    }
64
65
    /**
66
     * Adds a new repository to the container.
67
     *
68
     * @param string     $name
69
     * @param Repository $repository
70
     */
71
    public function __set($name, Repository $repository)
72
    {
73
        $this->repositories[$name] = $repository;
74
    }
75
}
76