Completed
Push — 4.4 ( cfe86a...592ab6 )
by Robbie
35:44 queued 28:14
created

DataObjectTest::testValidObjectsForBaseFields()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 2
nop 0
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\ORM\Tests;
4
5
use InvalidArgumentException;
6
use LogicException;
7
use SilverStripe\Core\Config\Config;
8
use SilverStripe\Dev\SapphireTest;
9
use SilverStripe\i18n\i18n;
10
use SilverStripe\ORM\Connect\MySQLDatabase;
11
use SilverStripe\ORM\DataObject;
12
use SilverStripe\ORM\DataObjectSchema;
13
use SilverStripe\ORM\DB;
14
use SilverStripe\ORM\FieldType\DBBoolean;
15
use SilverStripe\ORM\FieldType\DBDatetime;
16
use SilverStripe\ORM\FieldType\DBField;
17
use SilverStripe\ORM\FieldType\DBPolymorphicForeignKey;
18
use SilverStripe\ORM\FieldType\DBVarchar;
19
use SilverStripe\ORM\ManyManyList;
20
use SilverStripe\ORM\Tests\DataObjectTest\Company;
21
use SilverStripe\ORM\Tests\DataObjectTest\Player;
22
use SilverStripe\ORM\Tests\DataObjectTest\TreeNode;
23
use SilverStripe\Security\Member;
24
use SilverStripe\View\ViewableData;
25
use stdClass;
26
27
class DataObjectTest extends SapphireTest
28
{
29
30
    protected static $fixture_file = 'DataObjectTest.yml';
31
32
    /**
33
     * Standard set of dataobject test classes
34
     *
35
     * @var array
36
     */
37
    public static $extra_data_objects = array(
38
        DataObjectTest\Team::class,
39
        DataObjectTest\Fixture::class,
40
        DataObjectTest\SubTeam::class,
41
        DataObjectTest\OtherSubclassWithSameField::class,
42
        DataObjectTest\FieldlessTable::class,
43
        DataObjectTest\FieldlessSubTable::class,
44
        DataObjectTest\ValidatedObject::class,
45
        DataObjectTest\Player::class,
46
        DataObjectTest\TeamComment::class,
47
        DataObjectTest\EquipmentCompany::class,
48
        DataObjectTest\SubEquipmentCompany::class,
49
        DataObjectTest\ExtendedTeamComment::class,
50
        DataObjectTest\Company::class,
51
        DataObjectTest\Staff::class,
52
        DataObjectTest\CEO::class,
53
        DataObjectTest\Fan::class,
54
        DataObjectTest\Play::class,
55
        DataObjectTest\Ploy::class,
56
        DataObjectTest\Bogey::class,
57
        DataObjectTest\Sortable::class,
58
        DataObjectTest\Bracket::class,
59
        DataObjectTest\RelationParent::class,
60
        DataObjectTest\RelationChildFirst::class,
61
        DataObjectTest\RelationChildSecond::class,
62
        DataObjectTest\MockDynamicAssignmentDataObject::class,
63
        DataObjectTest\TreeNode::class,
64
    );
65
66
    protected function setUp()
67
    {
68
        parent::setUp();
69
70
        $validator = Member::password_validator();
71
        if ($validator) {
0 ignored issues
show
introduced by
$validator is of type SilverStripe\Security\PasswordValidator, thus it always evaluated to true.
Loading history...
72
            // Set low default password strength requirements so tests are not interfered with by user code
73
            $validator
74
                ->setMinTestScore(0)
75
                ->setMinLength(6);
76
        }
77
    }
78
79
    public static function getExtraDataObjects()
80
    {
81
        return array_merge(
82
            DataObjectTest::$extra_data_objects,
83
            ManyManyListTest::$extra_data_objects
84
        );
85
    }
86
87
    /**
88
     * @dataProvider provideSingletons
89
     */
90
    public function testSingleton($inst, $defaultValue, $altDefaultValue)
91
    {
92
        $inst = $inst();
93
        // Test that populateDefaults() isn't called on singletons
94
        // which can lead to SQL errors during build, and endless loops
95
        if ($defaultValue) {
96
            $this->assertEquals($defaultValue, $inst->MyFieldWithDefault);
97
        } else {
98
            $this->assertEmpty($inst->MyFieldWithDefault);
99
        }
100
101
        if ($altDefaultValue) {
102
            $this->assertEquals($altDefaultValue, $inst->MyFieldWithAltDefault);
103
        } else {
104
            $this->assertEmpty($inst->MyFieldWithAltDefault);
105
        }
106
    }
107
108
    public function provideSingletons()
109
    {
110
        // because PHPUnit evalutes test providers *before* setUp methods
111
        // any extensions added in the setUp methods won't be available
112
        // we must return closures to generate the arguments at run time
113
        return array(
114
            'create() static method' => array(function () {
115
                return DataObjectTest\Fixture::create();
116
            }, 'Default Value', 'Default Value'),
117
            'New object creation' => array(function () {
118
                return new DataObjectTest\Fixture();
119
            }, 'Default Value', 'Default Value'),
120
            'singleton() function' => array(function () {
121
                return singleton(DataObjectTest\Fixture::class);
122
            }, null, null),
123
            'singleton() static method' => array(function () {
124
                return DataObjectTest\Fixture::singleton();
125
            }, null, null),
126
            'Manual constructor args' => array(function () {
127
                return new DataObjectTest\Fixture(null, true);
128
            }, null, null),
129
        );
130
    }
131
132
    public function testDb()
133
    {
134
        $schema = DataObject::getSchema();
135
        $dbFields = $schema->fieldSpecs(DataObjectTest\TeamComment::class);
136
137
        // Assert fields are included
138
        $this->assertArrayHasKey('Name', $dbFields);
139
140
        // Assert the base fields are included
141
        $this->assertArrayHasKey('Created', $dbFields);
142
        $this->assertArrayHasKey('LastEdited', $dbFields);
143
        $this->assertArrayHasKey('ClassName', $dbFields);
144
        $this->assertArrayHasKey('ID', $dbFields);
145
146
        // Assert that the correct field type is returned when passing a field
147
        $this->assertEquals('Varchar', $schema->fieldSpec(DataObjectTest\TeamComment::class, 'Name'));
148
        $this->assertEquals('Text', $schema->fieldSpec(DataObjectTest\TeamComment::class, 'Comment'));
149
150
        // Test with table required
151
        $this->assertEquals(
152
            DataObjectTest\TeamComment::class . '.Varchar',
153
            $schema->fieldSpec(DataObjectTest\TeamComment::class, 'Name', DataObjectSchema::INCLUDE_CLASS)
154
        );
155
        $this->assertEquals(
156
            DataObjectTest\TeamComment::class . '.Text',
157
            $schema->fieldSpec(DataObjectTest\TeamComment::class, 'Comment', DataObjectSchema::INCLUDE_CLASS)
158
        );
159
        $dbFields = $schema->fieldSpecs(DataObjectTest\ExtendedTeamComment::class);
160
161
        // fixed fields are still included in extended classes
162
        $this->assertArrayHasKey('Created', $dbFields);
163
        $this->assertArrayHasKey('LastEdited', $dbFields);
164
        $this->assertArrayHasKey('ClassName', $dbFields);
165
        $this->assertArrayHasKey('ID', $dbFields);
166
167
        // Assert overloaded fields have correct data type
168
        $this->assertEquals('HTMLText', $schema->fieldSpec(DataObjectTest\ExtendedTeamComment::class, 'Comment'));
169
        $this->assertEquals(
170
            'HTMLText',
171
            $dbFields['Comment'],
172
            'Calls to DataObject::db without a field specified return correct data types'
173
        );
174
175
        // assertEquals doesn't verify the order of array elements, so access keys manually to check order:
176
        // expected: array('Name' => 'Varchar', 'Comment' => 'HTMLText')
177
        $this->assertEquals(
178
            array(
179
                'Name',
180
                'Comment'
181
            ),
182
            array_slice(array_keys($dbFields), 4, 2),
183
            'DataObject::db returns fields in correct order'
184
        );
185
    }
186
187
    public function testConstructAcceptsValues()
188
    {
189
        // Values can be an array...
190
        $player = new DataObjectTest\Player(
191
            array(
192
                'FirstName' => 'James',
193
                'Surname' => 'Smith'
194
            )
195
        );
196
197
        $this->assertEquals('James', $player->FirstName);
198
        $this->assertEquals('Smith', $player->Surname);
199
200
        // ... or a stdClass inst
201
        $data = new stdClass();
202
        $data->FirstName = 'John';
203
        $data->Surname = 'Doe';
204
        $player = new DataObjectTest\Player($data);
0 ignored issues
show
Bug introduced by
$data of type stdClass is incompatible with the type array|null expected by parameter $record of SilverStripe\ORM\Tests\D...t\Player::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

204
        $player = new DataObjectTest\Player(/** @scrutinizer ignore-type */ $data);
Loading history...
205
206
        $this->assertEquals('John', $player->FirstName);
207
        $this->assertEquals('Doe', $player->Surname);
208
209
        // IDs should be stored as integers, not strings
210
        $player = new DataObjectTest\Player(array('ID' => '5'));
211
        $this->assertSame(5, $player->ID);
212
    }
213
214
    public function testValidObjectsForBaseFields()
215
    {
216
        $obj = new DataObjectTest\ValidatedObject();
217
218
        foreach (array('Created', 'LastEdited', 'ClassName', 'ID') as $field) {
219
            $helper = $obj->dbObject($field);
220
            $this->assertTrue(
221
                ($helper instanceof DBField),
222
                "for {$field} expected helper to be DBField, but was " . (is_object($helper) ? get_class($helper) : "null")
223
            );
224
        }
225
    }
226
227
    public function testDataIntegrityWhenTwoSubclassesHaveSameField()
228
    {
229
        // Save data into DataObjectTest_SubTeam.SubclassDatabaseField
230
        $obj = new DataObjectTest\SubTeam();
231
        $obj->SubclassDatabaseField = "obj-SubTeam";
0 ignored issues
show
Bug Best Practice introduced by
The property SubclassDatabaseField does not exist on SilverStripe\ORM\Tests\DataObjectTest\SubTeam. Since you implemented __set, consider adding a @property annotation.
Loading history...
232
        $obj->write();
233
234
        // Change the class
235
        $obj->ClassName = DataObjectTest\OtherSubclassWithSameField::class;
236
        $obj->write();
237
        $obj->flushCache();
238
239
        // Re-fetch from the database and confirm that the data is sourced from
240
        // OtherSubclassWithSameField.SubclassDatabaseField
241
        $obj = DataObject::get_by_id(DataObjectTest\Team::class, $obj->ID);
242
        $this->assertNull($obj->SubclassDatabaseField);
0 ignored issues
show
Bug Best Practice introduced by
The property SubclassDatabaseField does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
243
244
        // Confirm that save the object in the other direction.
245
        $obj->SubclassDatabaseField = 'obj-Other';
0 ignored issues
show
Bug Best Practice introduced by
The property SubclassDatabaseField does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
246
        $obj->write();
247
248
        $obj->ClassName = DataObjectTest\SubTeam::class;
249
        $obj->write();
250
        $obj->flushCache();
251
252
        // If we restore the class, the old value has been lying dormant and will be available again.
253
        // NOTE: This behaviour is volatile; we may change this in the future to clear fields that
254
        // are no longer relevant when changing ClassName
255
        $obj = DataObject::get_by_id(DataObjectTest\Team::class, $obj->ID);
256
        $this->assertEquals('obj-SubTeam', $obj->SubclassDatabaseField);
257
    }
258
259
    /**
260
     * Test deletion of DataObjects
261
     *   - Deleting using delete() on the DataObject
262
     *   - Deleting using DataObject::delete_by_id()
263
     */
264
    public function testDelete()
265
    {
266
        // Test deleting using delete() on the DataObject
267
        // Get the first page
268
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
269
        $objID = $obj->ID;
270
        // Check the page exists before deleting
271
        $this->assertTrue(is_object($obj) && $obj->exists());
272
        // Delete the page
273
        $obj->delete();
274
        // Check that page does not exist after deleting
275
        $obj = DataObject::get_by_id(DataObjectTest\Player::class, $objID);
276
        $this->assertTrue(!$obj || !$obj->exists());
277
278
279
        // Test deleting using DataObject::delete_by_id()
280
        // Get the second page
281
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain2');
282
        $objID = $obj->ID;
283
        // Check the page exists before deleting
284
        $this->assertTrue(is_object($obj) && $obj->exists());
285
        // Delete the page
286
        DataObject::delete_by_id(DataObjectTest\Player::class, $obj->ID);
287
        // Check that page does not exist after deleting
288
        $obj = DataObject::get_by_id(DataObjectTest\Player::class, $objID);
289
        $this->assertTrue(!$obj || !$obj->exists());
290
    }
291
292
    /**
293
     * Test methods that get DataObjects
294
     *   - DataObject::get()
295
     *       - All records of a DataObject
296
     *       - Filtering
297
     *       - Sorting
298
     *       - Joins
299
     *       - Limit
300
     *       - Container class
301
     *   - DataObject::get_by_id()
302
     *   - DataObject::get_one()
303
     *        - With and without caching
304
     *        - With and without ordering
305
     */
306
    public function testGet()
307
    {
308
        // Test getting all records of a DataObject
309
        $comments = DataObject::get(DataObjectTest\TeamComment::class);
310
        $this->assertEquals(3, $comments->count());
311
312
        // Test WHERE clause
313
        $comments = DataObject::get(DataObjectTest\TeamComment::class, "\"Name\"='Bob'");
314
        $this->assertEquals(1, $comments->count());
315
        foreach ($comments as $comment) {
316
            $this->assertEquals('Bob', $comment->Name);
317
        }
318
319
        // Test sorting
320
        $comments = DataObject::get(DataObjectTest\TeamComment::class, '', "\"Name\" ASC");
321
        $this->assertEquals(3, $comments->count());
322
        $this->assertEquals('Bob', $comments->first()->Name);
0 ignored issues
show
Bug Best Practice introduced by
The property Name does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
323
        $comments = DataObject::get(DataObjectTest\TeamComment::class, '', "\"Name\" DESC");
324
        $this->assertEquals(3, $comments->count());
325
        $this->assertEquals('Phil', $comments->first()->Name);
326
327
        // Test limit
328
        $comments = DataObject::get(DataObjectTest\TeamComment::class, '', "\"Name\" ASC", '', '1,2');
329
        $this->assertEquals(2, $comments->count());
330
        $this->assertEquals('Joe', $comments->first()->Name);
331
        $this->assertEquals('Phil', $comments->last()->Name);
332
333
        // Test get_by_id()
334
        $captain1ID = $this->idFromFixture(DataObjectTest\Player::class, 'captain1');
335
        $captain1 = DataObject::get_by_id(DataObjectTest\Player::class, $captain1ID);
336
        $this->assertEquals('Captain', $captain1->FirstName);
0 ignored issues
show
Bug Best Practice introduced by
The property FirstName does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
337
338
        // Test get_one() without caching
339
        $comment1 = DataObject::get_one(
340
            DataObjectTest\TeamComment::class,
341
            array(
342
                '"DataObjectTest_TeamComment"."Name"' => 'Joe'
343
            ),
344
            false
345
        );
346
        $comment1->Comment = "Something Else";
0 ignored issues
show
Bug Best Practice introduced by
The property Comment does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
347
348
        $comment2 = DataObject::get_one(
349
            DataObjectTest\TeamComment::class,
350
            array(
351
                '"DataObjectTest_TeamComment"."Name"' => 'Joe'
352
            ),
353
            false
354
        );
355
        $this->assertNotEquals($comment1->Comment, $comment2->Comment);
0 ignored issues
show
Bug Best Practice introduced by
The property Comment does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
356
357
        // Test get_one() with caching
358
        $comment1 = DataObject::get_one(
359
            DataObjectTest\TeamComment::class,
360
            array(
361
                '"DataObjectTest_TeamComment"."Name"' => 'Bob'
362
            ),
363
            true
364
        );
365
        $comment1->Comment = "Something Else";
366
367
        $comment2 = DataObject::get_one(
368
            DataObjectTest\TeamComment::class,
369
            array(
370
                '"DataObjectTest_TeamComment"."Name"' => 'Bob'
371
            ),
372
            true
373
        );
374
        $this->assertEquals((string)$comment1->Comment, (string)$comment2->Comment);
375
376
        // Test get_one() with order by without caching
377
        $comment = DataObject::get_one(DataObjectTest\TeamComment::class, '', false, "\"Name\" ASC");
378
        $this->assertEquals('Bob', $comment->Name);
379
380
        $comment = DataObject::get_one(DataObjectTest\TeamComment::class, '', false, "\"Name\" DESC");
381
        $this->assertEquals('Phil', $comment->Name);
382
383
        // Test get_one() with order by with caching
384
        $comment = DataObject::get_one(DataObjectTest\TeamComment::class, '', true, '"Name" ASC');
385
        $this->assertEquals('Bob', $comment->Name);
386
        $comment = DataObject::get_one(DataObjectTest\TeamComment::class, '', true, '"Name" DESC');
387
        $this->assertEquals('Phil', $comment->Name);
388
    }
389
390
    public function testGetByIDCallerClass()
391
    {
392
        $captain1ID = $this->idFromFixture(DataObjectTest\Player::class, 'captain1');
393
        $captain1 = DataObjectTest\Player::get_by_id($captain1ID);
394
        $this->assertInstanceOf(DataObjectTest\Player::class, $captain1);
395
        $this->assertEquals('Captain', $captain1->FirstName);
396
397
        $captain2ID = $this->idFromFixture(DataObjectTest\Player::class, 'captain2');
398
        // make sure we can call from any class but get the one passed as an argument
399
        $captain2 = DataObjectTest\TeamComment::get_by_id(DataObjectTest\Player::class, $captain2ID);
400
        $this->assertInstanceOf(DataObjectTest\Player::class, $captain2);
401
        $this->assertEquals('Captain 2', $captain2->FirstName);
0 ignored issues
show
Bug Best Practice introduced by
The property FirstName does not exist on SilverStripe\ORM\Tests\DataObjectTest\TeamComment. Since you implemented __get, consider adding a @property annotation.
Loading history...
402
    }
403
404
    public function testGetCaseInsensitive()
405
    {
406
        // Test get_one() with bad case on the classname
407
        // Note: This will succeed only if the underlying DB server supports case-insensitive
408
        // table names (e.g. such as MySQL, but not SQLite3)
409
        if (!(DB::get_conn() instanceof MySQLDatabase)) {
410
            $this->markTestSkipped('MySQL only');
411
        }
412
413
        $subteam1 = DataObject::get_one(
414
            strtolower(DataObjectTest\SubTeam::class),
415
            array(
416
                '"DataObjectTest_Team"."Title"' => 'Subteam 1'
417
            ),
418
            true
419
        );
420
        $this->assertNotEmpty($subteam1);
421
        $this->assertEquals($subteam1->Title, "Subteam 1");
422
    }
423
424
    public function testGetSubclassFields()
425
    {
426
        /* Test that fields / has_one relations from the parent table and the subclass tables are extracted */
427
        $captain1 = $this->objFromFixture(DataObjectTest\Player::class, "captain1");
428
        // Base field
429
        $this->assertEquals('Captain', $captain1->FirstName);
0 ignored issues
show
Bug Best Practice introduced by
The property FirstName does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
430
        // Subclass field
431
        $this->assertEquals('007', $captain1->ShirtNumber);
0 ignored issues
show
Bug Best Practice introduced by
The property ShirtNumber does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
432
        // Subclass has_one relation
433
        $this->assertEquals($this->idFromFixture(DataObjectTest\Team::class, 'team1'), $captain1->FavouriteTeamID);
0 ignored issues
show
Bug Best Practice introduced by
The property FavouriteTeamID does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
434
    }
435
436
    public function testGetRelationClass()
437
    {
438
        $obj = new DataObjectTest\Player();
0 ignored issues
show
Unused Code introduced by
The assignment to $obj is dead and can be removed.
Loading history...
439
        $this->assertEquals(
440
            singleton(DataObjectTest\Player::class)->getRelationClass('FavouriteTeam'),
441
            DataObjectTest\Team::class,
442
            'has_one is properly inspected'
443
        );
444
        $this->assertEquals(
445
            singleton(DataObjectTest\Company::class)->getRelationClass('CurrentStaff'),
446
            DataObjectTest\Staff::class,
447
            'has_many is properly inspected'
448
        );
449
        $this->assertEquals(
450
            singleton(DataObjectTest\Team::class)->getRelationClass('Players'),
451
            DataObjectTest\Player::class,
452
            'many_many is properly inspected'
453
        );
454
        $this->assertEquals(
455
            singleton(DataObjectTest\Player::class)->getRelationClass('Teams'),
456
            DataObjectTest\Team::class,
457
            'belongs_many_many is properly inspected'
458
        );
459
        $this->assertEquals(
460
            singleton(DataObjectTest\CEO::class)->getRelationClass('Company'),
461
            DataObjectTest\Company::class,
462
            'belongs_to is properly inspected'
463
        );
464
        $this->assertEquals(
465
            singleton(DataObjectTest\Fan::class)->getRelationClass('Favourite'),
466
            DataObject::class,
467
            'polymorphic has_one is properly inspected'
468
        );
469
    }
470
471
    /**
472
     * Test that has_one relations can be retrieved
473
     */
474
    public function testGetHasOneRelations()
475
    {
476
        $captain1 = $this->objFromFixture(DataObjectTest\Player::class, "captain1");
477
        $team1ID = $this->idFromFixture(DataObjectTest\Team::class, 'team1');
478
479
        // There will be a field called (relname)ID that contains the ID of the
480
        // object linked to via the has_one relation
481
        $this->assertEquals($team1ID, $captain1->FavouriteTeamID);
0 ignored issues
show
Bug Best Practice introduced by
The property FavouriteTeamID does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
482
483
        // There will be a method called $obj->relname() that returns the object itself
484
        $this->assertEquals($team1ID, $captain1->FavouriteTeam()->ID);
0 ignored issues
show
Bug introduced by
The method FavouriteTeam() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

484
        $this->assertEquals($team1ID, $captain1->/** @scrutinizer ignore-call */ FavouriteTeam()->ID);
Loading history...
485
486
        // Test that getNonReciprocalComponent can find has_one from the has_many end
487
        $this->assertEquals(
488
            $team1ID,
489
            $captain1->inferReciprocalComponent(DataObjectTest\Team::class, 'PlayerFans')->ID
0 ignored issues
show
Bug Best Practice introduced by
The property ID does not exist on SilverStripe\ORM\DataList. Since you implemented __get, consider adding a @property annotation.
Loading history...
490
        );
491
492
        // Check entity with polymorphic has-one
493
        $fan1 = $this->objFromFixture(DataObjectTest\Fan::class, "fan1");
494
        $this->assertTrue((bool)$fan1->hasValue('Favourite'));
495
496
        // There will be fields named (relname)ID and (relname)Class for polymorphic
497
        // entities
498
        $this->assertEquals($team1ID, $fan1->FavouriteID);
0 ignored issues
show
Bug Best Practice introduced by
The property FavouriteID does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
499
        $this->assertEquals(DataObjectTest\Team::class, $fan1->FavouriteClass);
0 ignored issues
show
Bug Best Practice introduced by
The property FavouriteClass does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
500
501
        // There will be a method called $obj->relname() that returns the object itself
502
        $favourite = $fan1->Favourite();
0 ignored issues
show
Bug introduced by
The method Favourite() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

502
        /** @scrutinizer ignore-call */ 
503
        $favourite = $fan1->Favourite();
Loading history...
503
        $this->assertEquals($team1ID, $favourite->ID);
504
        $this->assertInstanceOf(DataObjectTest\Team::class, $favourite);
505
506
        // check behaviour of dbObject with polymorphic relations
507
        $favouriteDBObject = $fan1->dbObject('Favourite');
508
        $favouriteValue = $favouriteDBObject->getValue();
509
        $this->assertInstanceOf(DBPolymorphicForeignKey::class, $favouriteDBObject);
510
        $this->assertEquals($favourite->ID, $favouriteValue->ID);
511
        $this->assertEquals($favourite->ClassName, $favouriteValue->ClassName);
512
    }
513
514
    public function testLimitAndCount()
515
    {
516
        $players = DataObject::get(DataObjectTest\Player::class);
517
518
        // There's 4 records in total
519
        $this->assertEquals(4, $players->count());
520
521
        // Testing "##, ##" syntax
522
        $this->assertEquals(4, $players->limit(20)->count());
523
        $this->assertEquals(4, $players->limit(20, 0)->count());
524
        $this->assertEquals(0, $players->limit(20, 20)->count());
525
        $this->assertEquals(2, $players->limit(2, 0)->count());
526
        $this->assertEquals(1, $players->limit(5, 3)->count());
527
    }
528
529
    public function testWriteNoChangesDoesntUpdateLastEdited()
530
    {
531
        // set mock now so we can be certain of LastEdited time for our test
532
        DBDatetime::set_mock_now('2017-01-01 00:00:00');
533
        $obj = new Player();
534
        $obj->FirstName = 'Test';
535
        $obj->Surname = 'Plater';
536
        $obj->Email = '[email protected]';
537
        $obj->write();
538
        $this->assertEquals('2017-01-01 00:00:00', $obj->LastEdited);
539
        $writtenObj = Player::get()->byID($obj->ID);
540
        $this->assertEquals('2017-01-01 00:00:00', $writtenObj->LastEdited);
541
542
        // set mock now so we get a new LastEdited if, for some reason, it's updated
543
        DBDatetime::set_mock_now('2017-02-01 00:00:00');
544
        $writtenObj->write();
545
        $this->assertEquals('2017-01-01 00:00:00', $writtenObj->LastEdited);
546
        $this->assertEquals($obj->ID, $writtenObj->ID);
547
548
        $reWrittenObj = Player::get()->byID($writtenObj->ID);
549
        $this->assertEquals('2017-01-01 00:00:00', $reWrittenObj->LastEdited);
550
    }
551
552
    /**
553
     * Test writing of database columns which don't correlate to a DBField,
554
     * e.g. all relation fields on has_one/has_many like "ParentID".
555
     */
556
    public function testWritePropertyWithoutDBField()
557
    {
558
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
559
        $obj->FavouriteTeamID = 99;
0 ignored issues
show
Bug Best Practice introduced by
The property FavouriteTeamID does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
560
        $obj->write();
561
562
        // reload the page from the database
563
        $savedObj = DataObject::get_by_id(DataObjectTest\Player::class, $obj->ID);
564
        $this->assertTrue($savedObj->FavouriteTeamID == 99);
0 ignored issues
show
Bug Best Practice introduced by
The property FavouriteTeamID does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
565
566
        // Test with porymorphic relation
567
        $obj2 = $this->objFromFixture(DataObjectTest\Fan::class, "fan1");
568
        $obj2->FavouriteID = 99;
0 ignored issues
show
Bug Best Practice introduced by
The property FavouriteID does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
569
        $obj2->FavouriteClass = DataObjectTest\Player::class;
0 ignored issues
show
Bug Best Practice introduced by
The property FavouriteClass does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
570
        $obj2->write();
571
572
        $savedObj2 = DataObject::get_by_id(DataObjectTest\Fan::class, $obj2->ID);
573
        $this->assertTrue($savedObj2->FavouriteID == 99);
0 ignored issues
show
Bug Best Practice introduced by
The property FavouriteID does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
574
        $this->assertTrue($savedObj2->FavouriteClass == DataObjectTest\Player::class);
0 ignored issues
show
Bug Best Practice introduced by
The property FavouriteClass does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
575
    }
576
577
    /**
578
     * Test has many relationships
579
     *   - Test getComponents() gets the ComponentSet of the other side of the relation
580
     *   - Test the IDs on the DataObjects are set correctly
581
     */
582
    public function testHasManyRelationships()
583
    {
584
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
585
586
        // Test getComponents() gets the ComponentSet of the other side of the relation
587
        $this->assertTrue($team1->Comments()->count() == 2);
0 ignored issues
show
Bug introduced by
The method Comments() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

587
        $this->assertTrue($team1->/** @scrutinizer ignore-call */ Comments()->count() == 2);
Loading history...
588
589
        $team1Comments = [
590
            ['Comment' => 'This is a team comment by Joe'],
591
            ['Comment' => 'This is a team comment by Bob'],
592
        ];
593
594
        // Test the IDs on the DataObjects are set correctly
595
        $this->assertListEquals($team1Comments, $team1->Comments());
596
597
        // Test that has_many can be infered from the has_one via getNonReciprocalComponent
598
        $this->assertListEquals(
599
            $team1Comments,
600
            $team1->inferReciprocalComponent(DataObjectTest\TeamComment::class, 'Team')
0 ignored issues
show
Bug introduced by
It seems like $team1->inferReciprocalC...Comment::class, 'Team') can also be of type SilverStripe\ORM\DataObject; however, parameter $list of SilverStripe\Dev\SapphireTest::assertListEquals() does only seem to accept SilverStripe\ORM\SS_List, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

600
            /** @scrutinizer ignore-type */ $team1->inferReciprocalComponent(DataObjectTest\TeamComment::class, 'Team')
Loading history...
601
        );
602
603
        // Test that we can add and remove items that already exist in the database
604
        $newComment = new DataObjectTest\TeamComment();
605
        $newComment->Name = "Automated commenter";
0 ignored issues
show
Bug Best Practice introduced by
The property Name does not exist on SilverStripe\ORM\Tests\DataObjectTest\TeamComment. Since you implemented __set, consider adding a @property annotation.
Loading history...
606
        $newComment->Comment = "This is a new comment";
0 ignored issues
show
Bug Best Practice introduced by
The property Comment does not exist on SilverStripe\ORM\Tests\DataObjectTest\TeamComment. Since you implemented __set, consider adding a @property annotation.
Loading history...
607
        $newComment->write();
608
        $team1->Comments()->add($newComment);
609
        $this->assertEquals($team1->ID, $newComment->TeamID);
0 ignored issues
show
Bug Best Practice introduced by
The property TeamID does not exist on SilverStripe\ORM\Tests\DataObjectTest\TeamComment. Since you implemented __get, consider adding a @property annotation.
Loading history...
610
611
        $comment1 = $this->objFromFixture(DataObjectTest\TeamComment::class, 'comment1');
612
        $comment2 = $this->objFromFixture(DataObjectTest\TeamComment::class, 'comment2');
613
        $team1->Comments()->remove($comment2);
614
615
        $team1CommentIDs = $team1->Comments()->sort('ID')->column('ID');
0 ignored issues
show
Bug introduced by
The method sort() does not exist on SilverStripe\ORM\SS_List. It seems like you code against a sub-type of said class. However, the method does not exist in SilverStripe\ORM\Filterable or SilverStripe\ORM\Limitable. Are you sure you never get one of those? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

615
        $team1CommentIDs = $team1->Comments()->/** @scrutinizer ignore-call */ sort('ID')->column('ID');
Loading history...
616
        $this->assertEquals(array($comment1->ID, $newComment->ID), $team1CommentIDs);
617
618
        // Test that removing an item from a list doesn't remove it from the same
619
        // relation belonging to a different object
620
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
621
        $team2 = $this->objFromFixture(DataObjectTest\Team::class, 'team2');
622
        $team2->Comments()->remove($comment1);
623
        $team1CommentIDs = $team1->Comments()->sort('ID')->column('ID');
624
        $this->assertEquals(array($comment1->ID, $newComment->ID), $team1CommentIDs);
625
    }
