Completed
Pull Request — master (#1327)
by
unknown
07:46 queued 57s
created

testIdentifierIsCastedToString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 8
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the FOSElasticaBundle package.
5
 *
6
 * (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace FOS\ElasticaBundle\Tests\Transformer\ModelToElasticaAutoTransformer;
13
14
use Elastica\Document;
15
use FOS\ElasticaBundle\Event\TransformEvent;
16
use FOS\ElasticaBundle\Transformer\ModelToElasticaAutoTransformer;
17
use PHPUnit\Framework\TestCase;
18
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
19
use Symfony\Component\PropertyAccess\PropertyAccess;
20
21
class POPO
22
{
23
    public $id = 123;
24
    public $name = 'someName';
25
    public $float = 7.2;
26
    public $bool = true;
27
    public $falseBool = false;
28
    public $date;
29
    public $nullValue;
30
    public $file;
31
    public $fileContents;
32
    private $desc = 'desc';
33
34
    public function __construct()
35
    {
36
        $this->date = new \DateTime('1979-05-05');
37
        $this->file = new \SplFileInfo(__DIR__.'/../fixtures/attachment.odt');
38
        $this->fileContents = file_get_contents(__DIR__.'/../fixtures/attachment.odt');
39
    }
40
41
    public function getId()
42
    {
43
        return $this->id;
44
    }
45
46
    public function getName()
47
    {
48
        return $this->name;
49
    }
50
51
    public function getIterator()
52
    {
53
        $iterator = new \ArrayIterator();
54
        $iterator->append('value1');
55
56
        return $iterator;
57
    }
58
59
    public function getArray()
60
    {
61
        return [
62
            'key1' => 'value1',
63
            'key2' => 'value2',
64
        ];
65
    }
66
67
    public function getMultiArray()
68
    {
69
        return [
70
            'key1' => 'value1',
71
            'key2' => ['value2', false, 123, 8.9, new \DateTime('1978-09-07')],
72
        ];
73
    }
74
75
    public function getBool()
76
    {
77
        return $this->bool;
78
    }
79
80
    public function getFalseBool()
81
    {
82
        return $this->falseBool;
83
    }
84
85
    public function getFloat()
86
    {
87
        return $this->float;
88
    }
89
90
    public function getDate()
91
    {
92
        return $this->date;
93
    }
94
95
    public function getNullValue()
96
    {
97
        return $this->nullValue;
98
    }
99
100
    public function getFile()
101
    {
102
        return $this->file;
103
    }
104
105
    public function getFileContents()
106
    {
107
        return $this->fileContents;
108
    }
109
110
    public function getSub()
111
    {
112
        return [
113
            (object) ['foo' => 'foo', 'bar' => 'foo', 'id' => 1],
114
            (object) ['foo' => 'bar', 'bar' => 'bar', 'id' => 2],
115
        ];
116
    }
117
118
    public function getObj()
119
    {
120
        return ['foo' => 'foo', 'bar' => 'foo', 'id' => 1];
121
    }
122
123
    public function getNestedObject()
124
    {
125
        return ['key1' => (object) ['id' => 1, 'key1sub1' => 'value1sub1', 'key1sub2' => 'value1sub2']];
126
    }
127
128
    public function getUpper()
129
    {
130
        return (object) ['id' => 'parent', 'name' => 'a random name'];
131
    }
132
133
    public function getUpperAlias()
134
    {
135
        return $this->getUpper();
136
    }
137
138
    public function getObjWithoutIdentifier()
139
    {
140
        return (object) ['foo' => 'foo', 'bar' => 'foo'];
141
    }
142
143
    public function getSubWithoutIdentifier()
144
    {
145
        return [
146
            (object) ['foo' => 'foo', 'bar' => 'foo'],
147
            (object) ['foo' => 'bar', 'bar' => 'bar'],
148
        ];
149
    }
150
}
151
152
class CastableObject
153
{
154
    public $foo;
155
156
    public function __toString()
157
    {
158
        return $this->foo;
159
    }
160
}
161
162
class ModelToElasticaAutoTransformerTest extends TestCase
163
{
164
    public function testTransformerDispatches()
165
    {
166
        $dispatcher = $this->createMock(EventDispatcherInterface::class);
167
168
        $dispatcher->expects($this->exactly(2))
169
            ->method('dispatch')
170
            ->withConsecutive(
171
                [
172
                    TransformEvent::PRE_TRANSFORM,
173
                    $this->isInstanceOf(TransformEvent::class),
174
                ],
175
                [
176
                    TransformEvent::POST_TRANSFORM,
177
                    $this->isInstanceOf(TransformEvent::class),
178
                ]
179
            );
180
181
        $transformer = $this->getTransformer($dispatcher);
0 ignored issues
show
Documentation introduced by
$dispatcher is of type object<PHPUnit\Framework\MockObject\MockObject>, but the function expects a null|object<Symfony\Comp...entDispatcherInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
182
        $transformer->transform(new POPO(), []);
183
    }
184
185
    public function testPropertyPath()
186
    {
187
        $transformer = $this->getTransformer();
188
189
        $document = $transformer->transform(new POPO(), ['name' => ['property_path' => false]]);
190
        $this->assertInstanceOf(Document::class, $document);
191
        $this->assertFalse($document->has('name'));
192
193
        $document = $transformer->transform(new POPO(), ['realName' => ['property_path' => 'name']]);
194
        $this->assertInstanceOf(Document::class, $document);
195
        $this->assertTrue($document->has('realName'));
196
        $this->assertSame('someName', $document->get('realName'));
197
    }
198
199 View Code Duplication
    public function testThatCanTransformObject()
200
    {
201
        $transformer = $this->getTransformer();
202
        $document = $transformer->transform(new POPO(), ['name' => []]);
203
        $data = $document->getData();
204
205
        $this->assertInstanceOf(Document::class, $document);
206
        $this->assertSame(123, $document->getId());
207
        $this->assertSame('someName', $data['name']);
208
    }
209
210
    public function testThatCanTransformObjectWithCorrectTypes()
211
    {
212
        $transformer = $this->getTransformer();
213
        $document = $transformer->transform(
214
            new POPO(), [
215
                             'name' => [],
216
                             'float' => [],
217
                             'bool' => [],
218
                             'date' => [],
219
                             'falseBool' => [],
220
                        ]
221
        );
222
        $data = $document->getData();
223
224
        $this->assertInstanceOf(Document::class, $document);
225
        $this->assertSame(123, $document->getId());
226
        $this->assertSame('someName', $data['name']);
227
        $this->assertSame(7.2, $data['float']);
228
        $this->assertTrue($data['bool']);
229
        $this->assertFalse($data['falseBool']);
230
        $expectedDate = new \DateTime('1979-05-05');
231
        $this->assertSame($expectedDate->format('c'), $data['date']);
232
    }
233
234 View Code Duplication
    public function testThatCanTransformObjectWithIteratorValue()
235
    {
236
        $transformer = $this->getTransformer();
237
        $document = $transformer->transform(new POPO(), ['iterator' => []]);
238
        $data = $document->getData();
239
240
        $this->assertSame(['value1'], $data['iterator']);
241
    }
242
243 View Code Duplication
    public function testThatCanTransformObjectWithArrayValue()
244
    {
245
        $transformer = $this->getTransformer();
246
        $document = $transformer->transform(new POPO(), ['array' => []]);
247
        $data = $document->getData();
248
249
        $this->assertSame(
250
            [
251
                 'key1' => 'value1',
252
                 'key2' => 'value2',
253
            ], $data['array']
254
        );
255
    }
256
257
    public function testThatCanTransformObjectWithMultiDimensionalArrayValue()
258
    {
259
        $transformer = $this->getTransformer();
260
        $document = $transformer->transform(new POPO(), ['multiArray' => []]);
261
        $data = $document->getData();
262
263
        $expectedDate = new \DateTime('1978-09-07');
264
265
        $this->assertSame(
266
            [
267
                 'key1' => 'value1',
268
                 'key2' => ['value2', false, 123, 8.9, $expectedDate->format('c')],
269
            ], $data['multiArray']
270
        );
271
    }
272
273 View Code Duplication
    public function testThatNullValuesAreNotFilteredOut()
274
    {
275
        $transformer = $this->getTransformer();
276
        $document = $transformer->transform(new POPO(), ['nullValue' => []]);
277
        $data = $document->getData();
278
279
        $this->assertTrue(array_key_exists('nullValue', $data));
280
    }
281
282
    /**
283
     * @expectedException \Symfony\Component\PropertyAccess\Exception\RuntimeException
284
     */
285
    public function testThatCannotTransformObjectWhenGetterDoesNotExistForPrivateMethod()
286
    {
287
        $transformer = $this->getTransformer();
288
        $transformer->transform(new POPO(), ['desc' => []]);
289
    }
290
291 View Code Duplication
    public function testFileAddedForAttachmentMapping()
292
    {
293
        $transformer = $this->getTransformer();
294
        $document = $transformer->transform(new POPO(), ['file' => ['type' => 'attachment']]);
295
        $data = $document->getData();
296
297
        $this->assertSame(base64_encode(file_get_contents(__DIR__.'/../fixtures/attachment.odt')), $data['file']);
298
    }
299
300 View Code Duplication
    public function testFileContentsAddedForAttachmentMapping()
301
    {
302
        $transformer = $this->getTransformer();
303
        $document = $transformer->transform(new POPO(), ['fileContents' => ['type' => 'attachment']]);
304
        $data = $document->getData();
305
306
        $this->assertSame(
307
            base64_encode(file_get_contents(__DIR__.'/../fixtures/attachment.odt')), $data['fileContents']
308
        );
309
    }
310
311 View Code Duplication
    public function testNestedMapping()
312
    {
313
        $transformer = $this->getTransformer();
314
        $document = $transformer->transform(new POPO(), [
315
            'sub' => [
316
                'type' => 'nested',
317
                'properties' => ['foo' => []],
318
            ],
319
        ]);
320
        $data = $document->getData();
321
322
        $this->assertTrue(array_key_exists('sub', $data));
323
        $this->assertInternalType('array', $data['sub']);
324
        $this->assertSame([
325
             ['foo' => 'foo'],
326
             ['foo' => 'bar'],
327
           ], $data['sub']);
328
    }
329
330 View Code Duplication
    public function tesObjectMapping()
331
    {
332
        $transformer = $this->getTransformer();
333
        $document = $transformer->transform(new POPO(), [
334
                'sub' => [
335
                    'type' => 'object',
336
                    'properties' => ['bar'],
337
                    ],
338
                ]);
339
        $data = $document->getData();
340
341
        $this->assertTrue(array_key_exists('sub', $data));
342
        $this->assertInternalType('array', $data['sub']);
343
        $this->assertSame([
344
             ['bar' => 'foo'],
345
             ['bar' => 'bar'],
346
           ], $data['sub']);
347
    }
348
349
    public function testObjectDoesNotRequireProperties()
350
    {
351
        $transformer = $this->getTransformer();
352
        $document = $transformer->transform(new POPO(), [
353
                'obj' => [
354
                    'type' => 'object',
355
                    ],
356
                ]);
357
        $data = $document->getData();
358
359
        $this->assertTrue(array_key_exists('obj', $data));
360
        $this->assertInternalType('array', $data['obj']);
361
        $this->assertSame([
362
             'foo' => 'foo',
363
             'bar' => 'foo',
364
             'id' => 1,
365
       ], $data['obj']);
366
    }
367
368
    public function testObjectsMappingOfAtLeastOneAutoMappedObjectAndAtLeastOneManuallyMappedObject()
369
    {
370
        $transformer = $this->getTransformer();
371
        $document = $transformer->transform(
372
            new POPO(),
373
            [
374
                'obj' => ['type' => 'object', 'properties' => []],
375
                'nestedObject' => [
376
                    'type' => 'object',
377
                    'properties' => [
378
                        'key1sub1' => [
379
                            'type' => 'text',
380
                            'properties' => [],
381
                        ],
382
                        'key1sub2' => [
383
                            'type' => 'text',
384
                            'properties' => [],
385
                        ],
386
                    ],
387
                ],
388
            ]
389
        );
390
        $data = $document->getData();
391
392
        $this->assertTrue(array_key_exists('obj', $data));
393
        $this->assertTrue(array_key_exists('nestedObject', $data));
394
        $this->assertInternalType('array', $data['obj']);
395
        $this->assertInternalType('array', $data['nestedObject']);
396
        $this->assertSame(
397
            [
398
                'foo' => 'foo',
399
                'bar' => 'foo',
400
                'id' => 1,
401
            ],
402
            $data['obj']
403
        );
404
        $this->assertSame(
405
            [
406
                'key1sub1' => 'value1sub1',
407
                'key1sub2' => 'value1sub2',
408
            ],
409
            $data['nestedObject'][0]
410
        );
411
    }
412
413 View Code Duplication
    public function testParentMapping()
414
    {
415
        $transformer = $this->getTransformer();
416
        $document = $transformer->transform(new POPO(), [
417
            '_parent' => ['type' => 'upper', 'property' => 'upper', 'identifier' => 'id'],
418
        ]);
419
420
        $this->assertSame('parent', $document->getParent());
421
    }
422
423 View Code Duplication
    public function testParentMappingWithCustomIdentifier()
424
    {
425
        $transformer = $this->getTransformer();
426
        $document = $transformer->transform(new POPO(), [
427
            '_parent' => ['type' => 'upper', 'property' => 'upper', 'identifier' => 'name'],
428
        ]);
429
430
        $this->assertSame('a random name', $document->getParent());
431
    }
432
433 View Code Duplication
    public function testParentMappingWithNullProperty()
434
    {
435
        $transformer = $this->getTransformer();
436
        $document = $transformer->transform(new POPO(), [
437
            '_parent' => ['type' => 'upper', 'property' => null, 'identifier' => 'id'],
438
        ]);
439
440
        $this->assertSame('parent', $document->getParent());
441
    }
442
443 View Code Duplication
    public function testParentMappingWithCustomProperty()
444
    {
445
        $transformer = $this->getTransformer();
446
        $document = $transformer->transform(new POPO(), [
447
            '_parent' => ['type' => 'upper', 'property' => 'upperAlias', 'identifier' => 'id'],
448
        ]);
449
450
        $this->assertSame('parent', $document->getParent());
451
    }
452
453 View Code Duplication
    public function testThatMappedObjectsDontNeedAnIdentifierField()
454
    {
455
        $transformer = $this->getTransformer();
456
        $document = $transformer->transform(new POPO(), [
457
            'objWithoutIdentifier' => [
458
                'type' => 'object',
459
                'properties' => [
460
                    'foo' => [],
461
                    'bar' => [],
462
                ],
463
            ],
464
        ]);
465
        $data = $document->getData();
466
467
        $this->assertTrue(array_key_exists('objWithoutIdentifier', $data));
468
        $this->assertInternalType('array', $data['objWithoutIdentifier']);
469
        $this->assertSame([
470
            'foo' => 'foo',
471
            'bar' => 'foo',
472
        ], $data['objWithoutIdentifier']);
473
    }
474
475
    public function testThatNestedObjectsDontNeedAnIdentifierField()
476
    {
477
        $transformer = $this->getTransformer();
478
        $document = $transformer->transform(new POPO(), [
479
            'subWithoutIdentifier' => [
480
                'type' => 'nested',
481
                'properties' => [
482
                    'foo' => [],
483
                    'bar' => [],
484
                ],
485
            ],
486
        ]);
487
        $data = $document->getData();
488
489
        $this->assertTrue(array_key_exists('subWithoutIdentifier', $data));
490
        $this->assertInternalType('array', $data['subWithoutIdentifier']);
491
        $this->assertSame([
492
            ['foo' => 'foo', 'bar' => 'foo'],
493
            ['foo' => 'bar', 'bar' => 'bar'],
494
        ], $data['subWithoutIdentifier']);
495
    }
496
497 View Code Duplication
    public function testNestedTransformHandlesSingleObjects()
498
    {
499
        $transformer = $this->getTransformer();
500
        $document = $transformer->transform(new POPO(), [
501
            'upper' => [
502
                'type' => 'nested',
503
                'properties' => ['name' => null],
504
            ],
505
        ]);
506
507
        $data = $document->getData();
508
        $this->assertSame('a random name', $data['upper']['name']);
509
    }
510
511
    public function testNestedTransformReturnsAnEmptyArrayForNullValues()
512
    {
513
        $transformer = $this->getTransformer();
514
        $document = $transformer->transform(new POPO(), [
515
            'nullValue' => [
516
                'type' => 'nested',
517
                'properties' => [
518
                    'foo' => [],
519
                    'bar' => [],
520
                ],
521
            ],
522
        ]);
523
524
        $data = $document->getData();
525
        $this->assertInternalType('array', $data['nullValue']);
526
        $this->assertEmpty($data['nullValue']);
527
    }
528
529
    public function testUnmappedFieldValuesAreNormalisedToStrings()
530
    {
531
        $object = new \stdClass();
532
        $value = new CastableObject();
533
        $value->foo = 'bar';
534
535
        $object->id = 123;
536
        $object->unmappedValue = $value;
537
538
        $transformer = $this->getTransformer();
539
        $document = $transformer->transform($object, ['unmappedValue' => ['property' => 'unmappedValue']]);
540
541
        $data = $document->getData();
542
        $this->assertSame('bar', $data['unmappedValue']);
543
    }
544
545
    public function testIdentifierIsCastedToString()
546
    {
547
        $idObject = new CastableObject();;
548
        $idObject->foo = '00000000-0000-0000-0000-000000000000';
549
550
        $object = new \stdClass();
551
        $object->id = $idObject;
552
553
        $transformer = $this->getTransformer();
554
        $document = $transformer->transform($object, []);
555
556
        $this->assertSame('string', gettype($document->getId()));
557
    }
558
559
    /**
560
     * @param null|\Symfony\Component\EventDispatcher\EventDispatcherInterface $dispatcher
561
     *
562
     * @return ModelToElasticaAutoTransformer
563
     */
564
    private function getTransformer($dispatcher = null)
565
    {
566
        $transformer = new ModelToElasticaAutoTransformer([], $dispatcher);
567
        $transformer->setPropertyAccessor(PropertyAccess::createPropertyAccessor());
568
569
        return $transformer;
570
    }
571
}
572