Completed
Pull Request — master (#190)
by
unknown
03:11
created

EntityContext::afterScenario()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 6
rs 9.4285
cc 1
eloc 4
nc 1
nop 1
1
<?php
2
3
namespace Knp\FriendlyContexts\Context;
4
5
use Behat\Gherkin\Node\TableNode;
6
use Doctrine\ORM\EntityManager;
7
use Doctrine\ORM\Tools\SchemaTool;
8
use Symfony\Component\PropertyAccess\PropertyAccess;
9
10
class EntityContext extends Context
11
{
12
    /**
13
     * @Given /^the following ([\w ]+):?$/
14
     */
15
    public function theFollowing($name, TableNode $table)
16
    {
17
        $entityName = $this->resolveEntity($name)->getName();
18
19
        $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...
20
        $headers = array_shift($rows);
21
22
        foreach ($rows as $row) {
23
            $values     = array_combine($headers, $row);
24
            $entity     = new $entityName;
25
            $reflection = new \ReflectionClass($entity);
26
27 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...
28
                $this
29
                    ->getRecordBag()
30
                    ->getCollection($reflection->getName())
31
                    ->attach($entity, $values)
32
                ;
33
                $reflection = $reflection->getParentClass();
34
            } while (false !== $reflection);
35
36
            $this
37
                ->getEntityHydrator()
38
                ->hydrate($this->getManager(), $entity, $values)
39
                ->completeRequired($this->getManager(), $entity)
40
            ;
41
42
            $this->getManager()->persist($entity);
43
        }
44
45
        $this->getManager()->flush();
46
    }
47
48
    /**
49
     * @Given /^there (?:is|are) (\d+) ((?!\w* like)\w*)$/
50
     */
51
    public function thereIs($nbr, $name)
52
    {
53
        $entityName = $this->resolveEntity($name)->getName();
54
55
        for ($i = 0; $i < $nbr; $i++) {
56
            $entity = new $entityName;
57
            $this
58
                ->getRecordBag()
59
                ->getCollection($entityName)
60
                ->attach($entity)
61
            ;
62
            $this
63
                ->getEntityHydrator()
64
                ->completeRequired($this->getManager(), $entity)
65
            ;
66
67
            $this->getManager()->persist($entity);
68
        }
69
70
        $this->getManager()->flush();
71
    }
72
73
    /**
74
     * @Given /^there (?:is|are) (\d+) (.*) like:?$/
75
     */
76
    public function thereIsLikeFollowing($nbr, $name, TableNode $table)
77
    {
78
        $entityName = $this->resolveEntity($name)->getName();
79
80
        $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...
81
        $headers = array_shift($rows);
82
83
        for ($i = 0; $i < $nbr; $i++) {
84
            $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...
85
            $values = array_combine($headers, $row);
86
            $entity = new $entityName;
87
            $this
88
                ->getRecordBag()
89
                ->getCollection($entityName)
90
                ->attach($entity, $values)
91
            ;
92
            $this
93
                ->getEntityHydrator()
94
                ->hydrate($this->getManager(), $entity, $values)
95
                ->completeRequired($this->getManager(), $entity)
96
            ;
97
98
            $this->getManager()->persist($entity);
99
        }
100
101
        $this->getManager()->flush();
102
    }
103
104
    /**
105
     * @Given /^(\w+) (.+) should have been (created|deleted)$/
106
     */
107
    public function entitiesShouldHaveBeen($expected, $entity, $state)
108
    {
109
        $expected = (int) $expected;
110
111
        $entityName = $this->resolveEntity($entity)->getName();
112
        $collection = $this
113
            ->getRecordBag()
114
            ->getCollection($entityName)
115
        ;
116
117
        $records = array_map(function ($e) { return $e->getEntity(); }, $collection->all());
118
        $entities = $this
119
            ->getManager()
120
            ->getRepository($entityName)
121
            ->createQueryBuilder('o')
122
            ->resetDQLParts()
123
            ->select('o')
124
            ->from($entityName, ' o')
125
            ->getQuery()
126
            ->getResult()
127
        ;
128
129
        if ($state === 'created') {
130
            $diff = $this->compareArray($entities, $records);
131
            foreach ($diff as $e) {
132
                $collection->attach($e);
133
            }
134
        } else {
135
            $diff = $this->compareArray($records, $entities);
136
        }
137
        $real = count($diff);
138
139
        $this
140
            ->getAsserter()
141
            ->assertEquals(
142
                $real,
143
                $expected,
144
                sprintf('%s %s should have been %s, %s actually', $expected, $entity, $state, $real)
145
            )
146
        ;
147
    }
148
149
    /**
150
     * @Then /^should be (\d+) (.*) like:?$/
151
     */
152
    public function existLikeFollowing($nbr, $name, TableNode $table)
153
    {
154
        $entityName = $this->resolveEntity($name)->getName();
155
156
        $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...
157
        $headers = array_shift($rows);
158
159
        $accessor = PropertyAccess::createPropertyAccessor();
160
161
        for ($i = 0; $i < $nbr; $i++) {
162
            $row = $rows[$i % count($rows)];
163
164
            $values = array_combine($headers, $row);
165
            $object = $this->getManager()
166
                ->getRepository($entityName)
167
                ->findOneBy(
168
                    $this->getEntityIdentifiers($entityName, $headers, $row)
169
                );
170
171
            if (is_null($object)) {
172
                throw new \Exception(sprintf("There is not any object for the following identifiers: %s", json_encode($this->getEntityIdentifiers($entityName, $headers, $row))));
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal There is not any object ...llowing identifiers: %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...
173
            }
174
            $this->getManager()->refresh($object);
175
176
            foreach ($values as $key => $value) {
177
                if ($value != $accessor->getValue($object, $key) ) {
178
                    throw new \Exception("The expected object does not have property $key with value $value");
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $key instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $value instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
179
                }
180
            }
181
        }
182
    }
183
184
    /**
185
     * @BeforeScenario
186
     */
187
    public function beforeScenario($event)
188
    {
189
        $this->storeTags($event);
190
191
        if ($this->hasTags([ 'reset-schema', '~not-reset-schema' ])) {
192
            foreach ($this->getManagers() as $entityManager) {
193
                $metadata = $this->getMetadata($entityManager);
194
195
                if (!empty($metadata)) {
196
                    $tool = new SchemaTool($entityManager);
197
                    $tool->dropSchema($metadata);
198
                    $tool->createSchema($metadata);
199
                }
200
            }
201
        }
202
203
    }
204
205
    /**
206
     * @AfterScenario
207
     */
208
    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...
209
    {
210
        $this->getRecordBag()->clear();
211
        $this->getUniqueCache()->clear();
212
        $this->getManager()->clear();
213
    }
214
215
    protected function compareArray(array $a1, array $a2)
216
    {
217
        $diff = [];
218
        foreach ($a1 as $e) {
219
            if (!in_array($e, $a2)) {
220
                $diff[] = $e;
221
            }
222
        }
223
224
        return $diff;
225
    }
226
227
    protected function getMetadata(EntityManager $entityManager)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
228
    {
229
        return $entityManager->getMetadataFactory()->getAllMetadata();
230
    }
231
232
    protected function getManagers()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
233
    {
234
        return $this->get('doctrine')->getManagers();
235
    }
236
237
    protected function getConnections()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
238
    {
239
        return $this->get('doctrine')->getConnections();
240
    }
241
242
    protected function getDefaultOptions()
243
    {
244
        return [
245
            'Entities' => [''],
246
        ];
247
    }
248
249
    /**
250
     * @param string $entityName
251
     * @param array $headers Headers of the Behat TableNode
252
     * @param array $row current row if tge Behat TableNode
253
     * @return array ['id_column_A' => 'value', 'id_column_B' => 'value']
254
     * @throws \Exception
255
     */
256
    protected function getEntityIdentifiers($entityName, $headers, $row)
257
    {
258
        $metadata = $this->getManager()->getClassMetadata($entityName);
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...
259
        $identifiers = $metadata->getIdentifierFieldNames();
260
261
        $identifiersWithValues = [];
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $identifiersWithValues 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...
262
263
        foreach ($identifiers as $identifier) {
264
            $headersPosition = array_search($identifier, $headers);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 20 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...
265
            $identifiersWithValues[$identifier] = $row[$headersPosition];
266
        }
267
268
        return $identifiersWithValues;
269
    }
270
}
271