626
627
628
    /**
629
     * Test has many relationships against polymorphic has_one fields
630
     *   - Test getComponents() gets the ComponentSet of the other side of the relation
631
     *   - Test the IDs on the DataObjects are set correctly
632
     */
633
    public function testHasManyPolymorphicRelationships()
634
    {
635
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
636
637
        // Test getComponents() gets the ComponentSet of the other side of the relation
638
        $this->assertTrue($team1->Fans()->count() == 2);
0 ignored issues
show
Bug introduced by
The method Fans() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

638
        $this->assertTrue($team1->/** @scrutinizer ignore-call */ Fans()->count() == 2);
Loading history...
639
640
        // Test the IDs/Classes on the DataObjects are set correctly
641
        foreach ($team1->Fans() as $fan) {
642
            $this->assertEquals($team1->ID, $fan->FavouriteID, 'Fan has the correct FavouriteID');
643
            $this->assertEquals(DataObjectTest\Team::class, $fan->FavouriteClass, 'Fan has the correct FavouriteClass');
644
        }
645
646
        // Test that we can add and remove items that already exist in the database
647
        $newFan = new DataObjectTest\Fan();
648
        $newFan->Name = "New fan";
0 ignored issues
show
Bug Best Practice introduced by
The property Name does not exist on SilverStripe\ORM\Tests\DataObjectTest\Fan. Since you implemented __set, consider adding a @property annotation.
Loading history...
649
        $newFan->write();
650
        $team1->Fans()->add($newFan);
651
        $this->assertEquals($team1->ID, $newFan->FavouriteID, 'Newly created fan has the correct FavouriteID');
0 ignored issues
show
Bug Best Practice introduced by
The property FavouriteID does not exist on SilverStripe\ORM\Tests\DataObjectTest\Fan. Since you implemented __get, consider adding a @property annotation.
Loading history...
652
        $this->assertEquals(
653
            DataObjectTest\Team::class,
654
            $newFan->FavouriteClass,
0 ignored issues
show
Bug Best Practice introduced by
The property FavouriteClass does not exist on SilverStripe\ORM\Tests\DataObjectTest\Fan. Since you implemented __get, consider adding a @property annotation.
Loading history...
655
            'Newly created fan has the correct FavouriteClass'
656
        );
657
658
        $fan1 = $this->objFromFixture(DataObjectTest\Fan::class, 'fan1');
659
        $fan3 = $this->objFromFixture(DataObjectTest\Fan::class, 'fan3');
660
        $team1->Fans()->remove($fan3);
661
662
        $team1FanIDs = $team1->Fans()->sort('ID')->column('ID');
663
        $this->assertEquals(array($fan1->ID, $newFan->ID), $team1FanIDs);
664
665
        // Test that removing an item from a list doesn't remove it from the same
666
        // relation belonging to a different object
667
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
668
        $player1 = $this->objFromFixture(DataObjectTest\Player::class, 'player1');
669
        $player1->Fans()->remove($fan1);
670
        $team1FanIDs = $team1->Fans()->sort('ID')->column('ID');
671
        $this->assertEquals(array($fan1->ID, $newFan->ID), $team1FanIDs);
672
    }
