DbTablePopulator::populateTables()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4.0039

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 18
c 1
b 0
f 0
nc 6
nop 1
dl 0
loc 30
ccs 15
cts 16
cp 0.9375
crap 4.0039
rs 9.6666
1
<?php
2
/**
3
 * This file is part of graze/sprout.
4
 *
5
 * Copyright © 2018 Nature Delivered Ltd. <https://www.graze.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @license https://github.com/graze/sprout/blob/master/LICENSE.md
11
 * @link    https://github.com/graze/sprout
12
 */
13
14
namespace Graze\Sprout\Db;
15
16
use Graze\Sprout\Parser\ParsedSchema;
17
use Graze\Sprout\Parser\TableFilterer;
18
use Graze\Sprout\Parser\TablePopulatorInterface;
19
use PDO;
20
21
class DbTablePopulator implements TablePopulatorInterface
22
{
23
    /** @var PdoFactory */
24
    private $pdoFactory;
25
    /** @var TableFilterer */
26
    private $tableFilterer;
27
28
    /**
29
     * DbTablePopulator constructor.
30
     *
31
     * @param PdoFactory|null    $pdoFactory
32
     * @param TableFilterer|null $tableFilterer
33
     */
34 4
    public function __construct(PdoFactory $pdoFactory = null, TableFilterer $tableFilterer = null)
35
    {
36 4
        $this->pdoFactory = $pdoFactory ?: new PdoFactory();
37 4
        $this->tableFilterer = $tableFilterer ?: new TableFilterer();
38 4
    }
39
40
    /**
41
     * Populate the tables in a `ParsedSchema`
42
     *
43
     * @param ParsedSchema $parsedSchema
44
     *
45
     * @return ParsedSchema|null
46
     */
47 4
    public function populateTables(ParsedSchema $parsedSchema)
48
    {
49 4
        if (count($parsedSchema->getTables()) === 0) {
50 2
            $connection = $parsedSchema->getSchemaConfig()->getConnection();
51 2
            $pdo = $this->pdoFactory->getPdo($connection);
52
53 2
            $statement = $pdo->prepare(
54 2
                'SELECT table_name
55
                FROM INFORMATION_SCHEMA.TABLES 
56
                WHERE table_schema = :schema
57
                AND table_type = "BASE TABLE"'
58
            );
59 2
            $statement->execute(['schema' => $parsedSchema->getSchemaName()]);
60 2
            $tables = $statement->fetchAll(PDO::FETCH_COLUMN);
61
62 2
            if (count($parsedSchema->getSchemaConfig()->getExcludes()) > 0) {
63 1
                $tables = $this->tableFilterer->filter(
64 1
                    $tables,
65 1
                    $parsedSchema->getSchemaConfig()->getExcludes()
66
                );
67
            }
68
69 2
            $parsedSchema->setTables($tables);
70
        }
71
72 4
        if (count($parsedSchema->getTables()) === 0) {
73
            return null;
74
        }
75
76 4
        return $parsedSchema;
77
    }
78
}
79