Completed
Pull Request — master (#186)
by Vincent
03:26
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\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->getEntityManager(), $entity, $values)
39
                ->completeRequired($this->getEntityManager(), $entity)
40
            ;
41
42
            $this->getEntityManager()->persist($entity);
43
        }
44
45
        $this->getEntityManager()->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->getEntityManager(), $entity)
65
            ;
66
67
            $this->getEntityManager()->persist($entity);
68
        }
69
70
        $this->getEntityManager()->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->getEntityManager(), $entity, $values)
95
                ->completeRequired($this->getEntityManager(), $entity)
96
            ;
97
98
            $this->getEntityManager()->persist($entity);
99
        }
100
101
        $this->getEntityManager()->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
            ->getEntityManager()
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->getEntityManager()
166
                ->getRepository($entityName)
167
                ->findOneBy($values);
168
169
            if (is_null($object)) {
170
                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...
171
            }
172
            $this->getEntityManager()->refresh($object);
173
174
            foreach ($values as $key => $value) {
175
                if ($value != $accessor->getValue($object, $key) ) {
176
                    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...
177
                }
178
            }
179
        }
180
    }
181
182
    /**
183
     * @BeforeScenario
184
     */
185
    public function beforeScenario($event)
186
    {
187
        $this->storeTags($event);
188
189
        if ($this->hasTags([ 'reset-schema', '~not-reset-schema' ])) {
190
            foreach ($this->getEntityManagers() as $entityManager) {
191
                $metadata = $this->getMetadata($entityManager);
192
193
                if (!empty($metadata)) {
194
                    $tool = new SchemaTool($entityManager);
195
                    $tool->dropSchema($metadata);
196
                    $tool->createSchema($metadata);
197
                }
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
    protected function compareArray(array $a1, array $a2)
214
    {
215
        $diff = [];
216
        foreach ($a1 as $e) {
217
            if (!in_array($e, $a2)) {
218
                $diff[] = $e;
219
            }
220
        }
221
222
        return $diff;
223
    }
224
225
    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...
226
    {
227
        return $entityManager->getMetadataFactory()->getAllMetadata();
228
    }
229
230
    protected function getEntityManagers()
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...
231
    {
232
        return $this->get('doctrine')->getManagers();
233
    }
234
235
    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...
236
    {
237
        return $this->get('doctrine')->getConnections();
238
    }
239
240
    protected function getDefaultOptions()
241
    {
242
        return [
243
            'Entities' => [''],
244
        ];
245
    }
246
}
247