673
674
675
    public function testHasOneRelationship()
676
    {
677
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
678
        $player1 = $this->objFromFixture(DataObjectTest\Player::class, 'player1');
679
        $player2 = $this->objFromFixture(DataObjectTest\Player::class, 'player2');
680
        $fan1 = $this->objFromFixture(DataObjectTest\Fan::class, 'fan1');
681
682
        // Test relation probing
683
        $this->assertFalse((bool)$team1->hasValue('Captain', null, false));
684
        $this->assertFalse((bool)$team1->hasValue('CaptainID', null, false));
685
686
        // Add a captain to team 1
687
        $team1->setField('CaptainID', $player1->ID);
688
        $team1->write();
689
690
        $this->assertTrue((bool)$team1->hasValue('Captain', null, false));
691
        $this->assertTrue((bool)$team1->hasValue('CaptainID', null, false));
692
693
        $this->assertEquals(
694
            $player1->ID,
695
            $team1->Captain()->ID,
0 ignored issues
show
Bug introduced by
The method Captain() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

695
            $team1->/** @scrutinizer ignore-call */ 
696
                    Captain()->ID,
Loading history...
696
            'The captain exists for team 1'
697
        );
698
        $this->assertEquals(
699
            $player1->ID,
700
            $team1->getComponent('Captain')->ID,
701
            'The captain exists through the component getter'
702
        );
703
704
        $this->assertEquals(
705
            $team1->Captain()->FirstName,
706
            'Player 1',
707
            'Player 1 is the captain'
708
        );
709
        $this->assertEquals(
710
            $team1->getComponent('Captain')->FirstName,
711
            'Player 1',
712
            'Player 1 is the captain'
713
        );
714
715
        $team1->CaptainID = $player2->ID;
0 ignored issues
show
Bug Best Practice introduced by
The property CaptainID does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
716
        $team1->write();
717
718
        $this->assertEquals($player2->ID, $team1->Captain()->ID);
719
        $this->assertEquals($player2->ID, $team1->getComponent('Captain')->ID);
720
        $this->assertEquals('Player 2', $team1->Captain()->FirstName);
721
        $this->assertEquals('Player 2', $team1->getComponent('Captain')->FirstName);
722
723
724
        // Set the favourite team for fan1
725
        $fan1->setField('FavouriteID', $team1->ID);
726
        $fan1->setField('FavouriteClass', get_class($team1));
727
728
        $this->assertEquals($team1->ID, $fan1->Favourite()->ID, 'The team is assigned to fan 1');
729
        $this->assertInstanceOf(get_class($team1), $fan1->Favourite(), 'The team is assigned to fan 1');
730
        $this->assertEquals(
731
            $team1->ID,
732
            $fan1->getComponent('Favourite')->ID,
733
            'The team exists through the component getter'
734
        );
735
        $this->assertInstanceOf(
736
            get_class($team1),
737
            $fan1->getComponent('Favourite'),
738
            'The team exists through the component getter'
739
        );
740
741
        $this->assertEquals(
742
            $fan1->Favourite()->Title,
743
            'Team 1',
744
            'Team 1 is the favourite'
745
        );
746
        $this->assertEquals(
747
            $fan1->getComponent('Favourite')->Title,
748
            'Team 1',
749
            'Team 1 is the favourite'
750
        );
751
    }
752
753
    /**
754
     * Test has_one used as field getter/setter
755
     */
756
    public function testHasOneAsField()
757
    {
758
        /** @var DataObjectTest\Team $team1 */
759
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
760
        $captain1 = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
761
        $captain2 = $this->objFromFixture(DataObjectTest\Player::class, 'captain2');
762
763
        // Setter: By RelationID
764
        $team1->CaptainID = $captain1->ID;
0 ignored issues
show
Bug Best Practice introduced by
The property CaptainID does not exist on SilverStripe\ORM\Tests\DataObjectTest\Team. Since you implemented __set, consider adding a @property annotation.
Loading history...
765
        $team1->write();
766
        $this->assertEquals($captain1->ID, $team1->Captain->ID);
0 ignored issues
show
Bug Best Practice introduced by
The property Captain does not exist on SilverStripe\ORM\Tests\DataObjectTest\Team. Since you implemented __get, consider adding a @property annotation.
Loading history...
767
768
        // Setter: New object
769
        $team1->Captain = $captain2;
0 ignored issues
show
Bug Best Practice introduced by
The property Captain does not exist on SilverStripe\ORM\Tests\DataObjectTest\Team. Since you implemented __set, consider adding a @property annotation.
Loading history...
770
        $team1->write();
771
        $this->assertEquals($captain2->ID, $team1->Captain->ID);
772
773
        // Setter: Custom data (required by DataDifferencer)
774
        $team1->Captain = DBField::create_field('HTMLFragment', '<p>No captain</p>');
775
        $this->assertEquals('<p>No captain</p>', $team1->Captain);
776
    }
777
778
    /**
779
     * @todo Extend type change tests (e.g. '0'==NULL)
780
     */
781
    public function testChangedFields()
782
    {
783
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
784
        $obj->FirstName = 'Captain-changed';
0 ignored issues
show
Bug Best Practice introduced by
The property FirstName does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
785
        $obj->IsRetired = true;
0 ignored issues
show
Bug Best Practice introduced by
The property IsRetired does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
786
787
        $this->assertEquals(
788
            $obj->getChangedFields(true, DataObject::CHANGE_STRICT),
789
            array(
790
                'FirstName' => array(
791
                    'before' => 'Captain',
792
                    'after' => 'Captain-changed',
793
                    'level' => DataObject::CHANGE_VALUE
794
                ),
795
                'IsRetired' => array(
796
                    'before' => 1,
797
                    'after' => true,
798
                    'level' => DataObject::CHANGE_STRICT
799
                )
800
            ),
801
            'Changed fields are correctly detected with strict type changes (level=1)'
802
        );
803
804
        $this->assertEquals(
805
            $obj->getChangedFields(true, DataObject::CHANGE_VALUE),
806
            array(
807
                'FirstName' => array(
808
                    'before' => 'Captain',
809
                    'after' => 'Captain-changed',
810
                    'level' => DataObject::CHANGE_VALUE
811
                )
812
            ),
813
            'Changed fields are correctly detected while ignoring type changes (level=2)'
814
        );
815
816
        $newObj = new DataObjectTest\Player();
817
        $newObj->FirstName = "New Player";
818
        $this->assertEquals(
819
            array(
820
                'FirstName' => array(
821
                    'before' => null,
822
                    'after' => 'New Player',
823
                    'level' => DataObject::CHANGE_VALUE
824
                )
825
            ),
826
            $newObj->getChangedFields(true, DataObject::CHANGE_VALUE),
827
            'Initialised fields are correctly detected as full changes'
828
        );
829
    }
830
831
    public function testChangedFieldsWhenRestoringData()
832
    {
833
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
834
        $obj->FirstName = 'Captain-changed';
0 ignored issues
show
Bug Best Practice introduced by
The property FirstName does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
835
        $obj->FirstName = 'Captain';
836
837
        $this->assertEquals(
838
            [],
839
            $obj->getChangedFields(true, DataObject::CHANGE_STRICT)
840
        );
841
    }
842
843
    public function testChangedFieldsAfterWrite()
844
    {
845
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
846
        $obj->FirstName = 'Captain-changed';
0 ignored issues
show
Bug Best Practice introduced by
The property FirstName does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
847
        $obj->write();
848
        $obj->FirstName = 'Captain';
849
850
        $this->assertEquals(
851
            array(
852
                'FirstName' => array(
853
                    'before' => 'Captain-changed',
854
                    'after' => 'Captain',
855
                    'level' => DataObject::CHANGE_VALUE,
856
                ),
857
            ),
858
            $obj->getChangedFields(true, DataObject::CHANGE_VALUE)
859
        );
860
    }
861
862
    public function testForceChangeCantBeCancelledUntilWrite()
863
    {
864
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
865
        $this->assertFalse($obj->isChanged('FirstName'));
866
        $this->assertFalse($obj->isChanged('Surname'));
867
868
        // Force change marks the records as changed
869
        $obj->forceChange();
870
        $this->assertTrue($obj->isChanged('FirstName'));
871
        $this->assertTrue($obj->isChanged('Surname'));
872
873
        // ...but not if we explicitly ask if the value has changed
874
        $this->assertFalse($obj->isChanged('FirstName', DataObject::CHANGE_VALUE));
875
        $this->assertFalse($obj->isChanged('Surname', DataObject::CHANGE_VALUE));
876
877
        // Not overwritten by setting the value to is original value
878
        $obj->FirstName = 'Captain';
0 ignored issues
show
Bug Best Practice introduced by
The property FirstName does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
879
        $this->assertTrue($obj->isChanged('FirstName'));
880
        $this->assertTrue($obj->isChanged('Surname'));
881
882
        // Not overwritten by changing it to something else and back again
883
        $obj->FirstName = 'Captain-changed';
884
        $this->assertTrue($obj->isChanged('FirstName', DataObject::CHANGE_VALUE));
885
886
        $obj->FirstName = 'Captain';
887
        $this->assertFalse($obj->isChanged('FirstName', DataObject::CHANGE_VALUE));
888
        $this->assertTrue($obj->isChanged('FirstName'));
889
        $this->assertTrue($obj->isChanged('Surname'));
890
891
        // Cleared after write
892
        $obj->write();
893
        $this->assertFalse($obj->isChanged('FirstName'));
894
        $this->assertFalse($obj->isChanged('Surname'));
895
896
        $obj->FirstName = 'Captain';
897
        $this->assertFalse($obj->isChanged('FirstName'));
898
    }
899
900
    /**
901
     * @skipUpgrade
902
     */
903
    public function testIsChanged()
904
    {
905
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
906
        $obj->NonDBField = 'bob';
0 ignored issues
show
Bug Best Practice introduced by
The property NonDBField does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
907
        $obj->FirstName = 'Captain-changed';
0 ignored issues
show
Bug Best Practice introduced by
The property FirstName does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
908
        $obj->IsRetired = true; // type change only, database stores "1"
0 ignored issues
show
Bug Best Practice introduced by
The property IsRetired does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
909
910
        // Now that DB fields are changed, isChanged is true
911
        $this->assertTrue($obj->isChanged('NonDBField'));
912
        $this->assertFalse($obj->isChanged('NonField'));
913
        $this->assertTrue($obj->isChanged('FirstName', DataObject::CHANGE_STRICT));
914
        $this->assertTrue($obj->isChanged('FirstName', DataObject::CHANGE_VALUE));
915
        $this->assertTrue($obj->isChanged('IsRetired', DataObject::CHANGE_STRICT));
916
        $this->assertFalse($obj->isChanged('IsRetired', DataObject::CHANGE_VALUE));
917
        $this->assertFalse($obj->isChanged('Email', 1), 'Doesnt change mark unchanged property');
918
        $this->assertFalse($obj->isChanged('Email', 2), 'Doesnt change mark unchanged property');
919
920
        $newObj = new DataObjectTest\Player();
921
        $newObj->FirstName = "New Player";
922
        $this->assertTrue($newObj->isChanged('FirstName', DataObject::CHANGE_STRICT));
923
        $this->assertTrue($newObj->isChanged('FirstName', DataObject::CHANGE_VALUE));
924
        $this->assertFalse($newObj->isChanged('Email', DataObject::CHANGE_STRICT));
925
        $this->assertFalse($newObj->isChanged('Email', DataObject::CHANGE_VALUE));
926
927
        $newObj->write();
928
        $this->assertFalse($newObj->ischanged());
929
        $this->assertFalse($newObj->isChanged('FirstName', DataObject::CHANGE_STRICT));
930
        $this->assertFalse($newObj->isChanged('FirstName', DataObject::CHANGE_VALUE));
931
        $this->assertFalse($newObj->isChanged('Email', DataObject::CHANGE_STRICT));
932
        $this->assertFalse($newObj->isChanged('Email', DataObject::CHANGE_VALUE));
933
934
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
935
        $obj->FirstName = null;
936
        $this->assertTrue($obj->isChanged('FirstName', DataObject::CHANGE_STRICT));
937
        $this->assertTrue($obj->isChanged('FirstName', DataObject::CHANGE_VALUE));
938
939
        $obj->write();
940
        $obj->FirstName = null;
941
        $this->assertFalse($obj->isChanged('FirstName', DataObject::CHANGE_STRICT), 'Unchanged property was marked as changed');
942
        $obj->FirstName = 0;
943
        $this->assertTrue($obj->isChanged('FirstName', DataObject::CHANGE_STRICT), 'Strict (type) change was not detected');
944
        $this->assertFalse($obj->isChanged('FirstName', DataObject::CHANGE_VALUE), 'Type-only change was marked as a value change');
945
946
        /* Test when there's not field provided */
947
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain2');
948
        $this->assertFalse($obj->isChanged());
949
        $obj->NonDBField = 'new value';
950
        $this->assertFalse($obj->isChanged());
951
        $obj->FirstName = "New Player";
952
        $this->assertTrue($obj->isChanged());
953
954
        $obj->write();
955
        $this->assertFalse($obj->isChanged());
956
    }
