Completed
Pull Request — master (#11)
by Romain
02:27
created

QueryPart::isAtLeastOneSnippetHasNeededTable()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4.016

Importance

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