PdoAllWebsites::__construct()   B
last analyzed

Complexity

Conditions 6
Paths 2

Size

Total Lines 52

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 7.1598

Importance

Changes 0
Metric Value
dl 0
loc 52
ccs 15
cts 22
cp 0.6818
rs 8.425
c 0
b 0
f 0
cc 6
nc 2
nop 3
crap 7.1598

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace Germania\Websites;
3
4
class PdoAllWebsites extends Websites implements WebsitesInterface
5
{
6
7
    /**
8
     * @var string
9
     */
10
    public $table = 'pages';
11
12
    /**
13
     * @param PDO             $pdo
14
     * @param string          $table    Websites table name
15
     * @param WebsiteAbstract $website  Optional: Website template object
16
     */
17 5
    public function __construct( \PDO $pdo, $table, WebsiteAbstract $website = null  )
18
    {
19 5
        $this->table = $table;
20
21
        // ID is listed twice here in order to use it with FETCH_UNIQUE as array key
22
        $sql = "SELECT
23
        id,
24
        id,
25
        title,
26
        via,
27
        route,
28
        route_name,
29
        content_file,
30
        middleware,
31
        controller,
32
        template,
33
        dom_id,
34
        javascripts,
35
        stylesheets,
36
        is_active
37
38 5
        FROM {$this->table}
39
40 1
        WHERE 1";
41
42 5
        $stmt = $pdo->prepare( $sql );
43
44 5
        $stmt->setFetchMode( \PDO::FETCH_CLASS, $website ? get_class($website) : Website::class );
45
46 5
        if (!$stmt->execute()):
47
            throw new \RuntimeException("Could not retrieve Websites from database");
48
        endif;
49
50 2
        $this->websites = array_map(function($row) {
51
52
            // Cast numeric is_active field to integer
53 5
            $row->is_active = (int) $row->is_active;
54
55
            // Split into array
56 5
            if (isset($row->javascripts)):
57
                $row->javascripts = preg_split("/[\s,]+/", trim($row->javascripts));
58
            endif;
59 5
            if (isset($row->stylesheets)):
60
                $row->stylesheets = preg_split("/[\s,]+/", trim($row->stylesheets));
61
            endif;
62 5
            if (isset($row->via)):
63
                $row->via = preg_split("/[\s,]+/", trim($row->via));
64
            endif;
65
66 5
            return $row;
67 5
        }, $stmt->fetchAll(\PDO::FETCH_UNIQUE));
68 5
    }
69
70
}
71
72