Completed
Pull Request — master (#188)
by Vincent
05:20
created

EntityContext::getEntityIdentifiers()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 14
rs 9.4286
cc 2
eloc 8
nc 2
nop 3
1
<?php
2
3
namespace Knp\FriendlyContexts\Context;
4
5
use Behat\Gherkin\Node\TableNode;
6
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
7
use Doctrine\DBAL\Connection;
8
use Doctrine\DBAL\Sharding\PoolingShardConnection;
9
use Doctrine\DBAL\Sharding\PoolingShardManager;
10
use Doctrine\ORM\EntityManager;
11
use Doctrine\ORM\Tools\SchemaTool;
12
13
class EntityContext extends Context
14
{
15
    /**
16
     * @Given /^the following ([\w ]+):?$/
17
     */
18
    public function theFollowing($name, TableNode $table)
19
    {
20
        $entityName = $this->resolveEntity($name)->getName();
21
22
        $rows = $table->getRows();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 4 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
23
        $headers = array_shift($rows);
24
25
        foreach ($rows as $row) {
26
            $values     = array_combine($headers, $row);
27
            $entity     = new $entityName;
28
            $reflection = new \ReflectionClass($entity);
29
30 View Code Duplication
            do {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
31
                $this
32
                    ->getRecordBag()
33
                    ->getCollection($reflection->getName())
34
                    ->attach($entity, $values)
35
                ;
36
                $reflection = $reflection->getParentClass();
37
            } while (false !== $reflection);
38
39
            $this
40
                ->getEntityHydrator()
41
                ->hydrate($this->getEntityManager(), $entity, $values)
42
                ->completeRequired($this->getEntityManager(), $entity)
43
            ;
44
45
            $this->getEntityManager()->persist($entity);
46
        }
47
48
        $this->getEntityManager()->flush();
49
    }
50
51
    /**
52
     * @Given /^there (?:is|are) (\d+) ((?!\w* like)\w*)$/
53
     */
54
    public function thereIs($nbr, $name)
55
    {
56
        $entityName = $this->resolveEntity($name)->getName();
57
58
        for ($i = 0; $i < $nbr; $i++) {
59
            $entity = new $entityName;
60
            $this
61
                ->getRecordBag()
62
                ->getCollection($entityName)
63
                ->attach($entity)
64
            ;
65
            $this
66
                ->getEntityHydrator()
67
                ->completeRequired($this->getEntityManager(), $entity)
68
            ;
69
70
            $this->getEntityManager()->persist($entity);
71
        }
72
73
        $this->getEntityManager()->flush();
74
    }
75
76
    /**
77
     * @Given /^there (?:is|are) (\d+) (.*) like:?$/
78
     */
79
    public function thereIsLikeFollowing($nbr, $name, TableNode $table)
80
    {
81
        $entityName = $this->resolveEntity($name)->getName();
82
83
        $rows = $table->getRows();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 4 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
84
        $headers = array_shift($rows);
85
86
        for ($i = 0; $i < $nbr; $i++) {
87
            $row = $rows[$i % count($rows)];
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 4 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
88
            $values = array_combine($headers, $row);
89
            $entity = new $entityName;
90
            $this
91
                ->getRecordBag()
92
                ->getCollection($entityName)
93
                ->attach($entity, $values)
94
            ;
95
            $this
96
                ->getEntityHydrator()
97
                ->hydrate($this->getEntityManager(), $entity, $values)
98
                ->completeRequired($this->getEntityManager(), $entity)
99
            ;
100
101
            $this->getEntityManager()->persist($entity);
102
        }
103
104
        $this->getEntityManager()->flush();
105
    }
106
107
    /**
108
     * @Given /^(\w+) (.+) should have been (created|deleted)$/
109
     */
110
    public function entitiesShouldHaveBeen($expected, $entity, $state)
111
    {
112
        $expected = (int) $expected;
113
114
        $entityName = $this->resolveEntity($entity)->getName();
115
        $collection = $this
116
            ->getRecordBag()
117
            ->getCollection($entityName)
118
        ;
119
120
        $records = array_map(function ($e) { return $e->getEntity(); }, $collection->all());
121
        $entities = $this
122
            ->getEntityManager()
123
            ->getRepository($entityName)
124
            ->createQueryBuilder('o')
125
            ->resetDQLParts()
126
            ->select('o')
127
            ->from($entityName, ' o')
128
            ->getQuery()
129
            ->getResult()
130
        ;
131
132
        if ($state === 'created') {
133
            $diff = $this->compareArray($entities, $records);
134
            foreach ($diff as $e) {
135
                $collection->attach($e);
136
            }
137
        } else {
138
            $diff = $this->compareArray($records, $entities);
139
        }
140
        $real = count($diff);
141
142
        $this
143
            ->getAsserter()
144
            ->assertEquals(
145
                $real,
146
                $expected,
147
                sprintf('%s %s should have been %s, %s actually', $expected, $entity, $state, $real)
148
            )
149
        ;
150
    }
151
152
    /**
153
     * @Then /^should be (\d+) (.*) like:?$/
154
     */
155
    public function existLikeFollowing($nbr, $name, TableNode $table)
156
    {
157
        $entityName = $this->resolveEntity($name)->getName();
158
159
        $rows = $table->getRows();
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 4 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
160
        $headers = array_shift($rows);
161
162
        for ($i = 0; $i < $nbr; $i++) {
163
            $row = $rows[$i % count($rows)];
164
165
            $values = array_combine($headers, $row);
166
            $object = $this->getEntityManager()
167
                ->getRepository($entityName)
168
                ->findOneBy($values);
169
170
            if (is_null($object)) {
171
                throw new \Exception(sprintf("There is no object for the following criteria: %s", json_encode($values)));
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal There is no object for the following criteria: %s does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
172
            }
173
            $this->getEntityManager()->refresh($object);
174
        }
175
    }
176
177
    /**
178
     * @BeforeScenario
179
     */
180
    public function beforeScenario($event)
181
    {
182
        $this->storeTags($event);
183
184
        if ($this->hasTags([ 'reset-schema', '~not-reset-schema' ])) {
185
            foreach ($this->getEntityManagers() as $name => $entityManager) {
186
                $connection = $entityManager->getConnection();
187
                if ($connection instanceof PoolingShardConnection) {
188
                    $poolingShardManager = $this->getPoolingShardManager($connection);
189
                    foreach ($poolingShardManager->getShards() as $shardId) {
190
                        // Switch to shard database
191
                        $connection->connect($shardId['id']);
192
                        $this->resetSchema($entityManager);
193
                    }
194
                    // Back to global
195
                    $connection->connect(0);
196
                } else {
197
                    $this->resetSchema($entityManager);
198
                }
199
            }
200
        }
201
    }
202
203
    /**
204
     * @AfterScenario
205
     */
206
    public function afterScenario($event)
0 ignored issues
show
Unused Code introduced by
The parameter $event is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
207
    {
208
        $this->getRecordBag()->clear();
209
        $this->getUniqueCache()->clear();
210
        $this->getEntityManager()->clear();
211
    }
212
213
    /**
214
     * @param EntityManager $entityManager
215
     */
216
    protected function resetSchema(EntityManager $entityManager)
217
    {
218
        $metadata = $this->getMetadata($entityManager);
219
        if (!empty($metadata)) {
220
            $tool = new SchemaTool($entityManager);
221
            $tool->dropSchema($metadata);
222
            $tool->createSchema($metadata);
223
        }
224
    }
225
226
    protected function compareArray(array $a1, array $a2)
227
    {
228
        $diff = [];
229
        foreach ($a1 as $e) {
230
            if (!in_array($e, $a2)) {
231
                $diff[] = $e;
232
            }
233
        }
234
235
        return $diff;
236
    }
237
238
    /**
239
     * Find PoolingShardManager related to connection.
240
     *
241
     * Cannot directly find PoolingShardManager by EntityManager's name cause
242
     * PoolingShardManager is created from Connection's name.
243
     *
244
     * @param PoolingShardConnection $poolingShardConnection
245
     *
246
     * @return PoolingShardManager
247
     *
248
     * @throws \LogicException Unable to find PoolingShardManager related to this PoolingShardConnection.
249
     */
250
    protected function getPoolingShardManager(PoolingShardConnection $poolingShardConnection)
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $poolingShardConnection exceeds the maximum configured length of 20.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
251
    {
252
        foreach ($this->getConnections() as $name => $connection) {
253
            if ($connection === $poolingShardConnection
254
                && $this->getKernel()->getContainer()->has(sprintf('doctrine.dbal.%s_shard_manager', $name))
255
            ) {
256
                return $this->get(sprintf('doctrine.dbal.%s_shard_manager', $name));
257
            }
258
        }
259
260
        throw new \LogicException('Unable to find PoolingShardManager related to this PoolingShardConnection.');
261
    }
262
263
    /**
264
     * @param EntityManager $entityManager
265
     *
266
     * @return ClassMetadata[]
267
     */
268
    protected function getMetadata(EntityManager $entityManager)
269
    {
270
        return $entityManager->getMetadataFactory()->getAllMetadata();
271
    }
272
273
    /**
274
     * @return EntityManager[]
275
     */
276
    protected function getEntityManagers()
277
    {
278
        return $this->get('doctrine')->getManagers();
279
    }
280
281
    /**
282
     * @return Connection[]
283
     */
284
    protected function getConnections()
285
    {
286
        return $this->get('doctrine')->getConnections();
287
    }
288
289
    protected function getDefaultOptions()
290
    {
291
        return [
292
            'Entities' => [''],
293
        ];
294
    }
295
}
296