Failed Conditions
Pull Request — develop (#1577)
by Marco
66:01
created

User::loadMetadata()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 155
Code Lines 97

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 155
rs 8.2857
c 0
b 0
f 0
cc 1
eloc 97
nc 1
nop 1

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Doctrine\Tests\ORM\Mapping;
6
7
use Doctrine\DBAL\Types\Type;
8
use Doctrine\ORM\Annotation as ORM;
9
use Doctrine\ORM\EntityManagerInterface;
10
use Doctrine\ORM\Events;
11
use Doctrine\ORM\Mapping;
12
use Doctrine\ORM\Mapping\ClassMetadata;
13
use Doctrine\ORM\Mapping\ClassMetadataFactory;
14
use Doctrine\ORM\Mapping\Factory\DefaultNamingStrategy;
15
use Doctrine\ORM\Mapping\Factory\UnderscoreNamingStrategy;
16
use Doctrine\ORM\Mapping\MappingException;
17
use Doctrine\ORM\Reflection\RuntimeReflectionService;
18
use Doctrine\Tests\Models\Cache\City;
19
use Doctrine\Tests\Models\CMS\CmsAddress;
20
use Doctrine\Tests\Models\CMS\CmsAddressListener;
21
use Doctrine\Tests\Models\CMS\CmsUser;
22
use Doctrine\Tests\Models\Company\CompanyContract;
23
use Doctrine\Tests\Models\Company\CompanyContractListener;
24
use Doctrine\Tests\Models\Company\CompanyFixContract;
25
use Doctrine\Tests\Models\Company\CompanyFlexContract;
26
use Doctrine\Tests\Models\Company\CompanyFlexUltraContract;
27
use Doctrine\Tests\Models\Company\CompanyFlexUltraContractListener;
28
use Doctrine\Tests\Models\Company\CompanyPerson;
29
use Doctrine\Tests\Models\DDC1476\DDC1476EntityWithDefaultFieldType;
30
use Doctrine\Tests\Models\DDC2825\ExplicitSchemaAndTable;
31
use Doctrine\Tests\Models\DDC2825\SchemaAndTableInTableName;
32
use Doctrine\Tests\Models\DDC3579\DDC3579Admin;
33
use Doctrine\Tests\Models\DDC5934\DDC5934Contract;
34
use Doctrine\Tests\Models\DDC869\DDC869ChequePayment;
35
use Doctrine\Tests\Models\DDC869\DDC869CreditCardPayment;
36
use Doctrine\Tests\Models\DDC869\DDC869PaymentRepository;
37
use Doctrine\Tests\Models\DDC889\DDC889Class;
38
use Doctrine\Tests\Models\DDC889\DDC889Entity;
39
use Doctrine\Tests\Models\DDC964\DDC964Admin;
40
use Doctrine\Tests\Models\DDC964\DDC964Guest;
41
use Doctrine\Tests\OrmTestCase;
42
43
abstract class AbstractMappingDriverTest extends OrmTestCase
44
{
45
    /**
46
     * @var Mapping\ClassMetadataBuildingContext
47
     */
48
    protected $metadataBuildingContext;
49
50
    public function setUp()
51
    {
52
        parent::setUp();
53
54
        $this->metadataBuildingContext = new Mapping\ClassMetadataBuildingContext(
55
            $this->createMock(ClassMetadataFactory::class),
56
            new RuntimeReflectionService()
57
        );
58
    }
59
60
    abstract protected function loadDriver();
61
62
    public function createClassMetadata($entityClassName)
63
    {
64
        $mappingDriver = $this->loadDriver();
65
66
        $class = new ClassMetadata($entityClassName, $this->metadataBuildingContext);
67
68
        $mappingDriver->loadMetadataForClass($entityClassName, $class, $this->metadataBuildingContext);
69
70
        return $class;
71
    }
72
73
    protected function createClassMetadataFactory(EntityManagerInterface $em = null) : ClassMetadataFactory
74
    {
75
        $driver     = $this->loadDriver();
76
        $em         = $em ?: $this->getTestEntityManager();
77
        $factory    = new ClassMetadataFactory();
78
79
        $em->getConfiguration()->setMetadataDriverImpl($driver);
80
        $factory->setEntityManager($em);
81
82
        return $factory;
83
    }
84
85
    /**
86
     * @param ClassMetadata $class
0 ignored issues
show
Bug introduced by
There is no parameter named $class. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
87
     */
88
    public function testEntityTableNameAndInheritance()
89
    {
90
        $class = $this->createClassMetadata(User::class);
91
92
        self::assertEquals('cms_users', $class->getTableName());
93
        self::assertEquals(Mapping\InheritanceType::NONE, $class->inheritanceType);
94
95
        return $class;
96
    }
97
98
    /**
99
     *
100
     * @param ClassMetadata $class
0 ignored issues
show
Bug introduced by
There is no parameter named $class. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
101
     */
102
    public function testEntityIndexes()
103
    {
104
        $class = $this->createClassMetadata('Doctrine\Tests\ORM\Mapping\User');
105
106
        self::assertCount(2, $class->table->getIndexes());
107
        self::assertEquals(
108
            [
109
                'name_idx' => [
110
                    'name'    => 'name_idx',
111
                    'columns' => ['name'],
112
                    'unique'  => false,
113
                    'options' => [],
114
                    'flags'   => [],
115
                ],
116
                0 => [
117
                    'name'    => null,
118
                    'columns' => ['user_email'],
119
                    'unique'  => false,
120
                    'options' => [],
121
                    'flags'   => [],
122
                ]
123
            ],
124
            $class->table->getIndexes()
125
        );
126
127
        return $class;
128
    }
129
130
    public function testEntityIndexFlagsAndPartialIndexes()
131
    {
132
        $class = $this->createClassMetadata(Comment::class);
133
134
        self::assertEquals(
135
            [
136
                0 => [
137
                    'name'    => null,
138
                    'columns' => ['content'],
139
                    'unique'  => false,
140
                    'flags'   => ['fulltext'],
141
                    'options' => ['where' => 'content IS NOT NULL'],
142
                ]
143
            ],
144
            $class->table->getIndexes()
145
        );
146
    }
147
148
    /**
149
     * @depends testEntityTableNameAndInheritance
150
     * @param ClassMetadata $class
151
     */
152
    public function testEntityUniqueConstraints($class)
153
    {
154
        self::assertCount(1, $class->table->getUniqueConstraints());
155
        self::assertEquals(
156
            [
157
                'search_idx' => [
158
                    'name'    => 'search_idx',
159
                    'columns' => ['name', 'user_email'],
160
                    'options' => [],
161
                    'flags'   => [],
162
                ]
163
            ],
164
            $class->table->getUniqueConstraints()
165
        );
166
167
        return $class;
168
    }
169
170
    /**
171
     * @depends testEntityTableNameAndInheritance
172
     * @param ClassMetadata $class
173
     */
174
    public function testEntityOptions($class)
175
    {
176
        self::assertCount(2, $class->table->getOptions());
177
        self::assertEquals(
178
            [
179
                'foo' => 'bar',
180
                'baz' => ['key' => 'val']
181
            ],
182
            $class->table->getOptions()
183
        );
184
185
        return $class;
186
    }
187
188
    /**
189
     * @depends testEntityOptions
190
     * @param ClassMetadata $class
191
     */
192
    public function testEntitySequence($class)
193
    {
194
        self::assertInternalType(
195
            'array',
196
            $class->getProperty('id')->getValueGenerator()->getDefinition(),
0 ignored issues
show
Bug introduced by
The method getValueGenerator() does not exist on Doctrine\ORM\Mapping\Property. Did you maybe mean getValue()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
197
            'No Sequence Definition set on this driver.'
198
        );
199
        self::assertEquals(
200
            [
201
                'sequenceName'   => 'tablename_seq',
202
                'allocationSize' => 100,
203
            ],
204
            $class->getProperty('id')->getValueGenerator()->getDefinition()
0 ignored issues
show
Bug introduced by
The method getValueGenerator() does not exist on Doctrine\ORM\Mapping\Property. Did you maybe mean getValue()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
205
        );
206
    }
207
208 View Code Duplication
    public function testEntityCustomGenerator()
209
    {
210
        $class = $this->createClassMetadata(Animal::class);
211
212
        self::assertEquals(Mapping\GeneratorType::CUSTOM, $class->getProperty('id')->getValueGenerator()->getType(), "Generator Type");
0 ignored issues
show
Bug introduced by
The method getValueGenerator() does not exist on Doctrine\ORM\Mapping\Property. Did you maybe mean getValue()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
213
        self::assertEquals(
214
            [
215
                'class'     => 'stdClass',
216
                'arguments' => [],
217
            ],
218
            $class->getProperty('id')->getValueGenerator()->getDefinition(),
0 ignored issues
show
Bug introduced by
The method getValueGenerator() does not exist on Doctrine\ORM\Mapping\Property. Did you maybe mean getValue()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
219
            "Generator Definition"
220
        );
221
    }
222
223
224
    /**
225
     * @depends testEntityTableNameAndInheritance
226
     * @param ClassMetadata $class
227
     */
228
    public function testProperties($class)
229
    {
230
        self::assertCount(7, $class->getDeclaredPropertiesIterator());
231
232
        self::assertNotNull($class->getProperty('id'));
233
        self::assertNotNull($class->getProperty('name'));
234
        self::assertNotNull($class->getProperty('email'));
235
        self::assertNotNull($class->getProperty('version'));
236
        self::assertNotNull($class->getProperty('version'));
237
238
        return $class;
239
    }
240
241
    /**
242
     * @depends testProperties
243
     * @param ClassMetadata $class
244
     */
245
    public function testVersionProperty($class)
246
    {
247
        self::assertTrue($class->isVersioned());
248
        self::assertNotNull($class->versionProperty);
249
250
        $versionPropertyName = $class->versionProperty->getName();
251
252
        self::assertEquals("version", $versionPropertyName);
253
        self::assertNotNull($class->getProperty($versionPropertyName));
254
    }
255
256
    /**
257
     * @depends testEntityTableNameAndInheritance
258
     * @param ClassMetadata $class
259
     */
260
    public function testFieldMappingsColumnNames($class)
261
    {
262
        self::assertNotNull($class->getProperty('id'));
263
        self::assertNotNull($class->getProperty('name'));
264
        self::assertNotNull($class->getProperty('email'));
265
266
        self::assertEquals("id", $class->getProperty('id')->getColumnName());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\ORM\Mapping\Property as the method getColumnName() does only exist in the following implementations of said interface: Doctrine\ORM\Mapping\FieldMetadata, Doctrine\ORM\Mapping\VersionFieldMetadata.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
267
        self::assertEquals("name", $class->getProperty('name')->getColumnName());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\ORM\Mapping\Property as the method getColumnName() does only exist in the following implementations of said interface: Doctrine\ORM\Mapping\FieldMetadata, Doctrine\ORM\Mapping\VersionFieldMetadata.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
268
        self::assertEquals("user_email", $class->getProperty('email')->getColumnName());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\ORM\Mapping\Property as the method getColumnName() does only exist in the following implementations of said interface: Doctrine\ORM\Mapping\FieldMetadata, Doctrine\ORM\Mapping\VersionFieldMetadata.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
269
270
        return $class;
271
    }
272
273
    /**
274
     * @depends testEntityTableNameAndInheritance
275
     * @param ClassMetadata $class
276
     */
277
    public function testStringFieldMappings($class)
278
    {
279
        self::assertNotNull($class->getProperty('name'));
280
281
        $property = $class->getProperty('name');
282
283
        self::assertEquals('string', $property->getTypeName());
284
        self::assertEquals(50, $property->getLength());
285
        self::assertTrue($property->isNullable());
286
        self::assertTrue($property->isUnique());
287
288
        return $class;
289
    }
290
291
    /**
292
     * @depends testEntityTableNameAndInheritance
293
     *
294
     * @param ClassMetadata $class
295
     *
296
     * @return ClassMetadata
297
     */
298
    public function testFieldOptions(ClassMetadata $class)
299
    {
300
        self::assertNotNull($class->getProperty('name'));
301
302
        $property = $class->getProperty('name');
303
        $expected = ['foo' => 'bar', 'baz' => ['key' => 'val'], 'fixed' => false];
304
305
        self::assertEquals($expected, $property->getOptions());
306
307
        return $class;
308
    }
309
310
    /**
311
     * @depends testEntityTableNameAndInheritance
312
     * @param ClassMetadata $class
313
     */
314
    public function testIdFieldOptions($class)
315
    {
316
        self::assertNotNull($class->getProperty('id'));
317
318
        $property = $class->getProperty('id');
319
        $expected = ['foo' => 'bar', 'unsigned' => false];
320
321
        self::assertEquals($expected, $property->getOptions());
322
323
        return $class;
324
    }
325
326
    /**
327
     * @depends testProperties
328
     * @param ClassMetadata $class
329
     */
330 View Code Duplication
    public function testIdentifier($class)
331
    {
332
        self::assertNotNull($class->getProperty('id'));
333
334
        $property = $class->getProperty('id');
335
336
        self::assertEquals('integer', $property->getTypeName());
337
        self::assertEquals(['id'], $class->identifier);
338
        self::assertEquals(Mapping\GeneratorType::AUTO, $property->getValueGenerator()->getType(), "ID-Generator is not GeneratorType::AUTO");
0 ignored issues
show
Bug introduced by
The method getValueGenerator() does not exist on Doctrine\ORM\Mapping\Property. Did you maybe mean getValue()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
339
340
        return $class;
341
    }
342
343
    /**
344
     * @group #6129
345
     *
346
     * @return ClassMetadata
347
     */
348
    public function testBooleanValuesForOptionIsSetCorrectly()
349
    {
350
        $class = $this->createClassMetadata(User::class);
351
352
        $idOptions = $class->getProperty('id')->getOptions();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\ORM\Mapping\Property as the method getOptions() does only exist in the following implementations of said interface: Doctrine\ORM\Mapping\FieldMetadata, Doctrine\ORM\Mapping\VersionFieldMetadata.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
353
        $nameOptions = $class->getProperty('name')->getOptions();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\ORM\Mapping\Property as the method getOptions() does only exist in the following implementations of said interface: Doctrine\ORM\Mapping\FieldMetadata, Doctrine\ORM\Mapping\VersionFieldMetadata.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
354
355
        self::assertInternalType('bool', $idOptions['unsigned']);
356
        self::assertFalse($idOptions['unsigned']);
357
        self::assertInternalType('bool', $nameOptions['fixed']);
358
        self::assertFalse($nameOptions['fixed']);
359
360
        return $class;
361
    }
362
363
    /**
364
     * @depends testProperties
365
     * @param ClassMetadata $class
366
     */
367
    public function testOwningOneToOneAssociation($class)
368
    {
369
        self::assertArrayHasKey('address', $class->getDeclaredPropertiesIterator());
370
371
        $association = $class->getProperty('address');
372
373
        self::assertTrue($association->isOwningSide());
374
        self::assertEquals('user', $association->getInversedBy());
375
        // Check cascading
376
        self::assertEquals(['remove'], $association->getCascade());
377
378
        return $class;
379
    }
380
381
    /**
382
     * @depends testOwningOneToOneAssociation
383
     * @param ClassMetadata $class
384
     */
385 View Code Duplication
    public function testInverseOneToManyAssociation($class)
386
    {
387
        self::assertArrayHasKey('phonenumbers', $class->getDeclaredPropertiesIterator());
388
389
        $association = $class->getProperty('phonenumbers');
390
391
        self::assertFalse($association->isOwningSide());
392
        self::assertTrue($association->isOrphanRemoval());
393
394
        // Check cascading
395
        self::assertEquals(['persist', 'remove'], $association->getCascade());
396
397
        // Test Order By
398
        self::assertEquals(['number' => 'ASC'], $association->getOrderBy());
399
400
        return $class;
401
    }
402
403
    /**
404
     * @depends testInverseOneToManyAssociation
405
     * @param ClassMetadata $class
406
     */
407 View Code Duplication
    public function testManyToManyAssociationWithCascadeAll($class)
408
    {
409
        self::assertArrayHasKey('groups', $class->getDeclaredPropertiesIterator());
410
411
        $association = $class->getProperty('groups');
412
413
        self::assertTrue($association->isOwningSide());
414
415
        // Make sure that cascade-all works as expected
416
        self::assertEquals(['remove', 'persist', 'refresh'], $association->getCascade());
417
418
        // Test Order By
419
        self::assertEquals([], $association->getOrderBy());
420
421
        return $class;
422
    }
423
424
    /**
425
     * @depends testManyToManyAssociationWithCascadeAll
426
     * @param ClassMetadata $class
427
     */
428
    public function testLifecycleCallbacks($class)
429
    {
430
        self::assertEquals(count($class->lifecycleCallbacks), 2);
431
        self::assertEquals($class->lifecycleCallbacks['prePersist'][0], 'doStuffOnPrePersist');
432
        self::assertEquals($class->lifecycleCallbacks['postPersist'][0], 'doStuffOnPostPersist');
433
434
        return $class;
435
    }
436
437
    /**
438
     * @depends testManyToManyAssociationWithCascadeAll
439
     * @param ClassMetadata $class
440
     */
441
    public function testLifecycleCallbacksSupportMultipleMethodNames($class)
442
    {
443
        self::assertEquals(count($class->lifecycleCallbacks['prePersist']), 2);
444
        self::assertEquals($class->lifecycleCallbacks['prePersist'][1], 'doOtherStuffOnPrePersistToo');
445
446
        return $class;
447
    }
448
449
    /**
450
     * @depends testLifecycleCallbacksSupportMultipleMethodNames
451
     * @param ClassMetadata $class
452
     */
453
    public function testJoinColumnUniqueAndNullable($class)
454
    {
455
        // Non-Nullability of Join Column
456
        $association = $class->getProperty('groups');
457
        $joinTable   = $association->getJoinTable();
458
        $joinColumns = $joinTable->getJoinColumns();
459
        $joinColumn  = reset($joinColumns);
460
461
        self::assertFalse($joinColumn->isNullable());
462
        self::assertFalse($joinColumn->isUnique());
463
464
        return $class;
465
    }
466
467
    /**
468
     * @depends testJoinColumnUniqueAndNullable
469
     * @param ClassMetadata $class
470
     */
471
    public function testColumnDefinition($class)
472
    {
473
        self::assertNotNull($class->getProperty('email'));
474
475
        $property           = $class->getProperty('email');
476
        $association        = $class->getProperty('groups');
477
        $joinTable          = $association->getJoinTable();
478
        $inverseJoinColumns = $joinTable->getInverseJoinColumns();
479
        $inverseJoinColumn  = reset($inverseJoinColumns);
480
481
        self::assertEquals("CHAR(32) NOT NULL", $property->getColumnDefinition());
482
        self::assertEquals("INT NULL", $inverseJoinColumn->getColumnDefinition());
483
484
        return $class;
485
    }
486
487
    /**
488
     * @depends testColumnDefinition
489
     * @param ClassMetadata $class
490
     */
491
    public function testJoinColumnOnDelete($class)
492
    {
493
        $association = $class->getProperty('address');
494
        $joinColumns = $association->getJoinColumns();
495
        $joinColumn  = reset($joinColumns);
496
497
        self::assertEquals('CASCADE', $joinColumn->getOnDelete());
498
499
        return $class;
500
    }
501
502
    /**
503
     * @group DDC-514
504
     */
505
    public function testDiscriminatorColumnDefaults()
506
    {
507
        if (strpos(get_class($this), 'PHPMappingDriver') !== false) {
508
            $this->markTestSkipped('PHP Mapping Drivers have no defaults.');
509
        }
510
511
        $class = $this->createClassMetadata(Animal::class);
512
513
        self::assertNotNull($class->discriminatorColumn);
514
515
        $discrColumn = $class->discriminatorColumn;
516
517
        self::assertEquals('Animal', $discrColumn->getTableName());
518
        self::assertEquals('discr', $discrColumn->getColumnName());
519
        self::assertEquals('string', $discrColumn->getTypeName());
520
        self::assertEquals(32, $discrColumn->getLength());
521
        self::assertNull($discrColumn->getColumnDefinition());
522
    }
523
524
    /**
525
     * @group DDC-869
526
     */
527
    public function testMappedSuperclassWithRepository()
528
    {
529
        $em      = $this->getTestEntityManager();
530
        $factory = $this->createClassMetadataFactory($em);
531
        $class   = $factory->getMetadataFor(DDC869CreditCardPayment::class);
532
533
        self::assertNotNull($class->getProperty('id'));
534
        self::assertNotNull($class->getProperty('value'));
535
        self::assertNotNull($class->getProperty('creditCardNumber'));
536
        self::assertEquals($class->getCustomRepositoryClassName(), DDC869PaymentRepository::class);
537
        self::assertInstanceOf(DDC869PaymentRepository::class, $em->getRepository(DDC869CreditCardPayment::class));
538
        self::assertTrue($em->getRepository(DDC869ChequePayment::class)->isTrue());
539
540
        $class = $factory->getMetadataFor(DDC869ChequePayment::class);
541
542
        self::assertNotNull($class->getProperty('id'));
543
        self::assertNotNull($class->getProperty('value'));
544
        self::assertNotNull($class->getProperty('serialNumber'));
545
        self::assertEquals($class->getCustomRepositoryClassName(), DDC869PaymentRepository::class);
546
        self::assertInstanceOf(DDC869PaymentRepository::class, $em->getRepository(DDC869ChequePayment::class));
547
        self::assertTrue($em->getRepository(DDC869ChequePayment::class)->isTrue());
548
    }
549
550
    /**
551
     * @group DDC-1476
552
     */
553
    public function testDefaultFieldType()
554
    {
555
        $factory = $this->createClassMetadataFactory();
556
        $class   = $factory->getMetadataFor(DDC1476EntityWithDefaultFieldType::class);
557
558
        self::assertNotNull($class->getProperty('id'));
559
        self::assertNotNull($class->getProperty('name'));
560
561
        $idProperty = $class->getProperty('id');
562
        $nameProperty = $class->getProperty('name');
563
564
        self::assertInstanceOf(Mapping\FieldMetadata::class, $idProperty);
565
        self::assertInstanceOf(Mapping\FieldMetadata::class, $nameProperty);
566
567
        self::assertEquals('string', $idProperty->getTypeName());
568
        self::assertEquals('string', $nameProperty->getTypeName());
569
570
        self::assertEquals('id', $idProperty->getName());
571
        self::assertEquals('name', $nameProperty->getName());
572
573
        self::assertEquals('id', $idProperty->getColumnName());
574
        self::assertEquals('name', $nameProperty->getColumnName());
575
576
        self::assertFalse($idProperty->hasValueGenerator());
577
    }
578
579
    /**
580
     * @group DDC-1170
581
     */
582
    public function testIdentifierColumnDefinition()
583
    {
584
        $class = $this->createClassMetadata(DDC1170Entity::class);
585
586
        self::assertNotNull($class->getProperty('id'));
587
        self::assertNotNull($class->getProperty('value'));
588
589
        self::assertEquals("INT unsigned NOT NULL", $class->getProperty('id')->getColumnDefinition());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\ORM\Mapping\Property as the method getColumnDefinition() does only exist in the following implementations of said interface: Doctrine\ORM\Mapping\FieldMetadata, Doctrine\ORM\Mapping\VersionFieldMetadata.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
590
        self::assertEquals("VARCHAR(255) NOT NULL", $class->getProperty('value')->getColumnDefinition());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Doctrine\ORM\Mapping\Property as the method getColumnDefinition() does only exist in the following implementations of said interface: Doctrine\ORM\Mapping\FieldMetadata, Doctrine\ORM\Mapping\VersionFieldMetadata.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
591
    }
592
593
    /**
594
     * @group DDC-559
595
     */
596
    public function testNamingStrategy()
597
    {
598
        $em      = $this->getTestEntityManager();
599
        $factory = $this->createClassMetadataFactory($em);
600
601
        self::assertInstanceOf(DefaultNamingStrategy::class, $em->getConfiguration()->getNamingStrategy());
602
        $em->getConfiguration()->setNamingStrategy(new UnderscoreNamingStrategy(CASE_UPPER));
603
        self::assertInstanceOf(UnderscoreNamingStrategy::class, $em->getConfiguration()->getNamingStrategy());
604
605
        $class        = $factory->getMetadataFor(DDC1476EntityWithDefaultFieldType::class);
606
        $idProperty   = $class->getProperty('id');
607
        $nameProperty = $class->getProperty('name');
608
609
        self::assertEquals('ID', $idProperty->getColumnName());
610
        self::assertEquals('NAME', $nameProperty->getColumnName());
611
        self::assertEquals('DDC1476ENTITY_WITH_DEFAULT_FIELD_TYPE', $class->table->getName());
612
    }
613
614
    /**
615
     * @group DDC-807
616
     * @group DDC-553
617
     */
618
    public function testDiscriminatorColumnDefinition()
619
    {
620
        $class = $this->createClassMetadata(DDC807Entity::class);
621
622
        self::assertNotNull($class->discriminatorColumn);
623
624
        $discrColumn = $class->discriminatorColumn;
625
626
        self::assertEquals('dtype', $discrColumn->getColumnName());
627
        self::assertEquals("ENUM('ONE','TWO')", $discrColumn->getColumnDefinition());
628
    }
629
630
    /**
631
     * @group DDC-889
632
     */
633
    public function testInvalidEntityOrMappedSuperClassShouldMentionParentClasses()
634
    {
635
        $this->expectException(MappingException::class);
636
        $this->expectExceptionMessage('Class "Doctrine\Tests\Models\DDC889\DDC889Class" sub class of "Doctrine\Tests\Models\DDC889\DDC889SuperClass" is not a valid entity or mapped super class.');
637
638
        $this->createClassMetadata(DDC889Class::class);
639
    }
640
641
    /**
642
     * @group DDC-889
643
     */
644
    public function testIdentifierRequiredShouldMentionParentClasses()
645
    {
646
        $factory = $this->createClassMetadataFactory();
647
648
        $this->expectException(MappingException::class);
649
        $this->expectExceptionMessage('No identifier/primary key specified for Entity "Doctrine\Tests\Models\DDC889\DDC889Entity" sub class of "Doctrine\Tests\Models\DDC889\DDC889SuperClass". Every Entity must have an identifier/primary key.');
650
651
        $factory->getMetadataFor(DDC889Entity::class);
652
    }
653
654
    public function testNamedQuery()
655
    {
656
        $driver = $this->loadDriver();
657
        $class = $this->createClassMetadata(User::class);
658
659
        self::assertCount(1, $class->getNamedQueries(), sprintf("Named queries not processed correctly by driver %s", get_class($driver)));
660
    }
661
662
    /**
663
     * @group DDC-1663
664
     */
665
    public function testNamedNativeQuery()
666
    {
667
        $class = $this->createClassMetadata(CmsAddress::class);
668
669
        // named native query
670
        self::assertCount(3, $class->namedNativeQueries);
671
        self::assertArrayHasKey('find-all', $class->namedNativeQueries);
672
        self::assertArrayHasKey('find-by-id', $class->namedNativeQueries);
673
674
        $findAllQuery = $class->getNamedNativeQuery('find-all');
675
676
        self::assertEquals('mapping-find-all', $findAllQuery['resultSetMapping']);
677
        self::assertEquals('SELECT id, country, city FROM cms_addresses', $findAllQuery['query']);
678
679
        $findByIdQuery = $class->getNamedNativeQuery('find-by-id');
680
681
        self::assertEquals(CmsAddress::class,$findByIdQuery['resultClass']);
682
        self::assertEquals('SELECT * FROM cms_addresses WHERE id = ?',  $findByIdQuery['query']);
683
684
        $countQuery = $class->getNamedNativeQuery('count');
685
686
        self::assertEquals('mapping-count', $countQuery['resultSetMapping']);
687
        self::assertEquals('SELECT COUNT(*) AS count FROM cms_addresses',  $countQuery['query']);
688
689
        // result set mapping
690
        self::assertCount(3, $class->sqlResultSetMappings);
691
        self::assertArrayHasKey('mapping-count', $class->sqlResultSetMappings);
692
        self::assertArrayHasKey('mapping-find-all', $class->sqlResultSetMappings);
693
        self::assertArrayHasKey('mapping-without-fields', $class->sqlResultSetMappings);
694
695
        $findAllMapping = $class->getSqlResultSetMapping('mapping-find-all');
696
697
        self::assertEquals(CmsAddress::class, $findAllMapping['entities'][0]['entityClass']);
698
        self::assertEquals(['name'=>'id','column'=>'id'], $findAllMapping['entities'][0]['fields'][0]);
699
        self::assertEquals(['name'=>'city','column'=>'city'], $findAllMapping['entities'][0]['fields'][1]);
700
        self::assertEquals(['name'=>'country','column'=>'country'], $findAllMapping['entities'][0]['fields'][2]);
701
702
        $withoutFieldsMapping = $class->getSqlResultSetMapping('mapping-without-fields');
703
704
        self::assertEquals('__CLASS__', $withoutFieldsMapping['entities'][0]['entityClass']);
705
        self::assertEquals([], $withoutFieldsMapping['entities'][0]['fields']);
706
707
        $countMapping = $class->getSqlResultSetMapping('mapping-count');
708
709
        self::assertEquals(['name'=>'count'], $countMapping['columns'][0]);
710
711
    }
712
713
    /**
714
     * @group DDC-1663
715
     */
716
    public function testSqlResultSetMapping()
717
    {
718
        $userMetadata   = $this->createClassMetadata(CmsUser::class);
719
        $personMetadata = $this->createClassMetadata(CompanyPerson::class);
720
721
        // user asserts
722
        self::assertCount(4, $userMetadata->getSqlResultSetMappings());
723
724
        $mapping = $userMetadata->getSqlResultSetMapping('mappingJoinedAddress');
725
726
        self::assertEquals([],$mapping['columns']);
727
        self::assertEquals('mappingJoinedAddress', $mapping['name']);
728
729
        self::assertNull($mapping['entities'][0]['discriminatorColumn']);
730
731
        self::assertEquals(['name'=>'id','column'=>'id'],                   $mapping['entities'][0]['fields'][0]);
732
        self::assertEquals(['name'=>'name','column'=>'name'],               $mapping['entities'][0]['fields'][1]);
733
        self::assertEquals(['name'=>'status','column'=>'status'],           $mapping['entities'][0]['fields'][2]);
734
        self::assertEquals(['name'=>'address.zip','column'=>'zip'],         $mapping['entities'][0]['fields'][3]);
735
        self::assertEquals(['name'=>'address.city','column'=>'city'],       $mapping['entities'][0]['fields'][4]);
736
        self::assertEquals(['name'=>'address.country','column'=>'country'], $mapping['entities'][0]['fields'][5]);
737
        self::assertEquals(['name'=>'address.id','column'=>'a_id'],         $mapping['entities'][0]['fields'][6]);
738
        self::assertEquals('__CLASS__',                            $mapping['entities'][0]['entityClass']);
739
740
        $mapping = $userMetadata->getSqlResultSetMapping('mappingJoinedPhonenumber');
741
742
        self::assertEquals([],$mapping['columns']);
743
        self::assertEquals('mappingJoinedPhonenumber', $mapping['name']);
744
745
        self::assertNull($mapping['entities'][0]['discriminatorColumn']);
746
747
        self::assertEquals(['name'=>'id','column'=>'id'],                             $mapping['entities'][0]['fields'][0]);
748
        self::assertEquals(['name'=>'name','column'=>'name'],                         $mapping['entities'][0]['fields'][1]);
749
        self::assertEquals(['name'=>'status','column'=>'status'],                     $mapping['entities'][0]['fields'][2]);
750
        self::assertEquals(['name'=>'phonenumbers.phonenumber','column'=>'number'],   $mapping['entities'][0]['fields'][3]);
751
        self::assertEquals($userMetadata->getClassName(),                             $mapping['entities'][0]['entityClass']);
752
753
        $mapping = $userMetadata->getSqlResultSetMapping('mappingUserPhonenumberCount');
754
755
        self::assertEquals(['name'=>'numphones'],$mapping['columns'][0]);
756
        self::assertEquals('mappingUserPhonenumberCount', $mapping['name']);
757
758
        self::assertNull($mapping['entities'][0]['discriminatorColumn']);
759
760
        self::assertEquals(['name'=>'id','column'=>'id'],         $mapping['entities'][0]['fields'][0]);
761
        self::assertEquals(['name'=>'name','column'=>'name'],     $mapping['entities'][0]['fields'][1]);
762
        self::assertEquals(['name'=>'status','column'=>'status'], $mapping['entities'][0]['fields'][2]);
763
        self::assertEquals($userMetadata->getClassName(),         $mapping['entities'][0]['entityClass']);
764
765
        $mapping = $userMetadata->getSqlResultSetMapping('mappingMultipleJoinsEntityResults');
766
767
        self::assertEquals(['name'=>'numphones'],$mapping['columns'][0]);
768
        self::assertEquals('mappingMultipleJoinsEntityResults', $mapping['name']);
769
770
        self::assertNull($mapping['entities'][0]['discriminatorColumn']);
771
772
        self::assertEquals(['name'=>'id','column'=>'u_id'],           $mapping['entities'][0]['fields'][0]);
773
        self::assertEquals(['name'=>'name','column'=>'u_name'],       $mapping['entities'][0]['fields'][1]);
774
        self::assertEquals(['name'=>'status','column'=>'u_status'],   $mapping['entities'][0]['fields'][2]);
775
        self::assertEquals('__CLASS__',                      $mapping['entities'][0]['entityClass']);
776
777
        self::assertNull($mapping['entities'][1]['discriminatorColumn']);
778
779
        self::assertEquals(['name'=>'id','column'=>'a_id'],           $mapping['entities'][1]['fields'][0]);
780
        self::assertEquals(['name'=>'zip','column'=>'a_zip'],         $mapping['entities'][1]['fields'][1]);
781
        self::assertEquals(['name'=>'country','column'=>'a_country'], $mapping['entities'][1]['fields'][2]);
782
        self::assertEquals(CmsAddress::class,                $mapping['entities'][1]['entityClass']);
783
784
        //person asserts
785
        self::assertCount(1, $personMetadata->getSqlResultSetMappings());
786
787
        $mapping = $personMetadata->getSqlResultSetMapping('mappingFetchAll');
788
789
        self::assertEquals([], $mapping['columns']);
790
        self::assertEquals('mappingFetchAll', $mapping['name']);
791
792
        self::assertEquals('discriminator', $mapping['entities'][0]['discriminatorColumn']);
793
794
        self::assertEquals(['name'=>'id','column'=>'id'],     $mapping['entities'][0]['fields'][0]);
795
        self::assertEquals(['name'=>'name','column'=>'name'], $mapping['entities'][0]['fields'][1]);
796
        self::assertEquals('__CLASS__',              $mapping['entities'][0]['entityClass']);
797
    }
798
799
    /*
800
     * @group DDC-964
801
     */
802
    public function testAssociationOverridesMapping()
803
    {
804
        $factory        = $this->createClassMetadataFactory();
805
        $adminMetadata  = $factory->getMetadataFor(DDC964Admin::class);
806
        $guestMetadata  = $factory->getMetadataFor(DDC964Guest::class);
807
808
        // assert groups association mappings
809
        self::assertArrayHasKey('groups', $guestMetadata->getDeclaredPropertiesIterator());
810
        self::assertArrayHasKey('groups', $adminMetadata->getDeclaredPropertiesIterator());
811
812
        $guestGroups = $guestMetadata->getProperty('groups');
813
        $adminGroups = $adminMetadata->getProperty('groups');
814
815
        // assert not override attributes
816
        self::assertEquals($guestGroups->getName(), $adminGroups->getName());
817
        self::assertEquals(get_class($guestGroups), get_class($adminGroups));
818
        self::assertEquals($guestGroups->getMappedBy(), $adminGroups->getMappedBy());
819
        self::assertEquals($guestGroups->getInversedBy(), $adminGroups->getInversedBy());
820
        self::assertEquals($guestGroups->isOwningSide(), $adminGroups->isOwningSide());
821
        self::assertEquals($guestGroups->getFetchMode(), $adminGroups->getFetchMode());
822
        self::assertEquals($guestGroups->getCascade(), $adminGroups->getCascade());
823
824
         // assert not override attributes
825
        $guestGroupsJoinTable          = $guestGroups->getJoinTable();
826
        $guestGroupsJoinColumns        = $guestGroupsJoinTable->getJoinColumns();
827
        $guestGroupsJoinColumn         = reset($guestGroupsJoinColumns);
828
        $guestGroupsInverseJoinColumns = $guestGroupsJoinTable->getInverseJoinColumns();
829
        $guestGroupsInverseJoinColumn  = reset($guestGroupsInverseJoinColumns);
830
831
        self::assertEquals('ddc964_users_groups', $guestGroupsJoinTable->getName());
832
        self::assertEquals('user_id', $guestGroupsJoinColumn->getColumnName());
833
        self::assertEquals('group_id', $guestGroupsInverseJoinColumn->getColumnName());
834
835
        $adminGroupsJoinTable          = $adminGroups->getJoinTable();
836
        $adminGroupsJoinColumns        = $adminGroupsJoinTable->getJoinColumns();
837
        $adminGroupsJoinColumn         = reset($adminGroupsJoinColumns);
838
        $adminGroupsInverseJoinColumns = $adminGroupsJoinTable->getInverseJoinColumns();
839
        $adminGroupsInverseJoinColumn  = reset($adminGroupsInverseJoinColumns);
840
841
        self::assertEquals('ddc964_users_admingroups', $adminGroupsJoinTable->getName());
842
        self::assertEquals('adminuser_id', $adminGroupsJoinColumn->getColumnName());
843
        self::assertEquals('admingroup_id', $adminGroupsInverseJoinColumn->getColumnName());
844
845
        // assert address association mappings
846
        self::assertArrayHasKey('address', $guestMetadata->getDeclaredPropertiesIterator());
847
        self::assertArrayHasKey('address', $adminMetadata->getDeclaredPropertiesIterator());
848
849
        $guestAddress = $guestMetadata->getProperty('address');
850
        $adminAddress = $adminMetadata->getProperty('address');
851
852
        // assert not override attributes
853
        self::assertEquals($guestAddress->getName(), $adminAddress->getName());
854
        self::assertEquals(get_class($guestAddress), get_class($adminAddress));
855
        self::assertEquals($guestAddress->getMappedBy(), $adminAddress->getMappedBy());
856
        self::assertEquals($guestAddress->getInversedBy(), $adminAddress->getInversedBy());
857
        self::assertEquals($guestAddress->isOwningSide(), $adminAddress->isOwningSide());
858
        self::assertEquals($guestAddress->getFetchMode(), $adminAddress->getFetchMode());
859
        self::assertEquals($guestAddress->getCascade(), $adminAddress->getCascade());
860
861
        // assert override
862
        $guestAddressJoinColumns = $guestAddress->getJoinColumns();
863
        $guestAddressJoinColumn  = reset($guestAddressJoinColumns);
864
865
        self::assertEquals('address_id', $guestAddressJoinColumn->getColumnName());
866
867
        $adminAddressJoinColumns = $adminAddress->getJoinColumns();
868
        $adminAddressJoinColumn  = reset($adminAddressJoinColumns);
869
870
        self::assertEquals('adminaddress_id', $adminAddressJoinColumn->getColumnName());
871
    }
872
873
    /*
874
     * @group DDC-3579
875
     */
876
    public function testInversedByOverrideMapping()
877
    {
878
        $factory        = $this->createClassMetadataFactory();
879
        $adminMetadata  = $factory->getMetadataFor(DDC3579Admin::class);
880
881
        // assert groups association mappings
882
        self::assertArrayHasKey('groups', $adminMetadata->getDeclaredPropertiesIterator());
883
884
        $adminGroups = $adminMetadata->getProperty('groups');
885
886
        // assert override
887
        self::assertEquals('admins', $adminGroups->getInversedBy());
888
    }
889
890
    /**
891
     * @group DDC-5934
892
     */
893
    public function testFetchOverrideMapping()
894
    {
895
        // check override metadata
896
        $contractMetadata = $this->createClassMetadataFactory()->getMetadataFor(DDC5934Contract::class);
897
898
        self::assertArrayHasKey('members', $contractMetadata->getDeclaredPropertiesIterator());
899
900
        $contractMembers = $contractMetadata->getProperty('members');
901
902
        self::assertSame(Mapping\FetchMode::EXTRA_LAZY, $contractMembers->getFetchMode());
903
    }
904
905
    /**
906
     * @group DDC-964
907
     */
908
    public function testAttributeOverridesMapping()
909
    {
910
        $factory       = $this->createClassMetadataFactory();
911
        $adminMetadata = $factory->getMetadataFor(DDC964Admin::class);
912
913
        self::assertEquals(
914
            [
915
                'user_id' => 'id',
916
                'user_name' => 'name',
917
                'adminaddress_id' => 'address',
918
            ],
919
            $adminMetadata->fieldNames
920
        );
921
922
        self::assertNotNull($adminMetadata->getProperty('id'));
923
924
        $idProperty = $adminMetadata->getProperty('id');
925
926
        self::assertTrue($idProperty->isPrimaryKey());
927
        self::assertEquals('id', $idProperty->getName());
928
        self::assertEquals('user_id', $idProperty->getColumnName());
929
930
        self::assertNotNull($adminMetadata->getProperty('name'));
931
932
        $nameProperty = $adminMetadata->getProperty('name');
933
934
        self::assertEquals('name', $nameProperty->getName());
935
        self::assertEquals('user_name', $nameProperty->getColumnName());
936
        self::assertEquals(250, $nameProperty->getLength());
937
        self::assertTrue($nameProperty->isNullable());
938
        self::assertFalse($nameProperty->isUnique());
939
940
        $guestMetadata = $factory->getMetadataFor(DDC964Guest::class);
941
942
        self::assertEquals(
943
            [
944
                'guest_id' => 'id',
945
                'guest_name' => 'name',
946
                'address_id' => 'address',
947
            ],
948
            $guestMetadata->fieldNames
949
        );
950
951
        self::assertNotNull($guestMetadata->getProperty('id'));
952
953
        $idProperty = $guestMetadata->getProperty('id');
954
955
        self::assertTrue($idProperty->isPrimaryKey());
956
        self::assertEquals('id', $idProperty->getName());
957
        self::assertEquals('guest_id', $idProperty->getColumnName());
958
959
        self::assertNotNull($guestMetadata->getProperty('name'));
960
961
        $nameProperty = $guestMetadata->getProperty('name');
962
963
        self::assertEquals('name', $nameProperty->getName());
964
        self::assertEquals('guest_name', $nameProperty->getColumnName());
965
        self::assertEquals(240, $nameProperty->getLength());
966
        self::assertFalse($nameProperty->isNullable());
967
        self::assertTrue($nameProperty->isUnique());
968
    }
969
970
    /**
971
     * @group DDC-1955
972
     */
973
    public function testEntityListeners()
974
    {
975
        $factory    = $this->createClassMetadataFactory();
976
        $superClass = $factory->getMetadataFor(CompanyContract::class);
977
        $flexClass  = $factory->getMetadataFor(CompanyFixContract::class);
978
        $fixClass   = $factory->getMetadataFor(CompanyFlexContract::class);
979
980
        self::assertArrayHasKey(Events::prePersist, $superClass->entityListeners);
981
        self::assertArrayHasKey(Events::postPersist, $superClass->entityListeners);
982
983
        self::assertCount(1, $superClass->entityListeners[Events::prePersist]);
984
        self::assertCount(1, $superClass->entityListeners[Events::postPersist]);
985
986
        $postPersist = $superClass->entityListeners[Events::postPersist][0];
987
        $prePersist  = $superClass->entityListeners[Events::prePersist][0];
988
989
        self::assertEquals(CompanyContractListener::class, $postPersist['class']);
990
        self::assertEquals(CompanyContractListener::class, $prePersist['class']);
991
        self::assertEquals('postPersistHandler', $postPersist['method']);
992
        self::assertEquals('prePersistHandler', $prePersist['method']);
993
994
        //Inherited listeners
995
        self::assertEquals($fixClass->entityListeners, $superClass->entityListeners);
996
        self::assertEquals($flexClass->entityListeners, $superClass->entityListeners);
997
    }
998
999
    /**
1000
     * @group DDC-1955
1001
     */
1002
    public function testEntityListenersOverride()
1003
    {
1004
        $factory    = $this->createClassMetadataFactory();
1005
        $ultraClass = $factory->getMetadataFor(CompanyFlexUltraContract::class);
1006
1007
        //overridden listeners
1008
        self::assertArrayHasKey(Events::postPersist, $ultraClass->entityListeners);
1009
        self::assertArrayHasKey(Events::prePersist, $ultraClass->entityListeners);
1010
1011
        self::assertCount(1, $ultraClass->entityListeners[Events::postPersist]);
1012
        self::assertCount(3, $ultraClass->entityListeners[Events::prePersist]);
1013
1014
        $postPersist = $ultraClass->entityListeners[Events::postPersist][0];
1015
        $prePersist  = $ultraClass->entityListeners[Events::prePersist][0];
1016
1017
        self::assertEquals(CompanyContractListener::class, $postPersist['class']);
1018
        self::assertEquals(CompanyContractListener::class, $prePersist['class']);
1019
        self::assertEquals('postPersistHandler', $postPersist['method']);
1020
        self::assertEquals('prePersistHandler', $prePersist['method']);
1021
1022
        $prePersist = $ultraClass->entityListeners[Events::prePersist][1];
1023
        self::assertEquals(CompanyFlexUltraContractListener::class, $prePersist['class']);
1024
        self::assertEquals('prePersistHandler1', $prePersist['method']);
1025
1026
        $prePersist = $ultraClass->entityListeners[Events::prePersist][2];
1027
        self::assertEquals(CompanyFlexUltraContractListener::class, $prePersist['class']);
1028
        self::assertEquals('prePersistHandler2', $prePersist['method']);
1029
    }
1030
1031
1032
    /**
1033
     * @group DDC-1955
1034
     */
1035
    public function testEntityListenersNamingConvention()
1036
    {
1037
        $factory  = $this->createClassMetadataFactory();
1038
        $metadata = $factory->getMetadataFor(CmsAddress::class);
1039
1040
        self::assertArrayHasKey(Events::postPersist, $metadata->entityListeners);
1041
        self::assertArrayHasKey(Events::prePersist, $metadata->entityListeners);
1042
        self::assertArrayHasKey(Events::postUpdate, $metadata->entityListeners);
1043
        self::assertArrayHasKey(Events::preUpdate, $metadata->entityListeners);
1044
        self::assertArrayHasKey(Events::postRemove, $metadata->entityListeners);
1045
        self::assertArrayHasKey(Events::preRemove, $metadata->entityListeners);
1046
        self::assertArrayHasKey(Events::postLoad, $metadata->entityListeners);
1047
        self::assertArrayHasKey(Events::preFlush, $metadata->entityListeners);
1048
1049
        self::assertCount(1, $metadata->entityListeners[Events::postPersist]);
1050
        self::assertCount(1, $metadata->entityListeners[Events::prePersist]);
1051
        self::assertCount(1, $metadata->entityListeners[Events::postUpdate]);
1052
        self::assertCount(1, $metadata->entityListeners[Events::preUpdate]);
1053
        self::assertCount(1, $metadata->entityListeners[Events::postRemove]);
1054
        self::assertCount(1, $metadata->entityListeners[Events::preRemove]);
1055
        self::assertCount(1, $metadata->entityListeners[Events::postLoad]);
1056
        self::assertCount(1, $metadata->entityListeners[Events::preFlush]);
1057
1058
        $postPersist = $metadata->entityListeners[Events::postPersist][0];
1059
        $prePersist  = $metadata->entityListeners[Events::prePersist][0];
1060
        $postUpdate  = $metadata->entityListeners[Events::postUpdate][0];
1061
        $preUpdate   = $metadata->entityListeners[Events::preUpdate][0];
1062
        $postRemove  = $metadata->entityListeners[Events::postRemove][0];
1063
        $preRemove   = $metadata->entityListeners[Events::preRemove][0];
1064
        $postLoad    = $metadata->entityListeners[Events::postLoad][0];
1065
        $preFlush    = $metadata->entityListeners[Events::preFlush][0];
1066
1067
        self::assertEquals(CmsAddressListener::class, $postPersist['class']);
1068
        self::assertEquals(CmsAddressListener::class, $prePersist['class']);
1069
        self::assertEquals(CmsAddressListener::class, $postUpdate['class']);
1070
        self::assertEquals(CmsAddressListener::class, $preUpdate['class']);
1071
        self::assertEquals(CmsAddressListener::class, $postRemove['class']);
1072
        self::assertEquals(CmsAddressListener::class, $preRemove['class']);
1073
        self::assertEquals(CmsAddressListener::class, $postLoad['class']);
1074
        self::assertEquals(CmsAddressListener::class, $preFlush['class']);
1075
1076
        self::assertEquals(Events::postPersist, $postPersist['method']);
1077
        self::assertEquals(Events::prePersist, $prePersist['method']);
1078
        self::assertEquals(Events::postUpdate, $postUpdate['method']);
1079
        self::assertEquals(Events::preUpdate, $preUpdate['method']);
1080
        self::assertEquals(Events::postRemove, $postRemove['method']);
1081
        self::assertEquals(Events::preRemove, $preRemove['method']);
1082
        self::assertEquals(Events::postLoad, $postLoad['method']);
1083
        self::assertEquals(Events::preFlush, $preFlush['method']);
1084
    }
1085
1086
    /**
1087
     * @group DDC-2183
1088
     */
1089
    public function testSecondLevelCacheMapping()
1090
    {
1091
        $factory = $this->createClassMetadataFactory();
1092
        $class   = $factory->getMetadataFor(City::class);
1093
1094
        self::assertNotNull($class->getCache());
1095
        self::assertEquals(Mapping\CacheUsage::READ_ONLY, $class->getCache()->getUsage());
1096
        self::assertEquals('doctrine_tests_models_cache_city', $class->getCache()->getRegion());
1097
1098
        self::assertArrayHasKey('state', $class->getDeclaredPropertiesIterator());
1099
1100
        $stateAssociation = $class->getProperty('state');
1101
1102
        self::assertNotNull($stateAssociation->getCache());
1103
        self::assertEquals(Mapping\CacheUsage::READ_ONLY, $stateAssociation->getCache()->getUsage());
1104
        self::assertEquals('doctrine_tests_models_cache_city__state', $stateAssociation->getCache()->getRegion());
1105
1106
        self::assertArrayHasKey('attractions', $class->getDeclaredPropertiesIterator());
1107
1108
        $attractionsAssociation = $class->getProperty('attractions');
1109
1110
        self::assertNotNull($attractionsAssociation->getCache());
1111
        self::assertEquals(Mapping\CacheUsage::READ_ONLY, $attractionsAssociation->getCache()->getUsage());
1112
        self::assertEquals('doctrine_tests_models_cache_city__attractions', $attractionsAssociation->getCache()->getRegion());
1113
    }
1114
1115
    /**
1116
     * @group DDC-2825
1117
     * @group 881
1118
     */
1119 View Code Duplication
    public function testSchemaDefinitionViaExplicitTableSchemaAnnotationProperty()
1120
    {
1121
        $factory  = $this->createClassMetadataFactory();
1122
        $metadata = $factory->getMetadataFor(ExplicitSchemaAndTable::class);
1123
1124
        self::assertSame('explicit_schema', $metadata->getSchemaName());
1125
        self::assertSame('explicit_table', $metadata->getTableName());
1126
    }
1127
1128
    /**
1129
     * @group DDC-2825
1130
     * @group 881
1131
     */
1132 View Code Duplication
    public function testSchemaDefinitionViaSchemaDefinedInTableNameInTableAnnotationProperty()
1133
    {
1134
        $factory  = $this->createClassMetadataFactory();
1135
        $metadata = $factory->getMetadataFor(SchemaAndTableInTableName::class);
1136
1137
        self::assertSame('implicit_schema', $metadata->getSchemaName());
1138
        self::assertSame('implicit_table', $metadata->getTableName());
1139
    }
1140
1141
    /**
1142
     * @group DDC-514
1143
     * @group DDC-1015
1144
     */
1145 View Code Duplication
    public function testDiscriminatorColumnDefaultLength()
1146
    {
1147
        if (strpos(get_class($this), 'PHPMappingDriver') !== false) {
1148
            $this->markTestSkipped('PHP Mapping Drivers have no defaults.');
1149
        }
1150
1151
        $class = $this->createClassMetadata(SingleTableEntityNoDiscriminatorColumnMapping::class);
1152
1153
        self::assertEquals(255, $class->discriminatorColumn->getLength());
1154
1155
        $class = $this->createClassMetadata(SingleTableEntityIncompleteDiscriminatorColumnMapping::class);
1156
1157
        self::assertEquals(255, $class->discriminatorColumn->getLength());
1158
    }
1159
1160
    /**
1161
     * @group DDC-514
1162
     * @group DDC-1015
1163
     */
1164 View Code Duplication
    public function testDiscriminatorColumnDefaultType()
1165
    {
1166
        if (strpos(get_class($this), 'PHPMappingDriver') !== false) {
1167
            $this->markTestSkipped('PHP Mapping Drivers have no defaults.');
1168
        }
1169
1170
        $class = $this->createClassMetadata(SingleTableEntityNoDiscriminatorColumnMapping::class);
1171
1172
        self::assertEquals('string', $class->discriminatorColumn->getTypeName());
1173
1174
        $class = $this->createClassMetadata(SingleTableEntityIncompleteDiscriminatorColumnMapping::class);
1175
1176
        self::assertEquals('string', $class->discriminatorColumn->getTypeName());
1177
    }
1178
1179
    /**
1180
     * @group DDC-514
1181
     * @group DDC-1015
1182
     */
1183 View Code Duplication
    public function testDiscriminatorColumnDefaultName()
1184
    {
1185
        if (strpos(get_class($this), 'PHPMappingDriver') !== false) {
1186
            $this->markTestSkipped('PHP Mapping Drivers have no defaults.');
1187
        }
1188
1189
        $class = $this->createClassMetadata(SingleTableEntityNoDiscriminatorColumnMapping::class);
1190
1191
        self::assertEquals('dtype', $class->discriminatorColumn->getColumnName());
1192
1193
        $class = $this->createClassMetadata(SingleTableEntityIncompleteDiscriminatorColumnMapping::class);
1194
1195
        self::assertEquals('dtype', $class->discriminatorColumn->getColumnName());
1196
    }
1197
}
1198
1199
/**
1200
 * @ORM\Entity
1201
 * @ORM\HasLifecycleCallbacks
1202
 * @ORM\Table(
1203
 *  name="cms_users",
1204
 *  uniqueConstraints={@ORM\UniqueConstraint(name="search_idx", columns={"name", "user_email"})},
1205
 *  indexes={@ORM\Index(name="name_idx", columns={"name"}), @ORM\Index(columns={"user_email"})},
1206
 *  options={"foo": "bar", "baz": {"key": "val"}}
1207
 * )
1208
 * @ORM\NamedQueries({@ORM\NamedQuery(name="all", query="SELECT u FROM __CLASS__ u")})
1209
 */
1210
class User
1211
{
1212
    /**
1213
     * @ORM\Id
1214
     * @ORM\Column(type="integer", options={"foo": "bar", "unsigned": false})
1215
     * @ORM\GeneratedValue(strategy="AUTO")
1216
     * @ORM\SequenceGenerator(sequenceName="tablename_seq", allocationSize=100)
1217
     **/
1218
    public $id;
1219
1220
    /**
1221
     * @ORM\Column(length=50, nullable=true, unique=true, options={"foo": "bar", "baz": {"key": "val"}, "fixed": false})
1222
     */
1223
    public $name;
1224
1225
    /**
1226
     * @ORM\Column(name="user_email", columnDefinition="CHAR(32) NOT NULL")
1227
     */
1228
    public $email;
1229
1230
    /**
1231
     * @ORM\OneToOne(targetEntity="Address", cascade={"remove"}, inversedBy="user")
1232
     * @ORM\JoinColumn(onDelete="CASCADE")
1233
     */
1234
    public $address;
1235
1236
    /**
1237
     * @ORM\OneToMany(targetEntity="Phonenumber", mappedBy="user", cascade={"persist"}, orphanRemoval=true)
1238
     * @ORM\OrderBy({"number"="ASC"})
1239
     */
1240
    public $phonenumbers;
1241
1242
    /**
1243
     * @ORM\ManyToMany(targetEntity="Group", cascade={"all"})
1244
     * @ORM\JoinTable(name="cms_user_groups",
1245
     *    joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false, unique=false)},
1246
     *    inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id", columnDefinition="INT NULL")}
1247
     * )
1248
     */
1249
    public $groups;
1250
1251
    /**
1252
     * @ORM\Column(type="integer")
1253
     * @ORM\Version
1254
     */
1255
    public $version;
1256
1257
1258
    /**
1259
     * @ORM\PrePersist
1260
     */
1261
    public function doStuffOnPrePersist()
1262
    {
1263
    }
1264
1265
    /**
1266
     * @ORM\PrePersist
1267
     */
1268
    public function doOtherStuffOnPrePersistToo() {
1269
    }
1270
1271
    /**
1272
     * @ORM\PostPersist
1273
     */
1274
    public function doStuffOnPostPersist()
1275
    {
1276
1277
    }
1278
1279
    public static function loadMetadata(ClassMetadata $metadata)
1280
    {
1281
        $tableMetadata = new Mapping\TableMetadata();
1282
1283
        $tableMetadata->setName('cms_users');
1284
        $tableMetadata->addIndex(
1285
            [
1286
                'name'    => 'name_idx',
1287
                'columns' => ['name'],
1288
                'unique'  => false,
1289
                'options' => [],
1290
                'flags'   => [],
1291
            ]
1292
        );
1293
1294
        $tableMetadata->addIndex(
1295
            [
1296
                'name'    => null,
1297
                'columns' => ['user_email'],
1298
                'unique'  => false,
1299
                'options' => [],
1300
                'flags'   => [],
1301
            ]
1302
        );
1303
1304
        $tableMetadata->addUniqueConstraint(
1305
            [
1306
                'name'    => 'search_idx',
1307
                'columns' => ['name', 'user_email'],
1308
                'options' => [],
1309
                'flags'   => [],
1310
            ]
1311
        );
1312
        $tableMetadata->addOption('foo', 'bar');
1313
        $tableMetadata->addOption('baz', ['key' => 'val']);
1314
1315
        $metadata->setTable($tableMetadata);
1316
        $metadata->setInheritanceType(Mapping\InheritanceType::NONE);
1317
        $metadata->setChangeTrackingPolicy(Mapping\ChangeTrackingPolicy::DEFERRED_IMPLICIT);
1318
1319
        $metadata->addLifecycleCallback('doStuffOnPrePersist', 'prePersist');
1320
        $metadata->addLifecycleCallback('doOtherStuffOnPrePersistToo', 'prePersist');
1321
        $metadata->addLifecycleCallback('doStuffOnPostPersist', 'postPersist');
1322
1323
        $metadata->setGeneratorDefinition(
0 ignored issues
show
Bug introduced by
The method setGeneratorDefinition() does not seem to exist on object<Doctrine\ORM\Mapping\ClassMetadata>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1324
            [
1325
                'sequenceName'   => 'tablename_seq',
1326
                'allocationSize' => 100,
1327
            ]
1328
        );
1329
1330
        $metadata->addNamedQuery(
0 ignored issues
show
Bug introduced by
The call to addNamedQuery() misses a required argument $query.

This check looks for function calls that miss required arguments.

Loading history...
1331
            [
0 ignored issues
show
Documentation introduced by
array('name' => 'all', '...CT u FROM __CLASS__ u') is of type array<string,string,{"na...ing","query":"string"}>, but the function expects a string.

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...
1332
                'name' => 'all',
1333
                'query' => 'SELECT u FROM __CLASS__ u'
1334
            ]
1335
        );
1336
1337
        $fieldMetadata = new Mapping\FieldMetadata('id');
1338
        $fieldMetadata->setType(Type::getType('integer'));
1339
        $fieldMetadata->setPrimaryKey(true);
1340
        $fieldMetadata->setOptions(['foo' => 'bar', 'unsigned' => false]);
1341
1342
        $metadata->addProperty($fieldMetadata);
1343
1344
        $fieldMetadata = new Mapping\FieldMetadata('name');
1345
        $fieldMetadata->setType(Type::getType('string'));
1346
        $fieldMetadata->setLength(50);
1347
        $fieldMetadata->setNullable(true);
1348
        $fieldMetadata->setUnique(true);
1349
        $fieldMetadata->setOptions(
1350
            [
1351
                'foo' => 'bar',
1352
                'baz' => [
1353
                    'key' => 'val',
1354
                ],
1355
                'fixed' => false,
1356
            ]
1357
        );
1358
1359
        $metadata->addProperty($fieldMetadata);
1360
1361
        $fieldMetadata = new Mapping\FieldMetadata('email');
1362
1363
        $fieldMetadata->setType(Type::getType('string'));
1364
        $fieldMetadata->setColumnName('user_email');
1365
        $fieldMetadata->setColumnDefinition('CHAR(32) NOT NULL');
1366
1367
        $metadata->addProperty($fieldMetadata);
1368
1369
        $fieldMetadata = new Mapping\VersionFieldMetadata('version');
1370
1371
        $fieldMetadata->setType(Type::getType('integer'));
1372
1373
        $metadata->addProperty($fieldMetadata);
1374
        $metadata->setIdGeneratorType(Mapping\GeneratorType::AUTO);
0 ignored issues
show
Bug introduced by
The method setIdGeneratorType() does not seem to exist on object<Doctrine\ORM\Mapping\ClassMetadata>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1375
1376
        $joinColumns = [];
1377
1378
        $joinColumn = new Mapping\JoinColumnMetadata();
1379
1380
        $joinColumn->setColumnName('address_id');
1381
        $joinColumn->setReferencedColumnName('id');
1382
        $joinColumn->setOnDelete('CASCADE');
1383
1384
        $joinColumns[] = $joinColumn;
1385
1386
        $association = new Mapping\OneToOneAssociationMetadata('address');
1387
1388
        $association->setJoinColumns($joinColumns);
1389
        $association->setTargetEntity(Address::class);
1390
        $association->setInversedBy('user');
1391
        $association->setCascade(['remove']);
1392
        $association->setOrphanRemoval(false);
1393
1394
        $metadata->addProperty($association);
1395
1396
        $association = new Mapping\OneToManyAssociationMetadata('phonenumbers');
1397
1398
        $association->setTargetEntity(Phonenumber::class);
1399
        $association->setMappedBy('user');
1400
        $association->setCascade(['persist']);
1401
        $association->setOrderBy(['number' => 'ASC']);
1402
        $association->setOrphanRemoval(true);
1403
1404
        $metadata->addProperty($association);
1405
1406
        $joinTable = new Mapping\JoinTableMetadata();
1407
        $joinTable->setName('cms_users_groups');
1408
1409
        $joinColumn = new Mapping\JoinColumnMetadata();
1410
1411
        $joinColumn->setColumnName('user_id');
1412
        $joinColumn->setReferencedColumnName('id');
1413
        $joinColumn->setNullable(false);
1414
        $joinColumn->setUnique(false);
1415
1416
        $joinTable->addJoinColumn($joinColumn);
1417
1418
        $joinColumn = new Mapping\JoinColumnMetadata();
1419
1420
        $joinColumn->setColumnName('group_id');
1421
        $joinColumn->setReferencedColumnName('id');
1422
        $joinColumn->setColumnDefinition('INT NULL');
1423
1424
        $joinTable->addInverseJoinColumn($joinColumn);
1425
1426
        $association = new Mapping\ManyToManyAssociationMetadata('groups');
1427
1428
        $association->setJoinTable($joinTable);
1429
        $association->setTargetEntity(Group::class);
1430
        $association->setCascade(['remove', 'persist', 'refresh']);
1431
1432
        $metadata->addProperty($association);
1433
    }
1434
}
1435
1436
/**
1437
 * @ORM\Entity
1438
 * @ORM\InheritanceType("SINGLE_TABLE")
1439
 * @ORM\DiscriminatorMap({"cat" = "Cat", "dog" = "Dog"})
1440
 * @ORM\DiscriminatorColumn(name="discr", length=32, type="string")
1441
 */
1442
abstract class Animal
1443
{
1444
    /**
1445
     * @ORM\Id @ORM\Column(type="string") @ORM\GeneratedValue(strategy="CUSTOM")
1446
     * @ORM\CustomIdGenerator(class="stdClass")
1447
     */
1448
    public $id;
1449
}
1450
1451
/** @ORM\Entity */
1452
class Cat extends Animal
1453
{
1454
}
1455
1456
/** @ORM\Entity */
1457
class Dog extends Animal
1458
{
1459
}
1460
1461
/**
1462
 * @ORM\Entity
1463
 */
1464
class DDC1170Entity
1465
{
1466
    /**
1467
     * @param string $value
1468
     */
1469
    public function __construct($value = null)
1470
    {
1471
        $this->value = $value;
1472
    }
1473
1474
    /**
1475
     * @ORM\Id
1476
     * @ORM\GeneratedValue(strategy="NONE")
1477
     * @ORM\Column(type="integer", columnDefinition = "INT unsigned NOT NULL")
1478
     **/
1479
    private $id;
1480
1481
    /**
1482
     * @ORM\Column(columnDefinition = "VARCHAR(255) NOT NULL")
1483
     */
1484
    private $value;
1485
1486
    /**
1487
     * @return int
1488
     */
1489
    public function getId()
1490
    {
1491
        return $this->id;
1492
    }
1493
1494
    /**
1495
     * @return string
1496
     */
1497
    public function getValue()
1498
    {
1499
        return $this->value;
1500
    }
1501
1502
}
1503
1504
/**
1505
 * @ORM\Entity
1506
 * @ORM\InheritanceType("SINGLE_TABLE")
1507
 * @ORM\DiscriminatorMap({"ONE" = "DDC807SubClasse1", "TWO" = "DDC807SubClasse2"})
1508
 * @ORM\DiscriminatorColumn(name = "dtype", columnDefinition="ENUM('ONE','TWO')")
1509
 */
1510
class DDC807Entity
1511
{
1512
    /**
1513
     * @ORM\Id
1514
     * @ORM\Column(type="integer")
1515
     * @ORM\GeneratedValue(strategy="NONE")
1516
     **/
1517
    public $id;
1518
}
1519
1520
class DDC807SubClasse1 {}
1521
class DDC807SubClasse2 {}
1522
1523
class Address {}
1524
class Phonenumber {}
1525
class Group {}
1526
1527
/**
1528
 * @ORM\Entity
1529
 * @ORM\Table(indexes={@ORM\Index(columns={"content"}, flags={"fulltext"}, options={"where": "content IS NOT NULL"})})
1530
 */
1531
class Comment
1532
{
1533
    /**
1534
     * @ORM\Column(type="text")
1535
     */
1536
    private $content;
1537
}
1538
1539
/**
1540
 * @ORM\Entity
1541
 * @ORM\InheritanceType("SINGLE_TABLE")
1542
 * @ORM\DiscriminatorMap({
1543
 *     "ONE" = "SingleTableEntityNoDiscriminatorColumnMappingSub1",
1544
 *     "TWO" = "SingleTableEntityNoDiscriminatorColumnMappingSub2"
1545
 * })
1546
 */
1547
class SingleTableEntityNoDiscriminatorColumnMapping
1548
{
1549
    /**
1550
     * @ORM\Id
1551
     * @ORM\Column(type="integer")
1552
     * @ORM\GeneratedValue(strategy="NONE")
1553
     */
1554
    public $id;
1555
}
1556
1557
/**
1558
 * @ORM\Entity
1559
 */
1560
class SingleTableEntityNoDiscriminatorColumnMappingSub1 extends SingleTableEntityNoDiscriminatorColumnMapping {}
1561
1562
/**
1563
 * @ORM\Entity
1564
 */
1565
class SingleTableEntityNoDiscriminatorColumnMappingSub2 extends SingleTableEntityNoDiscriminatorColumnMapping {}
1566
1567
/**
1568
 * @ORM\Entity
1569
 * @ORM\InheritanceType("SINGLE_TABLE")
1570
 * @ORM\DiscriminatorMap({
1571
 *     "ONE" = "SingleTableEntityIncompleteDiscriminatorColumnMappingSub1",
1572
 *     "TWO" = "SingleTableEntityIncompleteDiscriminatorColumnMappingSub2"
1573
 * })
1574
 * @ORM\DiscriminatorColumn(name="dtype")
1575
 */
1576
class SingleTableEntityIncompleteDiscriminatorColumnMapping
1577
{
1578
    /**
1579
     * @ORM\Id
1580
     * @ORM\Column(type="integer")
1581
     * @ORM\GeneratedValue(strategy="NONE")
1582
     */
1583
    public $id;
1584
}
1585
1586
class SingleTableEntityIncompleteDiscriminatorColumnMappingSub1
1587
    extends SingleTableEntityIncompleteDiscriminatorColumnMapping {}
0 ignored issues
show
Coding Style introduced by
The extends keyword must be on the same line as the class name
Loading history...
1588
1589
class SingleTableEntityIncompleteDiscriminatorColumnMappingSub2
1590
    extends SingleTableEntityIncompleteDiscriminatorColumnMapping {}
0 ignored issues
show
Coding Style introduced by
The extends keyword must be on the same line as the class name
Loading history...
1591