957
958
    public function testRandomSort()
959
    {
960
        /* If we perform the same regularly sorted query twice, it should return the same results */
961
        $itemsA = DataObject::get(DataObjectTest\TeamComment::class, "", "ID");
962
        foreach ($itemsA as $item) {
963
            $keysA[] = $item->ID;
964
        }
965
966
        $itemsB = DataObject::get(DataObjectTest\TeamComment::class, "", "ID");
967
        foreach ($itemsB as $item) {
968
            $keysB[] = $item->ID;
969
        }
970
971
        /* Test when there's not field provided */
972
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
973
        $obj->FirstName = "New Player";
0 ignored issues
show
Bug Best Practice introduced by
The property FirstName does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
974
        $this->assertTrue($obj->isChanged());
975
976
        $obj->write();
977
        $this->assertFalse($obj->isChanged());
978
979
        /* If we perform the same random query twice, it shouldn't return the same results */
980
        $itemsA = DataObject::get(DataObjectTest\TeamComment::class, "", DB::get_conn()->random());
981
        $itemsB = DataObject::get(DataObjectTest\TeamComment::class, "", DB::get_conn()->random());
982
        $itemsC = DataObject::get(DataObjectTest\TeamComment::class, "", DB::get_conn()->random());
983
        $itemsD = DataObject::get(DataObjectTest\TeamComment::class, "", DB::get_conn()->random());
984
        foreach ($itemsA as $item) {
985
            $keysA[] = $item->ID;
986
        }
987
        foreach ($itemsB as $item) {
988
            $keysB[] = $item->ID;
989
        }
990
        foreach ($itemsC as $item) {
991
            $keysC[] = $item->ID;
992
        }
993
        foreach ($itemsD as $item) {
994
            $keysD[] = $item->ID;
995
        }
996
997
        // These shouldn't all be the same (run it 4 times to minimise chance of an accidental collision)
998
        // There's about a 1 in a billion chance of an accidental collision
999
        $this->assertTrue($keysA != $keysB || $keysB != $keysC || $keysC != $keysD);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $keysC seems to be defined by a foreach iteration on line 990. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
Comprehensibility Best Practice introduced by
The variable $keysA seems to be defined by a foreach iteration on line 962. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
Comprehensibility Best Practice introduced by
The variable $keysD seems to be defined by a foreach iteration on line 993. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
Comprehensibility Best Practice introduced by
The variable $keysB seems to be defined by a foreach iteration on line 967. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
1000
    }
1001
1002
    public function testWriteSavesToHasOneRelations()
1003
    {
1004
        /* DataObject::write() should save to a has_one relationship if you set a field called (relname)ID */
1005
        $team = new DataObjectTest\Team();
1006
        $captainID = $this->idFromFixture(DataObjectTest\Player::class, 'player1');
1007
        $team->CaptainID = $captainID;
0 ignored issues
show
Bug Best Practice introduced by
The property CaptainID does not exist on SilverStripe\ORM\Tests\DataObjectTest\Team. Since you implemented __set, consider adding a @property annotation.
Loading history...
1008
        $team->write();
1009
        $this->assertEquals(
1010
            $captainID,
1011
            DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $team->ID")->value()
1012
        );
1013
1014
        /* After giving it a value, you should also be able to set it back to null */
1015
        $team->CaptainID = '';
1016
        $team->write();
1017
        $this->assertEquals(
1018
            0,
1019
            DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $team->ID")->value()
1020
        );
1021
1022
        /* You should also be able to save a blank to it when it's first created */
1023
        $team = new DataObjectTest\Team();
1024
        $team->CaptainID = '';
1025
        $team->write();
1026
        $this->assertEquals(
1027
            0,
1028
            DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $team->ID")->value()
1029
        );
1030
1031
        /* Ditto for existing records without a value */
1032
        $existingTeam = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1033
        $existingTeam->CaptainID = '';
0 ignored issues
show
Bug Best Practice introduced by
The property CaptainID does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
1034
        $existingTeam->write();
1035
        $this->assertEquals(
1036
            0,
1037
            DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $existingTeam->ID")->value()
1038
        );
1039
    }
1040
1041
    public function testCanAccessHasOneObjectsAsMethods()
1042
    {
1043
        /* If you have a has_one relation 'Captain' on $obj, and you set the $obj->CaptainID = (ID), then the
1044
        * object itself should be accessible as $obj->Captain() */
1045
        $team = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1046
        $captainID = $this->idFromFixture(DataObjectTest\Player::class, 'captain1');
1047
1048
        $team->CaptainID = $captainID;
0 ignored issues
show
Bug Best Practice introduced by
The property CaptainID does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
1049
        $this->assertNotNull($team->Captain());
1050
        $this->assertEquals($captainID, $team->Captain()->ID);
1051
1052
        // Test for polymorphic has_one relations
1053
        $fan = $this->objFromFixture(DataObjectTest\Fan::class, 'fan1');
1054
        $fan->FavouriteID = $team->ID;
0 ignored issues
show
Bug Best Practice introduced by
The property FavouriteID does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
1055
        $fan->FavouriteClass = DataObjectTest\Team::class;
0 ignored issues
show
Bug Best Practice introduced by
The property FavouriteClass does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
1056
        $this->assertNotNull($fan->Favourite());
1057
        $this->assertEquals($team->ID, $fan->Favourite()->ID);
1058
        $this->assertInstanceOf(DataObjectTest\Team::class, $fan->Favourite());
1059
    }
1060
1061
    public function testFieldNamesThatMatchMethodNamesWork()
1062
    {
1063
        /* Check that a field name that corresponds to a method on DataObject will still work */
1064
        $obj = new DataObjectTest\Fixture();
1065
        $obj->Data = "value1";
0 ignored issues
show
Bug Best Practice introduced by
The property Data does not exist on SilverStripe\ORM\Tests\DataObjectTest\Fixture. Since you implemented __set, consider adding a @property annotation.
Loading history...
1066
        $obj->DbObject = "value2";
0 ignored issues
show
Bug Best Practice introduced by
The property DbObject does not exist on SilverStripe\ORM\Tests\DataObjectTest\Fixture. Since you implemented __set, consider adding a @property annotation.
Loading history...
1067
        $obj->Duplicate = "value3";
0 ignored issues
show
Bug Best Practice introduced by
The property Duplicate does not exist on SilverStripe\ORM\Tests\DataObjectTest\Fixture. Since you implemented __set, consider adding a @property annotation.
Loading history...
1068
        $obj->write();
1069
1070
        $this->assertNotNull($obj->ID);
1071
        $this->assertEquals(
1072
            'value1',
1073
            DB::query("SELECT \"Data\" FROM \"DataObjectTest_Fixture\" WHERE \"ID\" = $obj->ID")->value()
1074
        );
1075
        $this->assertEquals(
1076
            'value2',
1077
            DB::query("SELECT \"DbObject\" FROM \"DataObjectTest_Fixture\" WHERE \"ID\" = $obj->ID")->value()
1078
        );
1079
        $this->assertEquals(
1080
            'value3',
1081
            DB::query("SELECT \"Duplicate\" FROM \"DataObjectTest_Fixture\" WHERE \"ID\" = $obj->ID")->value()
1082
        );
1083
    }
1084
1085
    /**
1086
     * @todo Re-enable all test cases for field existence after behaviour has been fixed
1087
     */
1088
    public function testFieldExistence()
1089
    {
1090
        $teamInstance = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1091
        $teamSingleton = singleton(DataObjectTest\Team::class);
1092
1093
        $subteamInstance = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam1');
1094
        $schema = DataObject::getSchema();
1095
1096
        /* hasField() singleton checks */
1097
        $this->assertTrue(
1098
            $teamSingleton->hasField('ID'),
1099
            'hasField() finds built-in fields in singletons'
1100
        );
1101
        $this->assertTrue(
1102
            $teamSingleton->hasField('Title'),
1103
            'hasField() finds custom fields in singletons'
1104
        );
1105
1106
        /* hasField() instance checks */
1107
        $this->assertFalse(
1108
            $teamInstance->hasField('NonExistingField'),
1109
            'hasField() doesnt find non-existing fields in instances'
1110
        );
1111
        $this->assertTrue(
1112
            $teamInstance->hasField('ID'),
1113
            'hasField() finds built-in fields in instances'
1114
        );
1115
        $this->assertTrue(
1116
            $teamInstance->hasField('Created'),
1117
            'hasField() finds built-in fields in instances'
1118
        );
1119
        $this->assertTrue(
1120
            $teamInstance->hasField('DatabaseField'),
1121
            'hasField() finds custom fields in instances'
1122
        );
1123
        //$this->assertFalse($teamInstance->hasField('SubclassDatabaseField'),
1124
        //'hasField() doesnt find subclass fields in parentclass instances');
1125
        $this->assertTrue(
1126
            $teamInstance->hasField('DynamicField'),
1127
            'hasField() finds dynamic getters in instances'
1128
        );
1129
        $this->assertTrue(
1130
            $teamInstance->hasField('HasOneRelationshipID'),
1131
            'hasField() finds foreign keys in instances'
1132
        );
1133
        $this->assertTrue(
1134
            $teamInstance->hasField('ExtendedDatabaseField'),
1135
            'hasField() finds extended fields in instances'
1136
        );
1137
        $this->assertTrue(
1138
            $teamInstance->hasField('ExtendedHasOneRelationshipID'),
1139
            'hasField() finds extended foreign keys in instances'
1140
        );
1141
        //$this->assertTrue($teamInstance->hasField('ExtendedDynamicField'),
1142
        //'hasField() includes extended dynamic getters in instances');
1143
1144
        /* hasField() subclass checks */
1145
        $this->assertTrue(
1146
            $subteamInstance->hasField('ID'),
1147
            'hasField() finds built-in fields in subclass instances'
1148
        );
1149
        $this->assertTrue(
1150
            $subteamInstance->hasField('Created'),
1151
            'hasField() finds built-in fields in subclass instances'
1152
        );
1153
        $this->assertTrue(
1154
            $subteamInstance->hasField('DatabaseField'),
1155
            'hasField() finds custom fields in subclass instances'
1156
        );
1157
        $this->assertTrue(
1158
            $subteamInstance->hasField('SubclassDatabaseField'),
1159
            'hasField() finds custom fields in subclass instances'
1160
        );
1161
        $this->assertTrue(
1162
            $subteamInstance->hasField('DynamicField'),
1163
            'hasField() finds dynamic getters in subclass instances'
1164
        );
1165
        $this->assertTrue(
1166
            $subteamInstance->hasField('HasOneRelationshipID'),
1167
            'hasField() finds foreign keys in subclass instances'
1168
        );
1169
        $this->assertTrue(
1170
            $subteamInstance->hasField('ExtendedDatabaseField'),
1171
            'hasField() finds extended fields in subclass instances'
1172
        );
1173
        $this->assertTrue(
1174
            $subteamInstance->hasField('ExtendedHasOneRelationshipID'),
1175
            'hasField() finds extended foreign keys in subclass instances'
1176
        );
1177
1178
        /* hasDatabaseField() singleton checks */
1179
        //$this->assertTrue($teamSingleton->hasDatabaseField('ID'),
1180
        //'hasDatabaseField() finds built-in fields in singletons');
1181
        $this->assertNotEmpty(
1182
            $schema->fieldSpec(DataObjectTest\Team::class, 'Title'),
1183
            'hasDatabaseField() finds custom fields in singletons'
1184
        );
1185
1186
        /* hasDatabaseField() instance checks */
1187
        $this->assertNull(
1188
            $schema->fieldSpec(DataObjectTest\Team::class, 'NonExistingField'),
1189
            'hasDatabaseField() doesnt find non-existing fields in instances'
1190
        );
1191
        //$this->assertNotEmpty($schema->fieldSpec(DataObjectTest_Team::class, 'ID'),
1192
        //'hasDatabaseField() finds built-in fields in instances');
1193
        $this->assertNotEmpty(
1194
            $schema->fieldSpec(DataObjectTest\Team::class, 'Created'),
1195
            'hasDatabaseField() finds built-in fields in instances'
1196
        );
1197
        $this->assertNotEmpty(
1198
            $schema->fieldSpec(DataObjectTest\Team::class, 'DatabaseField'),
1199
            'hasDatabaseField() finds custom fields in instances'
1200
        );
1201
        $this->assertNull(
1202
            $schema->fieldSpec(DataObjectTest\Team::class, 'SubclassDatabaseField'),
1203
            'hasDatabaseField() doesnt find subclass fields in parentclass instances'
1204
        );
1205
        //$this->assertNull($schema->fieldSpec(DataObjectTest_Team::class, 'DynamicField'),
1206
        //'hasDatabaseField() doesnt dynamic getters in instances');
1207
        $this->assertNotEmpty(
1208
            $schema->fieldSpec(DataObjectTest\Team::class, 'HasOneRelationshipID'),
1209
            'hasDatabaseField() finds foreign keys in instances'
1210
        );
1211
        $this->assertNotEmpty(
1212
            $schema->fieldSpec(DataObjectTest\Team::class, 'ExtendedDatabaseField'),
1213
            'hasDatabaseField() finds extended fields in instances'
1214
        );
1215
        $this->assertNotEmpty(
1216
            $schema->fieldSpec(DataObjectTest\Team::class, 'ExtendedHasOneRelationshipID'),
1217
            'hasDatabaseField() finds extended foreign keys in instances'
1218
        );
1219
        $this->assertNull(
1220
            $schema->fieldSpec(DataObjectTest\Team::class, 'ExtendedDynamicField'),
1221
            'hasDatabaseField() doesnt include extended dynamic getters in instances'
1222
        );
1223
1224
        /* hasDatabaseField() subclass checks */
1225
        $this->assertNotEmpty(
1226
            $schema->fieldSpec(DataObjectTest\SubTeam::class, 'DatabaseField'),
1227
            'hasField() finds custom fields in subclass instances'
1228
        );
1229
        $this->assertNotEmpty(
1230
            $schema->fieldSpec(DataObjectTest\SubTeam::class, 'SubclassDatabaseField'),
1231
            'hasField() finds custom fields in subclass instances'
1232
        );
1233
    }
1234
1235
    /**
1236
     * @todo Re-enable all test cases for field inheritance aggregation after behaviour has been fixed
1237
     */
1238
    public function testFieldInheritance()
