Completed
Pull Request — master (#11)
by Romain
03:32
created

QueryPart   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 54
c 0
b 0
f 0
wmc 11
lcom 1
cbo 1
ccs 28
cts 28
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A add() 0 6 1
A needTable() 0 9 2
B ensureNeededTablesArePresent() 0 18 5
A isAtLeastOneSnippetHasNeededTable() 0 12 3
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($snippets as $snippet)
32
        {
33 46
            if(! $snippet instanceof NeedTableAware)
34 46
            {
35 3
                throw new \LogicException('Snippet has not expected NeedTableAware type');
36
            }
37 43
        }
38
39 43
        foreach($this->neededTableNames as $tableName)
40
        {
41 9
            if(! $this->isAtLeastOneSnippetHasNeededTable($tableName, $snippets))
42 9
            {
43 3
                throw new \LogicException("One of query parts you used needs $tableName table");
44
            }
45 40
        }
46 40
    }
47
48 9
    private function isAtLeastOneSnippetHasNeededTable($tableName, array $snippets)
49
    {
50 9
        foreach($snippets as $snippet)
51
        {
52 9
            if($snippet->hasNeededTable($tableName))
53 9
            {
54 6
                return true;
55
            }
56 4
        }
57
58 3
        return false;
59
    }
60
}
61