Completed
Push — master ( 48cda2...12f48c )
by Gaetano
07:13
created

FeatureContext::createObject()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 28
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 14
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 28
rs 8.8571
1
<?php
2
3
namespace Kaliop\eZMigrationBundle\Tests\behat;
4
5
use eZ\Publish\Core\Repository\Values\ContentType\ContentType;
6
use eZ\Publish\Core\Repository\Values\ContentType\ContentTypeGroup;
7
use eZ\Publish\Core\Repository\Values\ContentType\FieldDefinition;
8
use eZ\Publish\SPI\Persistence\Content\Location;
9
use Symfony\Component\HttpKernel\KernelInterface;
10
use Behat\Symfony2Extension\Context\KernelAwareContext;
11
use Behat\Behat\Exception\PendingException;
12
use Behat\Gherkin\Node\TableNode;
13
use Behat\Behat\Exception\UndefinedException;
14
15
use PHPUnit_Framework_Assert as Assertion;
16
use DateTime;
17
18
/**
19
 * Feature context.
20
 */
21
class FeatureContext /*extends BehatContext*/ implements KernelAwareContext
22
{
23
    private $kernel;
24
25
    const DEFAULT_LANGUAGE_CODE = 'eng-GB';
26
27
    /**
28
     * The parsed DSL instructions
29
     *
30
     * @var array
31
     */
32
    private $dsl = array();
33
34
    /**
35
     * Variable to store the step results in if needed.
36
     *
37
     * @var mixed
38
     */
39
    private $stepResults;
40
41
    /**
42
     * Sets HttpKernel instance.
43
     * This method will be automatically called by Symfony2Extension ContextInitializer.
44
     *
45
     * @param KernelInterface $kernel
46
     */
47
    public function setKernel(KernelInterface $kernel)
48
    {
49
        $this->kernel = $kernel;
50
    }
51
52
    /**
53
     * @Given /^I have the parsed DSL:$/
54
     */
55
    public function iHaveTheParsedDsl( TableNode $table )
56
    {
57
        $hash = $table->getHash();
58
        $this->dsl = $hash[0];
59
    }
60
61
    /**
62
     * @Given /^the attributes:$/
63
     */
64
    public function theAttributes( TableNode $table )
65
    {
66
        $this->dsl['attributes'] = $table->getHash();
67
    }
68
69
    /**
70
     * @When /^I create a "([^"]*)"$/
71
     */
72
    public function iCreateA( $className )
73
    {
74
        $this->stepResults = $this->createObject( $className );
75
76
    }
77
78
    /**
79
     * @Then /^I should get an object of "([^"]*)"$/
80
     */
81
    public function iShouldGetAnObjectOf( $className )
82
    {
83
        switch( $className ) {
84
            case 'ContentCreateStruct':
85
                Assertion::assertInstanceOf( 'eZ\Publish\Core\Repository\Values\Content\ContentCreateStruct', $this->stepResults );
86
                break;
87
            default:
88
                throw new PendingException( 'Handling for class name: ' . $className . ' not implemented.' );
89
        }
90
91
    }
92
93
    /**
94
     * @Given /^it should have (\d+) fields of type "([^"]*)"$/
95
     */
96
    public function itShouldHaveFieldsOfType( $numberOfFields, $className )
97
    {
98
        switch( $className )
99
        {
100
            case 'Field':
101
                $fieldType = 'eZ\Publish\API\Repository\Values\Content\Field';
102
                break;
103
            default:
104
                throw new PendingException( 'Handling for class ' . $className . ' not implemented' );
105
        }
106
107
        $fieldCount = count( $this->stepResults->fields );
108
109
        Assertion::assertEquals( $numberOfFields, $fieldCount );
110
        foreach( $this->stepResults->fields as $field )
111
        {
112
            Assertion::assertInstanceOf( $fieldType, $field );
113
        }
114
    }
115
116
    /**
117
     * @Given /^the fields should have the values:$/
118
     */
119
    public function theFieldsShouldHaveTheValues(TableNode $table )
0 ignored issues
show
Unused Code introduced by
The parameter $table 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...
120
    {
121
        throw new PendingException();
122
    }
123
124
    private function createObject( $className )
125
    {
126
        $object = null;
0 ignored issues
show
Unused Code introduced by
$object is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
127
128
        switch( $className )
129
        {
130
            case 'ContentCreateStruct':
131
                /** @var $repository \eZ\Publish\API\Repository\Repository */
132
                $repository = $this->kernel->getContainer()->get( 'ezpublish.api.repository' );
133
134
                $contentService = $repository->getContentService();
135
136
                $contentType = $this->createArticleContentType();
137
138
                $object = $contentService->newContentCreateStruct( $contentType, self::DEFAULT_LANGUAGE_CODE );
139
140
                foreach( $this->dsl['attributes'][0] as $field => $value )
141
                {
142
                    $object->setField( $field, $value );
143
                }
144
145
                break;
146
            default:
147
                throw new UndefinedException( $className );
148
        }
149
150
        return $object;
151
    }
152
153
154
    /* HELPER FUNCTIONS */
155
156
    private function createArticleContentType()
157
    {
158
        $contentTypeGroups[] = $this->createContentTypeGroup();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$contentTypeGroups was never initialized. Although not strictly required by PHP, it is generally a good practice to add $contentTypeGroups = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
159
        $fieldDefinitions = $this->createArticleFieldDefinitions();
160
161
        $dateTime = new DateTime();
162
        $dateTime->setTimestamp( time() );
163
164
        return new ContentType(
165
            array(
166
                "names" => 'Article',
167
                "descriptions" => '',
168
                "contentTypeGroups" => $contentTypeGroups,
169
                "fieldDefinitions" => $fieldDefinitions,
170
                "id" => 1,
171
                "status" => 0,
172
                "identifier" => 'article',
173
                "creationDate" => $dateTime,
174
                "modificationDate" => $dateTime,
175
                "creatorId" => 14,
176
                "modifierId" => 14,
177
                "remoteId" => 'remoteid',
178
                "urlAliasSchema" => '<title>',
179
                "nameSchema" => '<title>',
180
                "isContainer" => false,
181
                "mainLanguageCode" => self::DEFAULT_LANGUAGE_CODE,
182
                "defaultAlwaysAvailable" => true,
183
                "defaultSortField" => Location::SORT_FIELD_PUBLISHED,
184
                "defaultSortOrder" => Location::SORT_ORDER_DESC
185
            )
186
        );
187
    }
188
189
    /**
190
     * Helper function to create the needed field definitions for the article class.
191
     */
192
    private function createArticleFieldDefinitions()
193
    {
194
        /** @var $fieldType \eZ\Publish\SPI\FieldType\FieldType */
195
        $fieldDefinitions[] = new FieldDefinition(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$fieldDefinitions was never initialized. Although not strictly required by PHP, it is generally a good practice to add $fieldDefinitions = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
196
            array(
197
                "names" => 'Title',
198
                "descriptions" => '',
199
                "id" => 1,
200
                "identifier" => 'title',
201
                "fieldGroup" => 'default',
202
                "position" => 10,
203
                "fieldTypeIdentifier" => 'ezstring',
204
                "isTranslatable" => false,
205
                "isRequired" => true,
206
                "isInfoCollector" => false,
207
                "defaultValue" => '',
208
                "isSearchable" => true,
209
                "fieldSettings" => array(),
210
                "validatorConfiguration" => array(),
211
            )
212
        );
213
214
        /** @var $fieldType \eZ\Publish\SPI\FieldType\FieldType */
215
        $fieldDefinitions[] = new FieldDefinition(
216
            array(
217
                "names" => 'Author',
218
                "descriptions" => '',
219
                "id" => 2,
220
                "identifier" => 'author',
221
                "fieldGroup" => 'default',
222
                "position" => 20,
223
                "fieldTypeIdentifier" => 'ezstring',
224
                "isTranslatable" => false,
225
                "isRequired" => true,
226
                "isInfoCollector" => false,
227
                "defaultValue" => '',
228
                "isSearchable" => true,
229
                "fieldSettings" => array(),
230
                "validatorConfiguration" => array(),
231
            )
232
        );
233
234
        /** @var $fieldType \eZ\Publish\SPI\FieldType\FieldType */
235
        $fieldDefinitions[] = new FieldDefinition(
236
            array(
237
                "names" => 'Teaser',
238
                "descriptions" => '',
239
                "id" => 3,
240
                "identifier" => 'intro',
241
                "fieldGroup" => 'default',
242
                "position" => 30,
243
                "fieldTypeIdentifier" => 'ezxmltext',
244
                "isTranslatable" => false,
245
                "isRequired" => true,
246
                "isInfoCollector" => false,
247
                "defaultValue" => '',
248
                "isSearchable" => true,
249
                "fieldSettings" => array(),
250
                "validatorConfiguration" => array(),
251
            )
252
        );
253
254
        /** @var $fieldType \eZ\Publish\SPI\FieldType\FieldType */
255
        $fieldDefinitions[] = new FieldDefinition(
256
            array(
257
                "names" => 'Body',
258
                "descriptions" => '',
259
                "id" => 4,
260
                "identifier" => 'body',
261
                "fieldGroup" => 'default',
262
                "position" => 40,
263
                "fieldTypeIdentifier" => 'ezxmltext',
264
                "isTranslatable" => false,
265
                "isRequired" => true,
266
                "isInfoCollector" => false,
267
                "defaultValue" => '',
268
                "isSearchable" => true,
269
                "fieldSettings" => array(),
270
                "validatorConfiguration" => array(),
271
            )
272
        );
273
274
        return $fieldDefinitions;
275
    }
276
277
    /**
278
     * Helper function to create a dummy content type group object.
279
     *
280
     * return
281
     */
282
    private function createContentTypeGroup()
283
    {
284
        $dateTime = new DateTime();
285
        $dateTime->setTimestamp( time() );
286
287
        return new ContentTypeGroup(
288
            array(
289
                "id" => 1,
290
                "identifier" => 'content',
291
                "creationDate" => $dateTime,
292
                "modificationDate" => $dateTime,
293
                "creatorId" => 14,
294
                "modifierId" => 14,
295
                "names" => "Content",
296
                "descriptions" => ""
297
            )
298
        );
299
    }
300
}
301