Completed
Push — master ( 0ca994...bcdd07 )
by Neomerx
05:23
created

ExistInDbTableMultipleWithDoctrine::toBlock()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 0
1
<?php namespace Limoncello\Flute\Validation\Rules;
2
3
/**
4
 * Copyright 2015-2017 [email protected]
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
use Doctrine\DBAL\Connection;
20
use Limoncello\Flute\Contracts\Validation\ContextInterface;
21
use Limoncello\Flute\Contracts\Validation\ErrorCodes;
22
use Limoncello\Validation\Blocks\ProcedureBlock;
23
use Limoncello\Validation\Contracts\Blocks\ExecutionBlockInterface;
24
use Limoncello\Validation\Execution\BlockReplies;
25
use Limoncello\Validation\Rules\BaseRule;
26
27
/**
28
 * @package Limoncello\Flute
29
 */
30
final class ExistInDbTableMultipleWithDoctrine extends BaseRule
31
{
32
    /**
33
     * Property key.
34
     */
35
    const PROPERTY_TABLE_NAME = self::PROPERTY_LAST + 1;
36
37
    /**
38
     * Property key.
39
     */
40
    const PROPERTY_PRIMARY_NAME = self::PROPERTY_TABLE_NAME + 1;
41
42
    /**
43
     * @var string
44
     */
45
    private $tableName;
46
47
    /**
48
     * @var string
49
     */
50
    private $primaryName;
51
52
    /**
53
     * @param string $tableName
54
     * @param string $primaryName
55
     */
56
    public function __construct(string $tableName, string $primaryName)
57
    {
58
        $this->tableName   = $tableName;
59
        $this->primaryName = $primaryName;
60
    }
61
62
    /**
63
     * @inheritdoc
64
     */
65
    public function toBlock(): ExecutionBlockInterface
66
    {
67
        $customProperties = [
68
            self::PROPERTY_TABLE_NAME   => $this->getTableName(),
69
            self::PROPERTY_PRIMARY_NAME => $this->getPrimaryName(),
70
        ];
71
72
        return (new ProcedureBlock([self::class, 'execute']))
73
            ->setProperties($this->getStandardProperties() + $customProperties);
74
    }
75
76
    /**
77
     * @param mixed            $values
78
     * @param ContextInterface $context
79
     *
80
     * @return array
81
     *
82
     * @SuppressWarnings(PHPMD.StaticAccess)
83
     */
84
    public static function execute($values, ContextInterface $context): array
85
    {
86
        $count = 0;
87
88
        if (is_array($values) === true && empty($values) === false) {
89
            /** @var Connection $connection */
90
            $connection   = $context->getContainer()->get(Connection::class);
91
            $builder      = $connection->createQueryBuilder();
92
            $tableName    = $context->getProperties()->getProperty(self::PROPERTY_TABLE_NAME);
93
            $primaryName  = $context->getProperties()->getProperty(self::PROPERTY_PRIMARY_NAME);
94
            $placeholders = [];
95
            foreach ($values as $value) {
96
                $placeholders[] = $builder->createPositionalParameter($value);
97
            }
98
            $statement = $builder
99
                ->select('count(*)')
100
                ->from($tableName)
101
                ->where($builder->expr()->in($primaryName, $placeholders))
102
                ->execute();
103
104
            $count = $statement->fetchColumn();
105
        }
106
107
        $reply = $count > 0 ?
108
            BlockReplies::createSuccessReply($values) :
109
            BlockReplies::createErrorReply($context, $values, ErrorCodes::EXIST_IN_DATABASE_MULTIPLE);
110
111
        return $reply;
112
    }
113
114
    /**
115
     * @return string
116
     */
117
    public function getTableName(): string
118
    {
119
        return $this->tableName;
120
    }
121
122
    /**
123
     * @return string
124
     */
125
    public function getPrimaryName(): string
126
    {
127
        return $this->primaryName;
128
    }
129
}
130