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

QueryPart   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 94.74%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 2
dl 0
loc 51
ccs 18
cts 19
cp 0.9474
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A add() 0 6 1
A needTable() 0 9 2
A ensureNeededTablesArePresent() 0 10 3
A isAtLeastOneSnippetHasNeededTable() 0 17 4
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