1239
    {
1240
        $schema = DataObject::getSchema();
1241
1242
        // Test logical fields (including composite)
1243
        $teamSpecifications = $schema->fieldSpecs(DataObjectTest\Team::class);
1244
        $expected = array(
1245
            'ID',
1246
            'ClassName',
1247
            'LastEdited',
1248
            'Created',
1249
            'Title',
1250
            'DatabaseField',
1251
            'ExtendedDatabaseField',
1252
            'CaptainID',
1253
            'FounderID',
1254
            'HasOneRelationshipID',
1255
            'ExtendedHasOneRelationshipID'
1256
        );
1257
        $actual = array_keys($teamSpecifications);
1258
        sort($expected);
1259
        sort($actual);
1260
        $this->assertEquals(
1261
            $expected,
1262
            $actual,
1263
            'fieldSpecifications() contains all fields defined on instance: base, extended and foreign keys'
1264
        );
1265
1266
        $teamFields = $schema->databaseFields(DataObjectTest\Team::class, false);
1267
        $expected = array(
1268
            'ID',
1269
            'ClassName',
1270
            'LastEdited',
1271
            'Created',
1272
            'Title',
1273
            'DatabaseField',
1274
            'ExtendedDatabaseField',
1275
            'CaptainID',
1276
            'FounderID',
1277
            'HasOneRelationshipID',
1278
            'ExtendedHasOneRelationshipID'
1279
        );
1280
        $actual = array_keys($teamFields);
1281
        sort($expected);
1282
        sort($actual);
1283
        $this->assertEquals(
1284
            $expected,
1285
            $actual,
1286
            'databaseFields() contains only fields defined on instance, including base, extended and foreign keys'
1287
        );
1288
1289
        $subteamSpecifications = $schema->fieldSpecs(DataObjectTest\SubTeam::class);
1290
        $expected = array(
1291
            'ID',
1292
            'ClassName',
1293
            'LastEdited',
1294
            'Created',
1295
            'Title',
1296
            'DatabaseField',
1297
            'ExtendedDatabaseField',
1298
            'CaptainID',
1299
            'FounderID',
1300
            'HasOneRelationshipID',
1301
            'ExtendedHasOneRelationshipID',
1302
            'SubclassDatabaseField',
1303
            'ParentTeamID',
1304
        );
1305
        $actual = array_keys($subteamSpecifications);
1306
        sort($expected);
1307
        sort($actual);
1308
        $this->assertEquals(
1309
            $expected,
1310
            $actual,
1311
            'fieldSpecifications() on subclass contains all fields, including base, extended  and foreign keys'
1312
        );
1313
1314
        $subteamFields = $schema->databaseFields(DataObjectTest\SubTeam::class, false);
1315
        $expected = array(
1316
            'ID',
1317
            'SubclassDatabaseField',
1318
            'ParentTeamID',
1319
        );
1320
        $actual = array_keys($subteamFields);
1321
        sort($expected);
1322
        sort($actual);
1323
        $this->assertEquals(
1324
            $expected,
1325
            $actual,
1326
            'databaseFields() on subclass contains only fields defined on instance'
1327
        );
1328
    }
1329
1330
    public function testSearchableFields()
1331
    {
1332
        $player = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
1333
        $fields = $player->searchableFields();
1334
        $this->assertArrayHasKey(
1335
            'IsRetired',
1336
            $fields,
1337
            'Fields defined by $searchable_fields static are correctly detected'
1338
        );
1339
        $this->assertArrayHasKey(
1340
            'ShirtNumber',
1341
            $fields,
1342
            'Fields defined by $searchable_fields static are correctly detected'
1343
        );
1344
1345
        $team = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1346
        $fields = $team->searchableFields();
1347
        $this->assertArrayHasKey(
1348
            'Title',
1349
            $fields,
1350
            'Fields can be inherited from the $summary_fields static, including methods called on fields'
1351
        );
1352
        $this->assertArrayHasKey(
1353
            'Captain.ShirtNumber',
1354
            $fields,
1355
            'Fields on related objects can be inherited from the $summary_fields static'
1356
        );
1357
        $this->assertArrayHasKey(
1358
            'Captain.FavouriteTeam.Title',
1359
            $fields,
1360
            'Fields on related objects can be inherited from the $summary_fields static'
1361
        );
1362
1363
        $testObj = new DataObjectTest\Fixture();
1364
        $fields = $testObj->searchableFields();
1365
        $this->assertEmpty($fields);
1366
    }
1367
1368
    public function testCastingHelper()
1369
    {
1370
        $team = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1371
1372
        $this->assertEquals('Varchar', $team->castingHelper('Title'), 'db field wasn\'t casted correctly');
1373
        $this->assertEquals('HTMLVarchar', $team->castingHelper('DatabaseField'), 'db field wasn\'t casted correctly');
1374
1375
        $sponsor = $team->Sponsors()->first();
0 ignored issues
show
Bug introduced by
The method Sponsors() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1375
        $sponsor = $team->/** @scrutinizer ignore-call */ Sponsors()->first();
Loading history...
1376
        $this->assertEquals('Int', $sponsor->castingHelper('SponsorFee'), 'many_many_extraFields not casted correctly');
1377
    }
1378
1379
    public function testSummaryFieldsCustomLabels()
1380
    {
1381
        $team = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1382
        $summaryFields = $team->summaryFields();
1383
1384
        $this->assertEquals(
1385
            [
1386
                'Title' => 'Custom Title',
1387
                'Title.UpperCase' => 'Title',
1388
                'Captain.ShirtNumber' => 'Captain\'s shirt number',
1389
                'Captain.FavouriteTeam.Title' => 'Captain\'s favourite team',
1390
            ],
1391
            $summaryFields
1392
        );
1393
    }
1394
1395
    public function testDataObjectUpdate()
1396
    {
1397
        /* update() calls can use the dot syntax to reference has_one relations and other methods that return
1398
        * objects */
1399
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1400
        $team1->CaptainID = $this->idFromFixture(DataObjectTest\Player::class, 'captain1');
0 ignored issues
show
Bug Best Practice introduced by
The property CaptainID does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
1401
1402
        $team1->update(
1403
            array(
1404
                'DatabaseField' => 'Something',
1405
                'Captain.FirstName' => 'Jim',
1406
                'Captain.Email' => '[email protected]',
1407
                'Captain.FavouriteTeam.Title' => 'New and improved team 1',
1408
            )
1409
        );
1410
1411
        /* Test the simple case of updating fields on the object itself */
1412
        $this->assertEquals('Something', $team1->DatabaseField);
0 ignored issues
show
Bug Best Practice introduced by
The property DatabaseField does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
1413
1414
        /* Setting Captain.Email and Captain.FirstName will have updated DataObjectTest_Captain.captain1 in
1415
        * the database.  Although update() doesn't usually write, it does write related records automatically. */
1416
        $captain1 = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
1417
        $this->assertEquals('Jim', $captain1->FirstName);
0 ignored issues
show
Bug Best Practice introduced by
The property FirstName does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
1418
        $this->assertEquals('[email protected]', $captain1->Email);
0 ignored issues
show
Bug Best Practice introduced by
The property Email does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
1419
1420
        /* Jim's favourite team is team 1; we need to reload the object to the the change that setting Captain.
1421
        * FavouriteTeam.Title made */
1422
        $reloadedTeam1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1423
        $this->assertEquals('New and improved team 1', $reloadedTeam1->Title);
1424
    }
1425
1426
    public function testDataObjectUpdateNew()
1427
    {
1428
        /* update() calls can use the dot syntax to reference has_one relations and other methods that return
1429
        * objects */
1430
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1431
        $team1->CaptainID = 0;
0 ignored issues
show
Bug Best Practice introduced by
The property CaptainID does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
1432
1433
        $team1->update(
1434
            array(
1435
                'Captain.FirstName' => 'Jim',
1436
                'Captain.FavouriteTeam.Title' => 'New and improved team 1',
1437
            )
1438
        );
1439
        /* Test that the captain ID has been updated */
1440
        $this->assertGreaterThan(0, $team1->CaptainID);
0 ignored issues
show
Bug Best Practice introduced by
The property CaptainID does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
1441
1442
        /* Fetch the newly created captain */
1443
        $captain1 = DataObjectTest\Player::get()->byID($team1->CaptainID);
1444
        $this->assertEquals('Jim', $captain1->FirstName);
0 ignored issues
show
Bug Best Practice introduced by
The property FirstName does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
1445
1446
        /* Grab the favourite team and make sure it has the correct values */
1447
        $reloadedTeam1 = $captain1->FavouriteTeam();
1448
        $this->assertEquals($reloadedTeam1->ID, $captain1->FavouriteTeamID);
0 ignored issues
show
Bug Best Practice introduced by
The property FavouriteTeamID does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
1449
        $this->assertEquals('New and improved team 1', $reloadedTeam1->Title);
1450
    }
1451
1452
1453
    /**
1454
     * @expectedException \SilverStripe\ORM\ValidationException
1455
     */
1456
    public function testWritingInvalidDataObjectThrowsException()
1457
    {
1458
        $validatedObject = new DataObjectTest\ValidatedObject();
1459
        $validatedObject->write();
1460
    }
1461
1462
    public function testWritingValidDataObjectDoesntThrowException()
1463
    {
1464
        $validatedObject = new DataObjectTest\ValidatedObject();
1465
        $validatedObject->Name = "Mr. Jones";
0 ignored issues
show
Bug Best Practice introduced by
The property Name does not exist on SilverStripe\ORM\Tests\D...ectTest\ValidatedObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
1466
1467
        $validatedObject->write();
1468
        $this->assertTrue($validatedObject->isInDB(), "Validated object was not saved to database");
1469
    }
1470
1471
    public function testSubclassCreation()
1472
    {
1473
        /* Creating a new object of a subclass should set the ClassName field correctly */
1474
        $obj = new DataObjectTest\SubTeam();
1475
        $obj->write();
1476
        $this->assertEquals(
1477
            DataObjectTest\SubTeam::class,
1478
            DB::query("SELECT \"ClassName\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $obj->ID")->value()
1479
        );
1480
    }
1481
1482
    public function testForceInsert()
1483
    {
1484
        /* If you set an ID on an object and pass forceInsert = true, then the object should be correctly created */
1485
        $conn = DB::get_conn();
1486
        if (method_exists($conn, 'allowPrimaryKeyEditing')) {
1487
            $conn->allowPrimaryKeyEditing(DataObjectTest\Team::class, true);
1488
        }
1489
        $obj = new DataObjectTest\SubTeam();
1490
        $obj->ID = 1001;
1491
        $obj->Title = 'asdfasdf';
1492
        $obj->SubclassDatabaseField = 'asdfasdf';
0 ignored issues
show
Bug Best Practice introduced by
The property SubclassDatabaseField does not exist on SilverStripe\ORM\Tests\DataObjectTest\SubTeam. Since you implemented __set, consider adding a @property annotation.
Loading history...
1493
        $obj->write(false, true);
1494
        if (method_exists($conn, 'allowPrimaryKeyEditing')) {
1495
            $conn->allowPrimaryKeyEditing(DataObjectTest\Team::class, false);
1496
        }
1497
1498
        $this->assertEquals(
1499
            DataObjectTest\SubTeam::class,
1500
            DB::query("SELECT \"ClassName\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $obj->ID")->value()
1501
        );
1502
1503
        /* Check that it actually saves to the database with the correct ID */
1504
        $this->assertEquals(
1505
            "1001",
1506
            DB::query(
1507
                "SELECT \"ID\" FROM \"DataObjectTest_SubTeam\" WHERE \"SubclassDatabaseField\" = 'asdfasdf'"
1508
            )->value()
1509
        );
1510
        $this->assertEquals(
1511
            "1001",
1512
            DB::query("SELECT \"ID\" FROM \"DataObjectTest_Team\" WHERE \"Title\" = 'asdfasdf'")->value()
1513
        );
1514
    }
1515
1516
    public function testHasOwnTable()
1517
    {
1518
        $schema = DataObject::getSchema();
1519
        /* Test DataObject::has_own_table() returns true if the object has $has_one or $db values */
1520
        $this->assertTrue($schema->classHasTable(DataObjectTest\Player::class));
1521
        $this->assertTrue($schema->classHasTable(DataObjectTest\Team::class));
1522
        $this->assertTrue($schema->classHasTable(DataObjectTest\Fixture::class));
1523
1524
        /* Root DataObject that always have a table, even if they lack both $db and $has_one */
1525
        $this->assertTrue($schema->classHasTable(DataObjectTest\FieldlessTable::class));
1526
1527
        /* Subclasses without $db or $has_one don't have a table */
1528
        $this->assertFalse($schema->classHasTable(DataObjectTest\FieldlessSubTable::class));
1529
1530
        /* Return false if you don't pass it a subclass of DataObject */
1531
        $this->assertFalse($schema->classHasTable(DataObject::class));
1532
        $this->assertFalse($schema->classHasTable(ViewableData::class));
1533
1534
        /* Invalid class name */
1535
        $this->assertFalse($schema->classHasTable("ThisIsntADataObject"));
1536
    }
1537
1538
    public function testMerge()
1539
    {
1540
        // test right merge of subclasses
1541
        $left = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam1');
1542
        $right = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam2_with_player_relation');
1543
        $leftOrigID = $left->ID;
1544
        $left->merge($right, 'right', false, false);
1545
        $this->assertEquals(
1546
            $left->Title,
1547
            'Subteam 2',
1548
            'merge() with "right" priority overwrites fields with existing values on subclasses'
1549
        );
1550
        $this->assertEquals(
1551
            $left->ID,
1552
            $leftOrigID,
1553
            'merge() with "right" priority doesnt overwrite database ID'
1554
        );
1555
1556
        // test overwriteWithEmpty flag on existing left values
1557
        $left = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam2_with_player_relation');
1558
        $right = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam3_with_empty_fields');
1559
        $left->merge($right, 'right', false, true);
1560
        $this->assertEquals(
1561
            $left->Title,
1562
            'Subteam 3',
1563
            'merge() with $overwriteWithEmpty overwrites non-empty fields on left object'
1564
        );
1565
1566
        // test overwriteWithEmpty flag on empty left values
1567
        $left = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam1');
1568
        // $SubclassDatabaseField is empty on here
1569
        $right = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam2_with_player_relation');
1570
        $left->merge($right, 'right', false, true);
1571
        $this->assertEquals(
1572
            $left->SubclassDatabaseField,
0 ignored issues
show
Bug Best Practice introduced by
The property SubclassDatabaseField does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
1573
            null,
1574
            'merge() with $overwriteWithEmpty overwrites empty fields on left object'
1575
        );
1576
1577
        // @todo test "left" priority flag
1578
        // @todo test includeRelations flag
1579
        // @todo test includeRelations in combination with overwriteWithEmpty
1580
        // @todo test has_one relations
1581
        // @todo test has_many and many_many relations
1582
    }
1583
1584
    public function testPopulateDefaults()
1585
    {
1586
        $obj = new DataObjectTest\Fixture();
1587
        $this->assertEquals(
1588
            $obj->MyFieldWithDefault,
0 ignored issues
show
Bug Best Practice introduced by
The property MyFieldWithDefault does not exist on SilverStripe\ORM\Tests\DataObjectTest\Fixture. Since you implemented __get, consider adding a @property annotation.
Loading history...
1589
            'Default Value',
1590
            'Defaults are populated for in-memory object from $defaults array'
1591
        );
1592
1593
        $this->assertEquals(
1594
            $obj->MyFieldWithAltDefault,
1595
            'Default Value',
1596
            'Defaults are populated from overloaded populateDefaults() method'
1597
        );
1598
1599
        // Test populate defaults on subclasses
1600
        $staffObj = new DataObjectTest\Staff();
1601
        $this->assertEquals('Staff', $staffObj->EmploymentType);
0 ignored issues
show
Bug Best Practice introduced by
The property EmploymentType does not exist on SilverStripe\ORM\Tests\DataObjectTest\Staff. Since you implemented __get, consider adding a @property annotation.
Loading history...
1602
1603
        $ceoObj = new DataObjectTest\CEO();
1604
        $this->assertEquals('Staff', $ceoObj->EmploymentType);
0 ignored issues
show
Bug Best Practice introduced by
The property EmploymentType does not exist on SilverStripe\ORM\Tests\DataObjectTest\CEO. Since you implemented __get, consider adding a @property annotation.
Loading history...
1605
    }
1606
1607
    /**
1608
     * @expectedException \InvalidArgumentException
1609
     */
1610
    public function testValidateModelDefinitionsFailsWithArray()
1611
    {
1612
        Config::modify()->merge(DataObjectTest\Team::class, 'has_one', array('NotValid' => array('NoArraysAllowed')));
1613
        DataObject::getSchema()->hasOneComponent(DataObjectTest\Team::class, 'NotValid');
1614
    }
