Completed
Push — master ( 474113...884aa1 )
by Carsten
02:20
created

PdoRouteWebsiteFactory::__construct()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 24
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 0
cts 7
cp 0
rs 8.9713
c 0
b 0
f 0
cc 3
eloc 6
nc 2
nop 3
crap 12
1
<?php
2
namespace Germania\Websites;
3
4
use Interop\Container\ContainerInterface;
5
6
class PdoRouteWebsiteFactory implements ContainerInterface
7
{
8
9
    /**
10
     * @var string
11
     */
12
    public $table = 'pages';
13
14
    /**
15
     * @var \PDOStatement
16
     */
17
    public $stmt;
18
19
    /**
20
     * @param PDO             $pdo
21
     * @param WebsiteAbstract $website  Optional: Website template object
22
     * @param string          $table    Optional: Websites table name
23
     */
24
    public function __construct( \PDO $pdo, WebsiteAbstract $website = null, $table = null  )
25
    {
26
        $this->table = $table ?: $this->table;
27
28
        $sql = "SELECT
29
        id,
30
        title,
31
        route,
32
        content_file,
33
        template,
34
        dom_id,
35
        javascripts,
36
        stylesheets,
37
        is_active
38
39
        FROM {$this->table}
40
41
        WHERE route = :route
42
        LIMIT 1";
43
44
        $this->stmt = $pdo->prepare( $sql );
45
        $this->stmt->setFetchMode( \PDO::FETCH_CLASS, $website ? get_class($website) : Website::class );
46
47
    }
48
49
50
    public function __invoke( $route )
51
    {
52
        return $this->get( $route );
53
    }
54
55
56
57
    public function has ($route) {
58
        $this->executeStatement( $route );
59
        return (bool) $this->stmt->fetch();
60
    }
61
62
63
    public function get ($route) {
64
        $this->executeStatement( $route );
65
66
        if ($row = $this->stmt->fetch()) {
67
            // Cast numeric is_active field to integer
68
            $row->is_active = (int) $row->is_active;
69
            // Split into array
70
            if (isset($row->javascripts)):
71
                $row->javascripts = explode(",", $row->javascripts);
72
            endif;
73
            if (isset($row->stylesheets)):
74
                $row->stylesheets = explode(",", $row->stylesheets);
75
            endif;
76
77
            return $row;
78
        }
79
80
        throw new WebsiteNotFoundException("Could not find website for route '$route'");
81
    }
82
83
84
    protected function executeStatement ($route) {
85
        if (!$this->stmt->execute([
86
            ':route' => $route
87
        ])):
88
            throw new \RuntimeException("Could not execute PDOStatement", [
89
                'table' => $this->table,
90
                'route' => $route
91
            ]);
92
        endif;
93
94
        return true;
95
    }
96
97
}
98
99