Completed
Pull Request — master (#1)
by Romain
02:07
created

QueryPart::needTable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 4
cts 4
cp 1
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Puzzle\QueryBuilder\Queries\Snippets\Builders;
6
7
use Puzzle\QueryBuilder\Queries\Snippets\NeedTableAware;
8
use Puzzle\QueryBuilder\Query;
9
10
trait QueryPart
11
{
12
    private
13
        $neededTableNames = [];
14
15 10
    public function add(\Puzzle\QueryBuilder\QueryPart $queryPart): Query
16
    {
17 10
        $queryPart->build($this);
18
19 10
        return $this;
20
    }
21
22 9
    public function needTable($tableName): Query
23
    {
24 9
        if(! in_array($tableName, $this->neededTableNames))
25
        {
26 9
            $this->neededTableNames[] = $tableName;
27
        }
28
29 9
        return $this;
30
    }
31
32 46
    public function ensureNeededTablesArePresent(array $snippets): void
33
    {
34 46
        foreach($this->neededTableNames as $tableName)
35
        {
36 9
            if(! $this->isAtLeastOneSnippetHasNeededTable($tableName, $snippets))
37
            {
38 3
                throw new \LogicException("One of query parts you used needs $tableName table");
39
            }
40
        }
41 43
    }
42
43 9
    private function isAtLeastOneSnippetHasNeededTable($tableName, array $snippets): bool
44
    {
45 9
        foreach($snippets as $snippet)
46
        {
47 9
            if(! $snippet instanceof NeedTableAware)
48
            {
49
                throw new \LogicException('Snippet has not expected NeedTableAware type');
50
            }
51
52 9
            if($snippet->hasNeededTable($tableName))
53
            {
54 6
                return true;
55
            }
56
        }
57
58 3
        return false;
59
    }
60
}
61