1615
1616
    /**
1617
     * @expectedException \InvalidArgumentException
1618
     */
1619
    public function testValidateModelDefinitionsFailsWithIntKey()
1620
    {
1621
        Config::modify()->set(DataObjectTest\Team::class, 'has_many', array(0 => DataObjectTest\Player::class));
1622
        DataObject::getSchema()->hasManyComponent(DataObjectTest\Team::class, 0);
1623
    }
1624
1625
    /**
1626
     * @expectedException \InvalidArgumentException
1627
     */
1628
    public function testValidateModelDefinitionsFailsWithIntValue()
1629
    {
1630
        Config::modify()->merge(DataObjectTest\Team::class, 'many_many', array('Players' => 12));
1631
        DataObject::getSchema()->manyManyComponent(DataObjectTest\Team::class, 'Players');
1632
    }
1633
1634
    public function testNewClassInstance()
1635
    {
1636
        $dataObject = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1637
        $changedDO = $dataObject->newClassInstance(DataObjectTest\SubTeam::class);
1638
        $changedFields = $changedDO->getChangedFields();
1639
1640
        // Don't write the record, it will reset changed fields
1641
        $this->assertInstanceOf(DataObjectTest\SubTeam::class, $changedDO);
1642
        $this->assertEquals($changedDO->ClassName, DataObjectTest\SubTeam::class);
1643
        $this->assertEquals($changedDO->RecordClassName, DataObjectTest\SubTeam::class);
0 ignored issues
show
Bug Best Practice introduced by
The property RecordClassName does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
1644
        $this->assertContains('ClassName', array_keys($changedFields));
1645
        $this->assertEquals($changedFields['ClassName']['before'], DataObjectTest\Team::class);
1646
        $this->assertEquals($changedFields['ClassName']['after'], DataObjectTest\SubTeam::class);
1647
        $this->assertEquals($changedFields['RecordClassName']['before'], DataObjectTest\Team::class);
1648
        $this->assertEquals($changedFields['RecordClassName']['after'], DataObjectTest\SubTeam::class);
1649
1650
        $changedDO->write();
1651
1652
        $this->assertInstanceOf(DataObjectTest\SubTeam::class, $changedDO);
1653
        $this->assertEquals($changedDO->ClassName, DataObjectTest\SubTeam::class);
1654
1655
        // Test invalid classes fail
1656
        $this->expectException(InvalidArgumentException::class);
1657
        $this->expectExceptionMessage('Controller is not a valid subclass of DataObject');
1658
        /**
1659
         * @skipUpgrade
1660
         */
1661
        $dataObject->newClassInstance('Controller');
1662
    }
1663
1664
    public function testMultipleManyManyWithSameClass()
1665
    {
1666
        $team = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1667
        $company2 = $this->objFromFixture(DataObjectTest\EquipmentCompany::class, 'equipmentcompany2');
1668
        $sponsors = $team->Sponsors();
1669
        $equipmentSuppliers = $team->EquipmentSuppliers();
0 ignored issues
show
Bug introduced by
The method EquipmentSuppliers() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1669
        /** @scrutinizer ignore-call */ 
1670
        $equipmentSuppliers = $team->EquipmentSuppliers();
Loading history...
1670
1671
        // Check that DataObject::many_many() works as expected
1672
        $manyManyComponent = DataObject::getSchema()->manyManyComponent(DataObjectTest\Team::class, 'Sponsors');
1673
        $this->assertEquals(ManyManyList::class, $manyManyComponent['relationClass']);
1674
        $this->assertEquals(
1675
            DataObjectTest\Team::class,
1676
            $manyManyComponent['parentClass'],
1677
            'DataObject::many_many() didn\'t find the correct base class'
1678
        );
1679
        $this->assertEquals(
1680
            DataObjectTest\EquipmentCompany::class,
1681
            $manyManyComponent['childClass'],
1682
            'DataObject::many_many() didn\'t find the correct target class for the relation'
1683
        );
1684
        $this->assertEquals(
1685
            'DataObjectTest_EquipmentCompany_SponsoredTeams',
1686
            $manyManyComponent['join'],
1687
            'DataObject::many_many() didn\'t find the correct relation table'
1688
        );
1689
        $this->assertEquals('DataObjectTest_TeamID', $manyManyComponent['parentField']);
1690
        $this->assertEquals('DataObjectTest_EquipmentCompanyID', $manyManyComponent['childField']);
1691
1692
        // Check that ManyManyList still works
1693
        $this->assertEquals(2, $sponsors->count(), 'Rows are missing from relation');
1694
        $this->assertEquals(1, $equipmentSuppliers->count(), 'Rows are missing from relation');
1695
1696
        // Check everything works when no relation is present
1697
        $teamWithoutSponsor = $this->objFromFixture(DataObjectTest\Team::class, 'team3');
1698
        $this->assertInstanceOf(ManyManyList::class, $teamWithoutSponsor->Sponsors());
1699
        $this->assertEquals(0, $teamWithoutSponsor->Sponsors()->count());
1700
1701
        // Test that belongs_many_many can be infered from with getNonReciprocalComponent
1702
        $this->assertListEquals(
1703
            [
1704
                ['Name' => 'Company corp'],
1705
                ['Name' => 'Team co.'],
1706
            ],
1707
            $team->inferReciprocalComponent(DataObjectTest\EquipmentCompany::class, 'SponsoredTeams')
0 ignored issues
show
Bug introduced by
It seems like $team->inferReciprocalCo...lass, 'SponsoredTeams') can also be of type SilverStripe\ORM\DataObject; however, parameter $list of SilverStripe\Dev\SapphireTest::assertListEquals() does only seem to accept SilverStripe\ORM\SS_List, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1707
            /** @scrutinizer ignore-type */ $team->inferReciprocalComponent(DataObjectTest\EquipmentCompany::class, 'SponsoredTeams')
Loading history...
1708
        );
1709
1710
        // Test that many_many can be infered from getNonReciprocalComponent
1711
        $this->assertListEquals(
1712
            [
1713
                ['Title' => 'Team 1'],
1714
                ['Title' => 'Team 2'],
1715
                ['Title' => 'Subteam 1'],
1716
            ],
1717
            $company2->inferReciprocalComponent(DataObjectTest\Team::class, 'Sponsors')
1718
        );
1719
1720
        // Check many_many_extraFields still works
1721
        $equipmentCompany = $this->objFromFixture(DataObjectTest\EquipmentCompany::class, 'equipmentcompany1');
1722
        $equipmentCompany->SponsoredTeams()->add($teamWithoutSponsor, array('SponsorFee' => 1000));
0 ignored issues
show
Bug introduced by
The method SponsoredTeams() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1722
        $equipmentCompany->/** @scrutinizer ignore-call */ 
1723
                           SponsoredTeams()->add($teamWithoutSponsor, array('SponsorFee' => 1000));
Loading history...
1723
        $sponsoredTeams = $equipmentCompany->SponsoredTeams();
1724
        $this->assertEquals(
1725
            1000,
1726
            $sponsoredTeams->byID($teamWithoutSponsor->ID)->SponsorFee,
1727
            'Data from many_many_extraFields was not stored/extracted correctly'
1728
        );
1729
1730
        // Check subclasses correctly inherit multiple many_manys
1731
        $subTeam = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam1');
1732
        $this->assertEquals(
1733
            2,
1734
            $subTeam->Sponsors()->count(),
1735
            'Child class did not inherit multiple many_manys'
1736
        );
1737
        $this->assertEquals(
1738
            1,
1739
            $subTeam->EquipmentSuppliers()->count(),
1740
            'Child class did not inherit multiple many_manys'
1741
        );
1742
        // Team 2 has one EquipmentCompany sponsor and one SubEquipmentCompany
1743
        $team2 = $this->objFromFixture(DataObjectTest\Team::class, 'team2');
1744
        $this->assertEquals(
1745
            2,
1746
            $team2->Sponsors()->count(),
1747
            'Child class did not inherit multiple belongs_many_manys'
1748
        );
1749
1750
        // Check many_many_extraFields also works from the belongs_many_many side
1751
        $sponsors = $team2->Sponsors();
1752
        $sponsors->add($equipmentCompany, array('SponsorFee' => 750));
1753
        $this->assertEquals(
1754
            750,
1755
            $sponsors->byID($equipmentCompany->ID)->SponsorFee,
1756
            'Data from many_many_extraFields was not stored/extracted correctly'
1757
        );
1758
1759
        $subEquipmentCompany = $this->objFromFixture(DataObjectTest\SubEquipmentCompany::class, 'subequipmentcompany1');
1760
        $subTeam->Sponsors()->add($subEquipmentCompany, array('SponsorFee' => 1200));
1761
        $this->assertEquals(
1762
            1200,
1763
            $subTeam->Sponsors()->byID($subEquipmentCompany->ID)->SponsorFee,
1764
            'Data from inherited many_many_extraFields was not stored/extracted correctly'
1765
        );
1766
    }
1767
1768
    public function testManyManyExtraFields()
1769
    {
1770
        $team = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1771
        $schema = DataObject::getSchema();
1772
1773
        // Get all extra fields
1774
        $teamExtraFields = $team->manyManyExtraFields();
1775
        $this->assertEquals(
1776
            array(
1777
                'Players' => array('Position' => 'Varchar(100)')
1778
            ),
1779
            $teamExtraFields
1780
        );
1781
1782
        // Ensure fields from parent classes are included
1783
        $subTeam = singleton(DataObjectTest\SubTeam::class);
1784
        $teamExtraFields = $subTeam->manyManyExtraFields();
1785
        $this->assertEquals(
1786
            array(
1787
                'Players' => array('Position' => 'Varchar(100)'),
1788
                'FormerPlayers' => array('Position' => 'Varchar(100)')
1789
            ),
1790
            $teamExtraFields
1791
        );
1792
1793
        // Extra fields are immediately available on the Team class (defined in $many_many_extraFields)
1794
        $teamExtraFields = $schema->manyManyExtraFieldsForComponent(DataObjectTest\Team::class, 'Players');
1795
        $this->assertEquals(
1796
            $teamExtraFields,
1797
            array(
1798
                'Position' => 'Varchar(100)'
1799
            )
1800
        );
1801
1802
        // We'll have to go through the relation to get the extra fields on Player
1803
        $playerExtraFields = $schema->manyManyExtraFieldsForComponent(DataObjectTest\Player::class, 'Teams');
1804
        $this->assertEquals(
1805
            $playerExtraFields,
1806
            array(
1807
                'Position' => 'Varchar(100)'
1808
            )
1809
        );
1810
1811
        // Iterate through a many-many relationship and confirm that extra fields are included
1812
        $newTeam = new DataObjectTest\Team();
1813
        $newTeam->Title = "New team";
1814
        $newTeam->write();
1815
        $newTeamID = $newTeam->ID;
1816
1817
        $newPlayer = new DataObjectTest\Player();
1818
        $newPlayer->FirstName = "Sam";
1819
        $newPlayer->Surname = "Minnee";
1820
        $newPlayer->write();
1821
1822
        // The idea of Sam as a prop is essentially humourous.
1823
        $newTeam->Players()->add($newPlayer, array("Position" => "Prop"));
1824
1825
        // Requery and uncache everything
1826
        $newTeam->flushCache();
1827
        $newTeam = DataObject::get_by_id(DataObjectTest\Team::class, $newTeamID);
1828
1829
        // Check that the Position many_many_extraField is extracted.
1830
        $player = $newTeam->Players()->first();
0 ignored issues
show
Bug introduced by
The method Players() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1830
        $player = $newTeam->/** @scrutinizer ignore-call */ Players()->first();
Loading history...
1831
        $this->assertEquals('Sam', $player->FirstName);
1832
        $this->assertEquals("Prop", $player->Position);
1833
1834
        // Check that ordering a many-many relation by an aggregate column doesn't fail
1835
        $player = $this->objFromFixture(DataObjectTest\Player::class, 'player2');
1836
        $player->Teams()->sort("count(DISTINCT \"DataObjectTest_Team_Players\".\"DataObjectTest_PlayerID\") DESC");
0 ignored issues
show
Bug introduced by
The method Teams() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1836
        $player->/** @scrutinizer ignore-call */ 
1837
                 Teams()->sort("count(DISTINCT \"DataObjectTest_Team_Players\".\"DataObjectTest_PlayerID\") DESC");
Loading history...
1837
    }
1838
1839
    /**
1840
     * Check that the queries generated for many-many relation queries can have unlimitedRowCount
1841
     * called on them.
1842
     */
1843
    public function testManyManyUnlimitedRowCount()
1844
    {
1845
        $player = $this->objFromFixture(DataObjectTest\Player::class, 'player2');
1846
        // TODO: What's going on here?
1847
        $this->assertEquals(2, $player->Teams()->dataQuery()->query()->unlimitedRowCount());
1848
    }
1849
1850
    /**
1851
     * Tests that singular_name() generates sensible defaults.
1852
     */
1853
    public function testSingularName()
1854
    {
1855
        $assertions = array(
1856
            DataObjectTest\Player::class => 'Player',
1857
            DataObjectTest\Team::class => 'Team',
1858
            DataObjectTest\Fixture::class => 'Fixture',
1859
        );
1860
1861
        foreach ($assertions as $class => $expectedSingularName) {
1862
            $this->assertEquals(
1863
                $expectedSingularName,
1864
                singleton($class)->singular_name(),
1865
                "Assert that the singular_name for '$class' is correct."
1866
            );
1867
        }
1868
    }
1869
1870
    /**
1871
     * Tests that plural_name() generates sensible defaults.
1872
     */
1873
    public function testPluralName()
1874
    {
1875
        $assertions = array(
1876
            DataObjectTest\Player::class => 'Players',
1877
            DataObjectTest\Team::class => 'Teams',
1878
            DataObjectTest\Fixture::class => 'Fixtures',
1879
            DataObjectTest\Play::class => 'Plays',
1880
            DataObjectTest\Bogey::class => 'Bogeys',
1881
            DataObjectTest\Ploy::class => 'Ploys',
1882
        );
1883
        i18n::set_locale('en_NZ');
1884
        foreach ($assertions as $class => $expectedPluralName) {
1885
            $this->assertEquals(
1886
                $expectedPluralName,
1887
                DataObject::singleton($class)->plural_name(),
1888
                "Assert that the plural_name for '$class' is correct."
1889
            );
1890
            $this->assertEquals(
1891
                $expectedPluralName,
1892
                DataObject::singleton($class)->i18n_plural_name(),
1893
                "Assert that the i18n_plural_name for '$class' is correct."
1894
            );
1895
        }
1896
    }
1897
1898
    public function testHasDatabaseField()
1899
    {
1900
        $team = singleton(DataObjectTest\Team::class);
1901
        $subteam = singleton(DataObjectTest\SubTeam::class);
1902
1903
        $this->assertTrue(
1904
            $team->hasDatabaseField('Title'),
1905
            "hasOwnDatabaseField() works with \$db fields"
1906
        );
1907
        $this->assertTrue(
1908
            $team->hasDatabaseField('CaptainID'),
1909
            "hasOwnDatabaseField() works with \$has_one fields"
1910
        );
1911
        $this->assertFalse(
1912
            $team->hasDatabaseField('NonExistentField'),
1913
            "hasOwnDatabaseField() doesn't detect non-existend fields"
1914
        );
1915
        $this->assertTrue(
1916
            $team->hasDatabaseField('ExtendedDatabaseField'),
1917
            "hasOwnDatabaseField() works with extended fields"
1918
        );
1919
        $this->assertFalse(
1920
            $team->hasDatabaseField('SubclassDatabaseField'),
1921
            "hasOwnDatabaseField() doesn't pick up fields in subclasses on parent class"
1922
        );
1923
1924
        $this->assertTrue(
1925
            $subteam->hasDatabaseField('SubclassDatabaseField'),
1926
            "hasOwnDatabaseField() picks up fields in subclasses"
1927
        );
1928
    }
