Completed
Push — master ( 0eeb04...4002ae )
by Oscar
02:31
created

TableFactory::get()   B

Complexity

Conditions 5
Paths 13

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 24
rs 8.5125
cc 5
eloc 13
nc 13
nop 2
1
<?php
2
3
namespace SimpleCrud;
4
5
/**
6
 * Class to create instances of tables.
7
 */
8
class TableFactory implements TableFactoryInterface
9
{
10
    protected $namespaces = [];
11
    protected $default;
12
13
    /**
14
     * Add a namespace for the entities classes.
15
     *
16
     * @param string $namespace
17
     *
18
     * @return self
19
     */
20
    public function addNamespace($namespace)
21
    {
22
        array_unshift($this->namespaces, $namespace);
23
24
        return $this;
25
    }
26
27
    /**
28
     * Set whether the entities are autocreated or not.
29
     *
30
     * @param string $default Default class used by the tables
31
     *
32
     * @return self
33
     */
34
    public function setAutocreate($default = 'SimpleCrud\\Table')
35
    {
36
        $this->default = $default;
37
38
        return $this;
39
    }
40
41
    /**
42
     * @see TableFactoryInterface
43
     *
44
     * {@inheritdoc}
45
     */
46
    public function get(SimpleCrud $db, $name)
47
    {
48
        try {
49
            $className = ucfirst($name);
50
51
            foreach ($this->namespaces as $namespace) {
52
                $class = $namespace.$className;
53
54
                if (class_exists($class)) {
55
                    return new $class($db, $name);
56
                }
57
            }
58
59
            if ($this->default) {
60
                $class = $this->default;
61
62
                return new $class($db, $name);
63
            }
64
        } catch (\Exception $exception) {
65
            throw new SimpleCrudException("Error getting the '{$name}' table", 0, $exception);
66
        }
67
68
        throw new SimpleCrudException("Table '{$name}' not found");
69
    }
70
}
71