1929
1930
    public function testFieldTypes()
1931
    {
1932
        $obj = new DataObjectTest\Fixture();
1933
        $obj->DateField = '1988-01-02';
0 ignored issues
show
Bug Best Practice introduced by
The property DateField does not exist on SilverStripe\ORM\Tests\DataObjectTest\Fixture. Since you implemented __set, consider adding a @property annotation.
Loading history...
1934
        $obj->DatetimeField = '1988-03-04 06:30';
0 ignored issues
show
Bug Best Practice introduced by
The property DatetimeField does not exist on SilverStripe\ORM\Tests\DataObjectTest\Fixture. Since you implemented __set, consider adding a @property annotation.
Loading history...
1935
        $obj->write();
1936
        $obj->flushCache();
1937
1938
        $obj = DataObject::get_by_id(DataObjectTest\Fixture::class, $obj->ID);
1939
        $this->assertEquals('1988-01-02', $obj->DateField);
0 ignored issues
show
Bug Best Practice introduced by
The property DateField does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
1940
        $this->assertEquals('1988-03-04 06:30:00', $obj->DatetimeField);
0 ignored issues
show
Bug Best Practice introduced by
The property DatetimeField does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
1941
    }
1942
1943
    /**
1944
     * Tests that the autogenerated ID is returned as int
1945
     */
1946
    public function testIDFieldTypeAfterInsert()
1947
    {
1948
        $obj = new DataObjectTest\Fixture();
1949
        $obj->write();
1950
1951
        $this->assertInternalType("int", $obj->ID);
1952
    }
1953
1954
    /**
1955
     * Tests that zero values are returned with the correct types
1956
     */
1957
    public function testZeroIsFalse()
1958
    {
1959
        $obj = new DataObjectTest\Fixture();
1960
        $obj->MyInt = 0;
0 ignored issues
show
Bug Best Practice introduced by
The property MyInt does not exist on SilverStripe\ORM\Tests\DataObjectTest\Fixture. Since you implemented __set, consider adding a @property annotation.
Loading history...
1961
        $obj->MyDecimal = 0.00;
0 ignored issues
show
Bug Best Practice introduced by
The property MyDecimal does not exist on SilverStripe\ORM\Tests\DataObjectTest\Fixture. Since you implemented __set, consider adding a @property annotation.
Loading history...
1962
        $obj->MyCurrency = 0.00;
0 ignored issues
show
Bug Best Practice introduced by
The property MyCurrency does not exist on SilverStripe\ORM\Tests\DataObjectTest\Fixture. Since you implemented __set, consider adding a @property annotation.
Loading history...
1963
        $obj->write();
1964
1965
        $this->assertEquals(0, $obj->MyInt, 'DBInt fields should be integer on first assignment');
0 ignored issues
show
Bug Best Practice introduced by
The property MyInt does not exist on SilverStripe\ORM\Tests\DataObjectTest\Fixture. Since you implemented __get, consider adding a @property annotation.
Loading history...
1966
        $this->assertEquals(0.00, $obj->MyDecimal, 'DBDecimal fields should be float on first assignment');
0 ignored issues
show
Bug Best Practice introduced by
The property MyDecimal does not exist on SilverStripe\ORM\Tests\DataObjectTest\Fixture. Since you implemented __get, consider adding a @property annotation.
Loading history...
1967
        $this->assertEquals(0.00, $obj->MyCurrency, 'DBCurrency fields should be float on first assignment');
0 ignored issues
show
Bug Best Practice introduced by
The property MyCurrency does not exist on SilverStripe\ORM\Tests\DataObjectTest\Fixture. Since you implemented __get, consider adding a @property annotation.
Loading history...
1968
1969
        $obj2 = DataObjectTest\Fixture::get()->byId($obj->ID);
1970
1971
        $this->assertEquals(0, $obj2->MyInt, 'DBInt fields should be integer');
0 ignored issues
show
Bug Best Practice introduced by
The property MyInt does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
1972
        $this->assertEquals(0.00, $obj2->MyDecimal, 'DBDecimal fields should be float');
0 ignored issues
show
Bug Best Practice introduced by
The property MyDecimal does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
1973
        $this->assertEquals(0.00, $obj2->MyCurrency, 'DBCurrency fields should be float');
0 ignored issues
show
Bug Best Practice introduced by
The property MyCurrency does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
1974
1975
        $this->assertFalse((bool)$obj2->MyInt, 'DBInt zero fields should be falsey on fetch from DB');
1976
        $this->assertFalse((bool)$obj2->MyDecimal, 'DBDecimal zero fields should be falsey on fetch from DB');
1977
        $this->assertFalse((bool)$obj2->MyCurrency, 'DBCurrency zero fields should be falsey on fetch from DB');
1978
    }
1979
1980
    public function testTwoSubclassesWithTheSameFieldNameWork()
1981
    {
1982
        // Create two objects of different subclasses, setting the values of fields that are
1983
        // defined separately in each subclass
1984
        $obj1 = new DataObjectTest\SubTeam();
1985
        $obj1->SubclassDatabaseField = "obj1";
0 ignored issues
show
Bug Best Practice introduced by
The property SubclassDatabaseField does not exist on SilverStripe\ORM\Tests\DataObjectTest\SubTeam. Since you implemented __set, consider adding a @property annotation.
Loading history...
1986
        $obj2 = new DataObjectTest\OtherSubclassWithSameField();
1987
        $obj2->SubclassDatabaseField = "obj2";
0 ignored issues
show
Bug Best Practice introduced by
The property SubclassDatabaseField does not exist on SilverStripe\ORM\Tests\D...erSubclassWithSameField. Since you implemented __set, consider adding a @property annotation.
Loading history...
1988
1989
        // Write them to the database
1990
        $obj1->write();
1991
        $obj2->write();
1992
1993
        // Check that the values of those fields are properly read from the database
1994
        $values = DataObject::get(
1995
            DataObjectTest\Team::class,
1996
            "\"DataObjectTest_Team\".\"ID\" IN
1997
			($obj1->ID, $obj2->ID)"
1998
        )->column("SubclassDatabaseField");
1999
        $this->assertEquals(array_intersect($values, array('obj1', 'obj2')), $values);
2000
    }
2001
2002
    public function testClassNameSetForNewObjects()
2003
    {
2004
        $d = new DataObjectTest\Player();
2005
        $this->assertEquals(DataObjectTest\Player::class, $d->ClassName);
2006
    }
2007
2008
    public function testHasValue()
2009
    {
2010
        $team = new DataObjectTest\Team();
2011
        $this->assertFalse($team->hasValue('Title', null, false));
2012
        $this->assertFalse($team->hasValue('DatabaseField', null, false));
2013
2014
        $team->Title = 'hasValue';
2015
        $this->assertTrue($team->hasValue('Title', null, false));
2016
        $this->assertFalse($team->hasValue('DatabaseField', null, false));
2017
2018
        $team->Title = '<p></p>';
2019
        $this->assertTrue(
2020
            $team->hasValue('Title', null, false),
2021
            'Test that an empty paragraph is a value for non-HTML fields.'
2022
        );
2023
2024
        $team->DatabaseField = 'hasValue';
2025
        $this->assertTrue($team->hasValue('Title', null, false));
2026
        $this->assertTrue($team->hasValue('DatabaseField', null, false));
2027
    }
2028
2029
    public function testHasMany()
2030
    {
2031
        $company = new DataObjectTest\Company();
2032
2033
        $this->assertEquals(
2034
            array(
2035
                'CurrentStaff' => DataObjectTest\Staff::class,
2036
                'PreviousStaff' => DataObjectTest\Staff::class
2037
            ),
2038
            $company->hasMany(),
2039
            'has_many strips field name data by default.'
2040
        );
2041
2042
        $this->assertEquals(
2043
            DataObjectTest\Staff::class,
2044
            DataObject::getSchema()->hasManyComponent(DataObjectTest\Company::class, 'CurrentStaff'),
2045
            'has_many strips field name data by default on single relationships.'
2046
        );
2047
2048
        $this->assertEquals(
2049
            array(
2050
                'CurrentStaff' => DataObjectTest\Staff::class . '.CurrentCompany',
2051
                'PreviousStaff' => DataObjectTest\Staff::class . '.PreviousCompany'
2052
            ),
2053
            $company->hasMany(false),
2054
            'has_many returns field name data when $classOnly is false.'
2055
        );
2056
2057
        $this->assertEquals(
2058
            DataObjectTest\Staff::class . '.CurrentCompany',
2059
            DataObject::getSchema()->hasManyComponent(DataObjectTest\Company::class, 'CurrentStaff', false),
2060
            'has_many returns field name data on single records when $classOnly is false.'
2061
        );
2062
    }
2063
2064
    public function testGetRemoteJoinField()
2065
    {
2066
        $schema = DataObject::getSchema();
2067
2068
        // Company schema
2069
        $staffJoinField = $schema->getRemoteJoinField(
2070
            DataObjectTest\Company::class,
2071
            'CurrentStaff',
2072
            'has_many',
2073
            $polymorphic
2074
        );
2075
        $this->assertEquals('CurrentCompanyID', $staffJoinField);
2076
        $this->assertFalse($polymorphic, 'DataObjectTest_Company->CurrentStaff is not polymorphic');
2077
        $previousStaffJoinField = $schema->getRemoteJoinField(
2078
            DataObjectTest\Company::class,
2079
            'PreviousStaff',
2080
            'has_many',
2081
            $polymorphic
2082
        );
2083
        $this->assertEquals('PreviousCompanyID', $previousStaffJoinField);
2084
        $this->assertFalse($polymorphic, 'DataObjectTest_Company->PreviousStaff is not polymorphic');
2085
2086
        // CEO Schema
2087
        $this->assertEquals(
2088
            'CEOID',
2089
            $schema->getRemoteJoinField(
2090
                DataObjectTest\CEO::class,
2091
                'Company',
2092
                'belongs_to',
2093
                $polymorphic
2094
            )
2095
        );
2096
        $this->assertFalse($polymorphic, 'DataObjectTest_CEO->Company is not polymorphic');
2097
        $this->assertEquals(
2098
            'PreviousCEOID',
2099
            $schema->getRemoteJoinField(
2100
                DataObjectTest\CEO::class,
2101
                'PreviousCompany',
2102
                'belongs_to',
2103
                $polymorphic
2104
            )
2105
        );
2106
        $this->assertFalse($polymorphic, 'DataObjectTest_CEO->PreviousCompany is not polymorphic');
2107
2108
        // Team schema
2109
        $this->assertEquals(
2110
            'Favourite',
2111
            $schema->getRemoteJoinField(
2112
                DataObjectTest\Team::class,
2113
                'Fans',
2114
                'has_many',
2115
                $polymorphic
2116
            )
2117
        );
2118
        $this->assertTrue($polymorphic, 'DataObjectTest_Team->Fans is polymorphic');
2119
        $this->assertEquals(
2120
            'TeamID',
2121
            $schema->getRemoteJoinField(
2122
                DataObjectTest\Team::class,
2123
                'Comments',
2124
                'has_many',
2125
                $polymorphic
2126
            )
2127
        );
2128
        $this->assertFalse($polymorphic, 'DataObjectTest_Team->Comments is not polymorphic');
2129
    }
2130
2131
    public function testBelongsTo()
2132
    {
2133
        $company = new DataObjectTest\Company();
2134
        $ceo = new DataObjectTest\CEO();
2135
2136
        $company->Name = 'New Company';
0 ignored issues
show
Bug Best Practice introduced by
The property Name does not exist on SilverStripe\ORM\Tests\DataObjectTest\Company. Since you implemented __set, consider adding a @property annotation.
Loading history...
2137
        $company->write();
2138
        $ceo->write();
2139
2140
        // Test belongs_to assignment
2141
        $company->CEOID = $ceo->ID;
0 ignored issues
show
Bug Best Practice introduced by
The property CEOID does not exist on SilverStripe\ORM\Tests\DataObjectTest\Company. Since you implemented __set, consider adding a @property annotation.
Loading history...
2142
        $company->write();
2143
2144
        $this->assertEquals($company->ID, $ceo->Company()->ID, 'belongs_to returns the right results.');
0 ignored issues
show
Bug introduced by
The method Company() does not exist on SilverStripe\ORM\Tests\DataObjectTest\CEO. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

2144
        $this->assertEquals($company->ID, $ceo->/** @scrutinizer ignore-call */ Company()->ID, 'belongs_to returns the right results.');
Loading history...
2145
2146
        // Test belongs_to can be infered via getNonReciprocalComponent
2147
        // Note: Will be returned as has_many since the belongs_to is ignored.
2148
        $this->assertListEquals(
2149
            [['Name' => 'New Company']],
2150
            $ceo->inferReciprocalComponent(DataObjectTest\Company::class, 'CEO')
0 ignored issues
show
Bug introduced by
It seems like $ceo->inferReciprocalCom...\Company::class, 'CEO') can also be of type SilverStripe\ORM\DataObject; however, parameter $list of SilverStripe\Dev\SapphireTest::assertListEquals() does only seem to accept SilverStripe\ORM\SS_List, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2150
            /** @scrutinizer ignore-type */ $ceo->inferReciprocalComponent(DataObjectTest\Company::class, 'CEO')
Loading history...
2151
        );
2152
2153
        // Test has_one to a belongs_to can be infered via getNonReciprocalComponent
2154
        $this->assertEquals(
2155
            $ceo->ID,
2156
            $company->inferReciprocalComponent(DataObjectTest\CEO::class, 'Company')->ID
0 ignored issues
show
Bug Best Practice introduced by
The property ID does not exist on SilverStripe\ORM\DataList. Since you implemented __get, consider adding a @property annotation.
Loading history...
2157
        );
2158
2159
        // Test automatic creation of class where no assigment exists
2160
        $ceo = new DataObjectTest\CEO();
2161
        $ceo->write();
2162
2163
        $this->assertTrue(
2164
            $ceo->Company() instanceof DataObjectTest\Company,
2165
            'DataObjects across belongs_to relations are automatically created.'
2166
        );
2167
        $this->assertEquals($ceo->ID, $ceo->Company()->CEOID, 'Remote IDs are automatically set.');
2168
2169
        // Write object with components
2170
        $ceo->Name = 'Edward Scissorhands';
0 ignored issues
show
Bug Best Practice introduced by
The property Name does not exist on SilverStripe\ORM\Tests\DataObjectTest\CEO. Since you implemented __set, consider adding a @property annotation.
Loading history...
2171
        $ceo->write(false, false, false, true);
2172
        $this->assertTrue($ceo->Company()->isInDB(), 'write() writes belongs_to components to the database.');
2173
2174
        $newCEO = DataObject::get_by_id(DataObjectTest\CEO::class, $ceo->ID);
2175
        $this->assertEquals(
2176
            $ceo->Company()->ID,
2177
            $newCEO->Company()->ID,
0 ignored issues
show
Bug introduced by
The method Company() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

2177
            $newCEO->/** @scrutinizer ignore-call */ 
2178
                     Company()->ID,
Loading history...
2178
            'belongs_to can be retrieved from the database.'
2179
        );
2180
    }
2181
2182
    public function testBelongsToPolymorphic()
2183
    {
2184
        $company = new DataObjectTest\Company();
2185
        $ceo = new DataObjectTest\CEO();
2186
2187
        $company->write();
2188
        $ceo->write();
2189
2190
        // Test belongs_to assignment
2191
        $company->OwnerID = $ceo->ID;
0 ignored issues
show
Bug Best Practice introduced by
The property OwnerID does not exist on SilverStripe\ORM\Tests\DataObjectTest\Company. Since you implemented __set, consider adding a @property annotation.
Loading history...
2192
        $company->OwnerClass = DataObjectTest\CEO::class;
0 ignored issues
show
Bug Best Practice introduced by
The property OwnerClass does not exist on SilverStripe\ORM\Tests\DataObjectTest\Company. Since you implemented __set, consider adding a @property annotation.
Loading history...
2193
        $company->write();
2194
2195
        $this->assertEquals($company->ID, $ceo->CompanyOwned()->ID, 'belongs_to returns the right results.');
0 ignored issues
show
Bug introduced by
The method CompanyOwned() does not exist on SilverStripe\ORM\Tests\DataObjectTest\CEO. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

2195
        $this->assertEquals($company->ID, $ceo->/** @scrutinizer ignore-call */ CompanyOwned()->ID, 'belongs_to returns the right results.');
Loading history...
2196
        $this->assertInstanceOf(
2197
            DataObjectTest\Company::class,
2198
            $ceo->CompanyOwned(),
2199
            'belongs_to returns the right results.'
2200
        );
2201
2202
        // Test automatic creation of class where no assigment exists
2203
        $ceo = new DataObjectTest\CEO();
2204
        $ceo->write();
2205
2206
        $this->assertTrue(
2207
            $ceo->CompanyOwned() instanceof DataObjectTest\Company,
2208
            'DataObjects across polymorphic belongs_to relations are automatically created.'
2209
        );
2210
        $this->assertEquals($ceo->ID, $ceo->CompanyOwned()->OwnerID, 'Remote IDs are automatically set.');
2211
        $this->assertInstanceOf($ceo->CompanyOwned()->OwnerClass, $ceo, 'Remote class is automatically  set');
2212
2213
        // Write object with components
2214
        $ceo->write(false, false, false, true);
2215
        $this->assertTrue($ceo->CompanyOwned()->isInDB(), 'write() writes belongs_to components to the database.');
2216
2217
        $newCEO = DataObject::get_by_id(DataObjectTest\CEO::class, $ceo->ID);
2218
        $this->assertEquals(
2219
            $ceo->CompanyOwned()->ID,
2220
            $newCEO->CompanyOwned()->ID,
0 ignored issues
show
Bug introduced by
The method CompanyOwned() does not exist on SilverStripe\ORM\DataObject. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

2220
            $newCEO->/** @scrutinizer ignore-call */ 
2221
                     CompanyOwned()->ID,
Loading history...
2221
            'polymorphic belongs_to can be retrieved from the database.'
2222
        );
2223
    }
2224
2225
    /**
2226
     * @expectedException LogicException
2227
     */
2228
    public function testInvalidate()
2229
    {
2230
        $do = new DataObjectTest\Fixture();
2231
        $do->write();
2232
2233
        $do->delete();
2234
2235
        $do->delete(); // Prohibit invalid object manipulation
2236
        $do->write();
2237
        $do->duplicate();
2238
    }
2239
2240
    public function testToMap()
2241
    {
2242
        $obj = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam1');
2243
2244
        $map = $obj->toMap();
2245
2246
        $this->assertArrayHasKey('ID', $map, 'Contains base fields');
2247
        $this->assertArrayHasKey('Title', $map, 'Contains fields from parent class');
2248
        $this->assertArrayHasKey('SubclassDatabaseField', $map, 'Contains fields from concrete class');
2249
2250
        $this->assertEquals(
2251
            $obj->ID,
2252
            $map['ID'],
2253
            'Contains values from base fields'
2254
        );
2255
        $this->assertEquals(
2256
            $obj->Title,
2257
            $map['Title'],
2258
            'Contains values from parent class fields'
2259
        );
2260
        $this->assertEquals(
2261
            $obj->SubclassDatabaseField,
0 ignored issues
show
Bug Best Practice introduced by
The property SubclassDatabaseField does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
2262
            $map['SubclassDatabaseField'],
2263
            'Contains values from concrete class fields'
2264
        );
2265
2266
        $newObj = new DataObjectTest\SubTeam();
0 ignored issues
show
Unused Code introduced by
The assignment to $newObj is dead and can be removed.
Loading history...
2267
        $this->assertArrayHasKey('Title', $map, 'Contains null fields');
2268
    }
2269
2270
    public function testIsEmpty()
2271
    {
2272
        $objEmpty = new DataObjectTest\Team();
2273
        $this->assertTrue($objEmpty->isEmpty(), 'New instance without populated defaults is empty');
2274
2275
        $objEmpty->Title = '0'; //
2276
        $this->assertFalse($objEmpty->isEmpty(), 'Zero value in attribute considered non-empty');
2277
    }
2278
2279
    public function testRelField()
2280
    {
2281
        $captain1 = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
2282
        // Test traversal of a single has_one
2283
        $this->assertEquals("Team 1", $captain1->relField('FavouriteTeam.Title'));
2284
        // Test direct field access
2285
        $this->assertEquals("Captain", $captain1->relField('FirstName'));
2286
2287
        // Test empty link
2288
        $captain2 = $this->objFromFixture(DataObjectTest\Player::class, 'captain2');
2289
        $this->assertEmpty($captain2->relField('FavouriteTeam.Title'));
2290
        $this->assertNull($captain2->relField('FavouriteTeam.ReturnsNull'));
2291
        $this->assertNull($captain2->relField('FavouriteTeam.ReturnsNull.Title'));
2292
2293
        $player = $this->objFromFixture(DataObjectTest\Player::class, 'player2');
2294
        // Test that we can traverse more than once, and that arbitrary methods are okay
2295
        $this->assertEquals("Team 1", $player->relField('Teams.First.Title'));
2296
2297
        $newPlayer = new DataObjectTest\Player();
2298
        $this->assertNull($newPlayer->relField('Teams.First.Title'));
2299
2300
        // Test that relField works on db field manipulations
2301
        $comment = $this->objFromFixture(DataObjectTest\TeamComment::class, 'comment3');
2302
        $this->assertEquals("PHIL IS A UNIQUE GUY, AND COMMENTS ON TEAM2", $comment->relField('Comment.UpperCase'));
2303
2304
        // relField throws exception on invalid properties
2305
        $this->expectException(LogicException::class);
2306
        $this->expectExceptionMessage("Not is not a relation/field on " . DataObjectTest\TeamComment::class);
2307
        $comment->relField('Not.A.Field');
2308
    }
2309
2310
    public function testRelObject()
2311
    {
2312
        $captain1 = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
2313
2314
        // Test traversal of a single has_one
2315
        $this->assertInstanceOf(DBVarchar::class, $captain1->relObject('FavouriteTeam.Title'));
2316
        $this->assertEquals("Team 1", $captain1->relObject('FavouriteTeam.Title')->getValue());
2317
2318
        // Test empty link
2319
        $captain2 = $this->objFromFixture(DataObjectTest\Player::class, 'captain2');
2320
        $this->assertEmpty($captain2->relObject('FavouriteTeam.Title')->getValue());
2321
        $this->assertNull($captain2->relObject('FavouriteTeam.ReturnsNull.Title'));
2322
2323
        // Test direct field access
2324
        $this->assertInstanceOf(DBBoolean::class, $captain1->relObject('IsRetired'));
2325
        $this->assertEquals(1, $captain1->relObject('IsRetired')->getValue());
2326
2327
        $player = $this->objFromFixture(DataObjectTest\Player::class, 'player2');
2328
        // Test that we can traverse more than once, and that arbitrary methods are okay
2329
        $this->assertInstanceOf(DBVarchar::class, $player->relObject('Teams.First.Title'));
2330
        $this->assertEquals("Team 1", $player->relObject('Teams.First.Title')->getValue());
2331
2332
        // relObject throws exception on invalid properties
2333
        $this->expectException(LogicException::class);
2334
        $this->expectExceptionMessage("Not is not a relation/field on " . DataObjectTest\Player::class);
2335
        $player->relObject('Not.A.Field');
2336
    }
2337
2338
    public function testLateStaticBindingStyle()
2339
    {
2340
        // Confirm that DataObjectTest_Player::get() operates as excepted
2341
        $this->assertEquals(4, DataObjectTest\Player::get()->count());
2342
        $this->assertInstanceOf(DataObjectTest\Player::class, DataObjectTest\Player::get()->first());
2343
2344
        // You can't pass arguments to LSB syntax - use the DataList methods instead.
2345
        $this->expectException(InvalidArgumentException::class);
2346
2347
        DataObjectTest\Player::get(null, "\"ID\" = 1");
2348
    }
2349
2350
    /**
2351
     * @expectedException \InvalidArgumentException
2352
     */
2353
    public function testBrokenLateStaticBindingStyle()
2354
    {
2355
        // If you call DataObject::get() you have to pass a first argument
2356
        DataObject::get();
2357
    }
2358
2359
    public function testBigIntField()
2360
    {
2361
        $staff = new DataObjectTest\Staff();
2362
        $staff->Salary = PHP_INT_MAX;
0 ignored issues
show
Bug Best Practice introduced by
The property Salary does not exist on SilverStripe\ORM\Tests\DataObjectTest\Staff. Since you implemented __set, consider adding a @property annotation.
Loading history...
2363
        $staff->write();
2364
        $this->assertEquals(PHP_INT_MAX, DataObjectTest\Staff::get()->byID($staff->ID)->Salary);
0 ignored issues
show
Bug Best Practice introduced by
The property Salary does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
2365
    }
2366
2367
    public function testGetOneMissingValueReturnsNull()
2368
    {
2369
2370
        // Test that missing values return null
2371
        $this->assertEquals(null, DataObject::get_one(
2372
            DataObjectTest\TeamComment::class,
2373
            ['"DataObjectTest_TeamComment"."Name"' => 'does not exists']
2374
        ));
2375
    }
2376
2377
    public function testSetFieldWithArrayOnScalarOnlyField()
2378
    {
2379
        $this->expectException(InvalidArgumentException::class);
2380
        $do = Company::singleton();
2381
        $do->FoundationYear = '1984';
2382
        $do->FoundationYear = array('Amount' => 123, 'Currency' => 'CAD');
2383
        $this->assertEmpty($do->FoundationYear);
2384
    }
2385
2386
    public function testSetFieldWithArrayOnCompositeField()
2387
    {
2388
        $do = Company::singleton();
2389
        $do->SalaryCap = array('Amount' => 123456, 'Currency' => 'CAD');
2390
        $this->assertNotEmpty($do->SalaryCap);
2391
    }
2392
2393
    public function testWriteManipulationWithNonScalarValuesAllowed()
2394
    {
2395
        $do = DataObjectTest\MockDynamicAssignmentDataObject::create();
2396
        $do->write();
2397
2398
        $do->StaticScalarOnlyField = true;
2399
        $do->DynamicScalarOnlyField = false;
2400
        $do->DynamicField = true;
2401
2402
        $do->write();
2403
2404
        $this->assertTrue($do->StaticScalarOnlyField);
2405
        $this->assertFalse($do->DynamicScalarOnlyField);
2406
        $this->assertTrue($do->DynamicField);
2407
    }
2408
2409
    public function testWriteManipulationWithNonScalarValuesDisallowed()
2410
    {
2411
        $this->expectException(InvalidArgumentException::class);
2412
2413
        $do = DataObjectTest\MockDynamicAssignmentDataObject::create();
2414
        $do->write();
2415
2416
        $do->StaticScalarOnlyField = false;
2417
        $do->DynamicScalarOnlyField = true;
2418
        $do->DynamicField = false;
2419
2420
        $do->write();
2421
    }
2422
2423
    public function testRecursiveWrite()
2424
    {
2425
2426
        $root = $this->objFromFixture(TreeNode::class, 'root');
2427
        $child = $this->objFromFixture(TreeNode::class, 'child');
2428
        $grandchild = $this->objFromFixture(TreeNode::class, 'grandchild');
2429
2430
        // Create a cycle ... this will test that we can't create an infinite loop
2431
        $root->CycleID = $grandchild->ID;
0 ignored issues
show
Bug Best Practice introduced by
The property CycleID does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
2432
        $root->write();
2433
2434
        // Our count will have been set while loading our fixtures, let's reset eveything back to 0
2435
        TreeNode::singleton()->resetCounts();
2436
        $root = TreeNode::get()->byID($root->ID);
2437
        $child = TreeNode::get()->byID($child->ID);
2438
        $grandchild = TreeNode::get()->byID($grandchild->ID);
2439
        $this->assertEquals(0, $root->WriteCount, 'Root node write count has been reset');
0 ignored issues
show
Bug Best Practice introduced by
The property WriteCount does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
2440
        $this->assertEquals(0, $child->WriteCount, 'Child node write count has been reset');
2441
        $this->assertEquals(0, $grandchild->WriteCount, 'Grand Child node write count has been reset');
2442
2443
        // Trigger a recursive write of the grand children
2444
        $grandchild->write(false, false, false, true);
2445
2446
        // Reload the DataObject from the DB to get the new Write Counts
2447
        $root = TreeNode::get()->byID($root->ID);
2448
        $child = TreeNode::get()->byID($child->ID);
2449
        $grandchild = TreeNode::get()->byID($grandchild->ID);
2450
2451
        $this->assertEquals(
2452
            1,
2453
            $grandchild->WriteCount,
2454
            'Grand child has been written once because write was directly called on it'
2455
        );
2456
        $this->assertEquals(
2457
            1,
2458
            $child->WriteCount,
2459
            'Child should has been written once because it is directly related to grand child'
2460
        );
2461
        $this->assertEquals(
2462
            1,
2463
            $root->WriteCount,
2464
            'Root should have been written once because it is indirectly related to grand child'
2465
        );
2466
    }
2467
2468
    public function testShallowRecursiveWrite()
2469
    {
2470
        $root = $this->objFromFixture(TreeNode::class, 'root');
2471
        $child = $this->objFromFixture(TreeNode::class, 'child');
2472
        $grandchild = $this->objFromFixture(TreeNode::class, 'grandchild');
2473
2474
        // Create a cycle ... this will test that we can't create an infinite loop
2475
        $root->CycleID = $grandchild->ID;
0 ignored issues
show
Bug Best Practice introduced by
The property CycleID does not exist on SilverStripe\ORM\DataObject. Since you implemented __set, consider adding a @property annotation.
Loading history...
2476
        $root->write();
2477
2478
        // Our count will have been set while loading our fixtures, let's reset eveything back to 0
2479
        TreeNode::singleton()->resetCounts();
2480
        $root = TreeNode::get()->byID($root->ID);
2481
        $child = TreeNode::get()->byID($child->ID);
2482
        $grandchild = TreeNode::get()->byID($grandchild->ID);
2483
        $this->assertEquals(0, $root->WriteCount);
0 ignored issues
show
Bug Best Practice introduced by
The property WriteCount does not exist on SilverStripe\ORM\DataObject. Since you implemented __get, consider adding a @property annotation.
Loading history...
2484
        $this->assertEquals(0, $child->WriteCount);
2485
        $this->assertEquals(0, $grandchild->WriteCount);
2486
2487
        // Recursively only affect component that have been loaded
2488
        $grandchild->write(false, false, false, ['recursive' => false]);
2489
2490
        // Reload the DataObject from the DB to get the new Write Counts
2491
        $root = TreeNode::get()->byID($root->ID);
2492
        $child = TreeNode::get()->byID($child->ID);
2493
        $grandchild = TreeNode::get()->byID($grandchild->ID);
2494
2495
        $this->assertEquals(
2496
            1,
2497
            $grandchild->WriteCount,
2498
            'Grand child was written once because write was directly called on it'
2499
        );
2500
        $this->assertEquals(
2501
            1,
2502
            $child->WriteCount,
2503
            'Child was written once because it is directly related grand child'
2504
        );
2505
        $this->assertEquals(
2506
            0,
2507
            $root->WriteCount,
2508
            'Root is 2 step remove from grand children. It was not written on a shallow recursive write.'
2509
        );
2510
    }
2511
}
2512