Passed
Push — less-original ( 2e1bf4...c19c33 )
by Sam
05:19
created

testFieldNamesThatMatchMethodNamesWork()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 15
nc 1
nop 0
dl 0
loc 21
rs 9.7666
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\Player;
21
use SilverStripe\View\ViewableData;
22
use stdClass;
23
24
class DataObjectTest extends SapphireTest
25
{
26
27
    protected static $fixture_file = 'DataObjectTest.yml';
28
29
    /**
30
     * Standard set of dataobject test classes
31
     *
32
     * @var array
33
     */
34
    public static $extra_data_objects = array(
35
        DataObjectTest\Team::class,
36
        DataObjectTest\Fixture::class,
37
        DataObjectTest\SubTeam::class,
38
        DataObjectTest\OtherSubclassWithSameField::class,
39
        DataObjectTest\FieldlessTable::class,
40
        DataObjectTest\FieldlessSubTable::class,
41
        DataObjectTest\ValidatedObject::class,
42
        DataObjectTest\Player::class,
43
        DataObjectTest\TeamComment::class,
44
        DataObjectTest\EquipmentCompany::class,
45
        DataObjectTest\SubEquipmentCompany::class,
46
        DataObjectTest\ExtendedTeamComment::class,
47
        DataObjectTest\Company::class,
48
        DataObjectTest\Staff::class,
49
        DataObjectTest\CEO::class,
50
        DataObjectTest\Fan::class,
51
        DataObjectTest\Play::class,
52
        DataObjectTest\Ploy::class,
53
        DataObjectTest\Bogey::class,
54
        DataObjectTest\Sortable::class,
55
        DataObjectTest\Bracket::class,
56
        DataObjectTest\RelationParent::class,
57
        DataObjectTest\RelationChildFirst::class,
58
        DataObjectTest\RelationChildSecond::class,
59
    );
60
61
    public static function getExtraDataObjects()
62
    {
63
        return array_merge(
64
            DataObjectTest::$extra_data_objects,
65
            ManyManyListTest::$extra_data_objects
66
        );
67
    }
68
69
    public function testDb()
70
    {
71
        $schema = DataObject::getSchema();
72
        $dbFields = $schema->fieldSpecs(DataObjectTest\TeamComment::class);
73
74
        // Assert fields are included
75
        $this->assertArrayHasKey('Name', $dbFields);
76
77
        // Assert the base fields are included
78
        $this->assertArrayHasKey('Created', $dbFields);
79
        $this->assertArrayHasKey('LastEdited', $dbFields);
80
        $this->assertArrayHasKey('ClassName', $dbFields);
81
        $this->assertArrayHasKey('ID', $dbFields);
82
83
        // Assert that the correct field type is returned when passing a field
84
        $this->assertEquals('Varchar', $schema->fieldSpec(DataObjectTest\TeamComment::class, 'Name'));
85
        $this->assertEquals('Text', $schema->fieldSpec(DataObjectTest\TeamComment::class, 'Comment'));
86
87
        // Test with table required
88
        $this->assertEquals(
89
            DataObjectTest\TeamComment::class . '.Varchar',
90
            $schema->fieldSpec(DataObjectTest\TeamComment::class, 'Name', DataObjectSchema::INCLUDE_CLASS)
91
        );
92
        $this->assertEquals(
93
            DataObjectTest\TeamComment::class . '.Text',
94
            $schema->fieldSpec(DataObjectTest\TeamComment::class, 'Comment', DataObjectSchema::INCLUDE_CLASS)
95
        );
96
        $dbFields = $schema->fieldSpecs(DataObjectTest\ExtendedTeamComment::class);
97
98
        // fixed fields are still included in extended classes
99
        $this->assertArrayHasKey('Created', $dbFields);
100
        $this->assertArrayHasKey('LastEdited', $dbFields);
101
        $this->assertArrayHasKey('ClassName', $dbFields);
102
        $this->assertArrayHasKey('ID', $dbFields);
103
104
        // Assert overloaded fields have correct data type
105
        $this->assertEquals('HTMLText', $schema->fieldSpec(DataObjectTest\ExtendedTeamComment::class, 'Comment'));
106
        $this->assertEquals(
107
            'HTMLText',
108
            $dbFields['Comment'],
109
            'Calls to DataObject::db without a field specified return correct data types'
110
        );
111
112
        // assertEquals doesn't verify the order of array elements, so access keys manually to check order:
113
        // expected: array('Name' => 'Varchar', 'Comment' => 'HTMLText')
114
        $this->assertEquals(
115
            array(
116
                'Name',
117
                'Comment'
118
            ),
119
            array_slice(array_keys($dbFields), 4, 2),
120
            'DataObject::db returns fields in correct order'
121
        );
122
    }
123
124
    public function testConstructAcceptsValues()
125
    {
126
        // Values can be an array...
127
        $player = new DataObjectTest\Player(
128
            array(
129
                'FirstName' => 'James',
130
                'Surname' => 'Smith'
131
            )
132
        );
133
134
        $this->assertEquals('James', $player->FirstName);
135
        $this->assertEquals('Smith', $player->Surname);
136
137
        // ... or a stdClass inst
138
        $data = new stdClass();
139
        $data->FirstName = 'John';
140
        $data->Surname = 'Doe';
141
        $player = new DataObjectTest\Player($data);
0 ignored issues
show
Bug introduced by
$data of type stdClass is incompatible with the type null|array 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

141
        $player = new DataObjectTest\Player(/** @scrutinizer ignore-type */ $data);
Loading history...
142
143
        $this->assertEquals('John', $player->FirstName);
144
        $this->assertEquals('Doe', $player->Surname);
145
146
        // IDs should be stored as integers, not strings
147
        $player = new DataObjectTest\Player(array('ID' => '5'));
148
        $this->assertSame(5, $player->ID);
149
    }
150
151
    public function testValidObjectsForBaseFields()
152
    {
153
        $obj = new DataObjectTest\ValidatedObject();
154
155
        foreach (array('Created', 'LastEdited', 'ClassName', 'ID') as $field) {
156
            $helper = $obj->dbObject($field);
157
            $this->assertTrue(
158
                ($helper instanceof DBField),
159
                "for {$field} expected helper to be DBField, but was " . (is_object($helper) ? get_class($helper) : "null")
160
            );
161
        }
162
    }
163
164
    public function testDataIntegrityWhenTwoSubclassesHaveSameField()
165
    {
166
        // Save data into DataObjectTest_SubTeam.SubclassDatabaseField
167
        $obj = new DataObjectTest\SubTeam();
168
        $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...
169
        $obj->write();
170
171
        // Change the class
172
        $obj->ClassName = DataObjectTest\OtherSubclassWithSameField::class;
173
        $obj->write();
174
        $obj->flushCache();
175
176
        // Re-fetch from the database and confirm that the data is sourced from
177
        // OtherSubclassWithSameField.SubclassDatabaseField
178
        $obj = DataObject::get_by_id(DataObjectTest\Team::class, $obj->ID);
179
        $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...
180
181
        // Confirm that save the object in the other direction.
182
        $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...
183
        $obj->write();
184
185
        $obj->ClassName = DataObjectTest\SubTeam::class;
186
        $obj->write();
187
        $obj->flushCache();
188
189
        // If we restore the class, the old value has been lying dormant and will be available again.
190
        // NOTE: This behaviour is volatile; we may change this in the future to clear fields that
191
        // are no longer relevant when changing ClassName
192
        $obj = DataObject::get_by_id(DataObjectTest\Team::class, $obj->ID);
193
        $this->assertEquals('obj-SubTeam', $obj->SubclassDatabaseField);
194
    }
195
196
    /**
197
     * Test deletion of DataObjects
198
     *   - Deleting using delete() on the DataObject
199
     *   - Deleting using DataObject::delete_by_id()
200
     */
201
    public function testDelete()
202
    {
203
        // Test deleting using delete() on the DataObject
204
        // Get the first page
205
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
206
        $objID = $obj->ID;
207
        // Check the page exists before deleting
208
        $this->assertTrue(is_object($obj) && $obj->exists());
209
        // Delete the page
210
        $obj->delete();
211
        // Check that page does not exist after deleting
212
        $obj = DataObject::get_by_id(DataObjectTest\Player::class, $objID);
213
        $this->assertTrue(!$obj || !$obj->exists());
214
215
216
        // Test deleting using DataObject::delete_by_id()
217
        // Get the second page
218
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain2');
219
        $objID = $obj->ID;
220
        // Check the page exists before deleting
221
        $this->assertTrue(is_object($obj) && $obj->exists());
222
        // Delete the page
223
        DataObject::delete_by_id(DataObjectTest\Player::class, $obj->ID);
224
        // Check that page does not exist after deleting
225
        $obj = DataObject::get_by_id(DataObjectTest\Player::class, $objID);
226
        $this->assertTrue(!$obj || !$obj->exists());
227
    }
228
229
    /**
230
     * Test methods that get DataObjects
231
     *   - DataObject::get()
232
     *       - All records of a DataObject
233
     *       - Filtering
234
     *       - Sorting
235
     *       - Joins
236
     *       - Limit
237
     *       - Container class
238
     *   - DataObject::get_by_id()
239
     *   - DataObject::get_one()
240
     *        - With and without caching
241
     *        - With and without ordering
242
     */
243
    public function testGet()
244
    {
245
        // Test getting all records of a DataObject
246
        $comments = DataObject::get(DataObjectTest\TeamComment::class);
247
        $this->assertEquals(3, $comments->count());
248
249
        // Test WHERE clause
250
        $comments = DataObject::get(DataObjectTest\TeamComment::class, "\"Name\"='Bob'");
251
        $this->assertEquals(1, $comments->count());
252
        foreach ($comments as $comment) {
253
            $this->assertEquals('Bob', $comment->Name);
254
        }
255
256
        // Test sorting
257
        $comments = DataObject::get(DataObjectTest\TeamComment::class, '', "\"Name\" ASC");
258
        $this->assertEquals(3, $comments->count());
259
        $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...
260
        $comments = DataObject::get(DataObjectTest\TeamComment::class, '', "\"Name\" DESC");
261
        $this->assertEquals(3, $comments->count());
262
        $this->assertEquals('Phil', $comments->first()->Name);
263
264
        // Test limit
265
        $comments = DataObject::get(DataObjectTest\TeamComment::class, '', "\"Name\" ASC", '', '1,2');
266
        $this->assertEquals(2, $comments->count());
267
        $this->assertEquals('Joe', $comments->first()->Name);
268
        $this->assertEquals('Phil', $comments->last()->Name);
269
270
        // Test get_by_id()
271
        $captain1ID = $this->idFromFixture(DataObjectTest\Player::class, 'captain1');
272
        $captain1 = DataObject::get_by_id(DataObjectTest\Player::class, $captain1ID);
273
        $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...
274
275
        // Test get_one() without caching
276
        $comment1 = DataObject::get_one(
277
            DataObjectTest\TeamComment::class,
278
            array(
279
                '"DataObjectTest_TeamComment"."Name"' => 'Joe'
280
            ),
281
            false
282
        );
283
        $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...
284
285
        $comment2 = DataObject::get_one(
286
            DataObjectTest\TeamComment::class,
287
            array(
288
                '"DataObjectTest_TeamComment"."Name"' => 'Joe'
289
            ),
290
            false
291
        );
292
        $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...
293
294
        // Test get_one() with caching
295
        $comment1 = DataObject::get_one(
296
            DataObjectTest\TeamComment::class,
297
            array(
298
                '"DataObjectTest_TeamComment"."Name"' => 'Bob'
299
            ),
300
            true
301
        );
302
        $comment1->Comment = "Something Else";
303
304
        $comment2 = DataObject::get_one(
305
            DataObjectTest\TeamComment::class,
306
            array(
307
                '"DataObjectTest_TeamComment"."Name"' => 'Bob'
308
            ),
309
            true
310
        );
311
        $this->assertEquals((string)$comment1->Comment, (string)$comment2->Comment);
312
313
        // Test get_one() with order by without caching
314
        $comment = DataObject::get_one(DataObjectTest\TeamComment::class, '', false, "\"Name\" ASC");
315
        $this->assertEquals('Bob', $comment->Name);
316
317
        $comment = DataObject::get_one(DataObjectTest\TeamComment::class, '', false, "\"Name\" DESC");
318
        $this->assertEquals('Phil', $comment->Name);
319
320
        // Test get_one() with order by with caching
321
        $comment = DataObject::get_one(DataObjectTest\TeamComment::class, '', true, '"Name" ASC');
322
        $this->assertEquals('Bob', $comment->Name);
323
        $comment = DataObject::get_one(DataObjectTest\TeamComment::class, '', true, '"Name" DESC');
324
        $this->assertEquals('Phil', $comment->Name);
325
    }
326
327
    public function testGetByIDCallerClass()
328
    {
329
        $captain1ID = $this->idFromFixture(DataObjectTest\Player::class, 'captain1');
330
        $captain1 = DataObjectTest\Player::get_by_id($captain1ID);
331
        $this->assertInstanceOf(DataObjectTest\Player::class, $captain1);
332
        $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...
333
334
        $captain2ID = $this->idFromFixture(DataObjectTest\Player::class, 'captain2');
335
        // make sure we can call from any class but get the one passed as an argument
336
        $captain2 = DataObjectTest\TeamComment::get_by_id(DataObjectTest\Player::class, $captain2ID);
337
        $this->assertInstanceOf(DataObjectTest\Player::class, $captain2);
338
        $this->assertEquals('Captain 2', $captain2->FirstName);
339
    }
340
341
    public function testGetCaseInsensitive()
342
    {
343
        // Test get_one() with bad case on the classname
344
        // Note: This will succeed only if the underlying DB server supports case-insensitive
345
        // table names (e.g. such as MySQL, but not SQLite3)
346
        if (!(DB::get_conn() instanceof MySQLDatabase)) {
347
            $this->markTestSkipped('MySQL only');
348
        }
349
350
        $subteam1 = DataObject::get_one(
351
            strtolower(DataObjectTest\SubTeam::class),
352
            array(
353
                '"DataObjectTest_Team"."Title"' => 'Subteam 1'
354
            ),
355
            true
356
        );
357
        $this->assertNotEmpty($subteam1);
358
        $this->assertEquals($subteam1->Title, "Subteam 1");
359
    }
360
361
    public function testGetSubclassFields()
362
    {
363
        /* Test that fields / has_one relations from the parent table and the subclass tables are extracted */
364
        $captain1 = $this->objFromFixture(DataObjectTest\Player::class, "captain1");
365
        // Base field
366
        $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...
367
        // Subclass field
368
        $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...
369
        // Subclass has_one relation
370
        $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...
371
    }
372
373
    public function testGetRelationClass()
374
    {
375
        $obj = new DataObjectTest\Player();
0 ignored issues
show
Unused Code introduced by
The assignment to $obj is dead and can be removed.
Loading history...
376
        $this->assertEquals(
377
            singleton(DataObjectTest\Player::class)->getRelationClass('FavouriteTeam'),
378
            DataObjectTest\Team::class,
379
            'has_one is properly inspected'
380
        );
381
        $this->assertEquals(
382
            singleton(DataObjectTest\Company::class)->getRelationClass('CurrentStaff'),
383
            DataObjectTest\Staff::class,
384
            'has_many is properly inspected'
385
        );
386
        $this->assertEquals(
387
            singleton(DataObjectTest\Team::class)->getRelationClass('Players'),
388
            DataObjectTest\Player::class,
389
            'many_many is properly inspected'
390
        );
391
        $this->assertEquals(
392
            singleton(DataObjectTest\Player::class)->getRelationClass('Teams'),
393
            DataObjectTest\Team::class,
394
            'belongs_many_many is properly inspected'
395
        );
396
        $this->assertEquals(
397
            singleton(DataObjectTest\CEO::class)->getRelationClass('Company'),
398
            DataObjectTest\Company::class,
399
            'belongs_to is properly inspected'
400
        );
401
        $this->assertEquals(
402
            singleton(DataObjectTest\Fan::class)->getRelationClass('Favourite'),
403
            DataObject::class,
404
            'polymorphic has_one is properly inspected'
405
        );
406
    }
407
408
    /**
409
     * Test that has_one relations can be retrieved
410
     */
411
    public function testGetHasOneRelations()
412
    {
413
        $captain1 = $this->objFromFixture(DataObjectTest\Player::class, "captain1");
414
        $team1ID = $this->idFromFixture(DataObjectTest\Team::class, 'team1');
415
416
        // There will be a field called (relname)ID that contains the ID of the
417
        // object linked to via the has_one relation
418
        $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...
419
420
        // There will be a method called $obj->relname() that returns the object itself
421
        $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

421
        $this->assertEquals($team1ID, $captain1->/** @scrutinizer ignore-call */ FavouriteTeam()->ID);
Loading history...
422
423
        // Test that getNonReciprocalComponent can find has_one from the has_many end
424
        $this->assertEquals(
425
            $team1ID,
426
            $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...
427
        );
428
429
        // Check entity with polymorphic has-one
430
        $fan1 = $this->objFromFixture(DataObjectTest\Fan::class, "fan1");
431
        $this->assertTrue((bool)$fan1->hasValue('Favourite'));
432
433
        // There will be fields named (relname)ID and (relname)Class for polymorphic
434
        // entities
435
        $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...
436
        $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...
437
438
        // There will be a method called $obj->relname() that returns the object itself
439
        $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

439
        /** @scrutinizer ignore-call */ 
440
        $favourite = $fan1->Favourite();
Loading history...
440
        $this->assertEquals($team1ID, $favourite->ID);
441
        $this->assertInstanceOf(DataObjectTest\Team::class, $favourite);
442
443
        // check behaviour of dbObject with polymorphic relations
444
        $favouriteDBObject = $fan1->dbObject('Favourite');
445
        $favouriteValue = $favouriteDBObject->getValue();
446
        $this->assertInstanceOf(DBPolymorphicForeignKey::class, $favouriteDBObject);
447
        $this->assertEquals($favourite->ID, $favouriteValue->ID);
448
        $this->assertEquals($favourite->ClassName, $favouriteValue->ClassName);
449
    }
450
451
    public function testLimitAndCount()
452
    {
453
        $players = DataObject::get(DataObjectTest\Player::class);
454
455
        // There's 4 records in total
456
        $this->assertEquals(4, $players->count());
457
458
        // Testing "##, ##" syntax
459
        $this->assertEquals(4, $players->limit(20)->count());
460
        $this->assertEquals(4, $players->limit(20, 0)->count());
461
        $this->assertEquals(0, $players->limit(20, 20)->count());
462
        $this->assertEquals(2, $players->limit(2, 0)->count());
463
        $this->assertEquals(1, $players->limit(5, 3)->count());
464
    }
465
466
    public function testWriteNoChangesDoesntUpdateLastEdited()
467
    {
468
        // set mock now so we can be certain of LastEdited time for our test
469
        DBDatetime::set_mock_now('2017-01-01 00:00:00');
470
        $obj = new Player();
471
        $obj->FirstName = 'Test';
472
        $obj->Surname = 'Plater';
473
        $obj->Email = '[email protected]';
474
        $obj->write();
475
        $this->assertEquals('2017-01-01 00:00:00', $obj->LastEdited);
476
        $writtenObj = Player::get()->byID($obj->ID);
477
        $this->assertEquals('2017-01-01 00:00:00', $writtenObj->LastEdited);
478
479
        // set mock now so we get a new LastEdited if, for some reason, it's updated
480
        DBDatetime::set_mock_now('2017-02-01 00:00:00');
481
        $writtenObj->write();
482
        $this->assertEquals('2017-01-01 00:00:00', $writtenObj->LastEdited);
483
        $this->assertEquals($obj->ID, $writtenObj->ID);
484
485
        $reWrittenObj = Player::get()->byID($writtenObj->ID);
486
        $this->assertEquals('2017-01-01 00:00:00', $reWrittenObj->LastEdited);
487
    }
488
489
    /**
490
     * Test writing of database columns which don't correlate to a DBField,
491
     * e.g. all relation fields on has_one/has_many like "ParentID".
492
     */
493
    public function testWritePropertyWithoutDBField()
494
    {
495
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
496
        $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...
497
        $obj->write();
498
499
        // reload the page from the database
500
        $savedObj = DataObject::get_by_id(DataObjectTest\Player::class, $obj->ID);
501
        $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...
502
503
        // Test with porymorphic relation
504
        $obj2 = $this->objFromFixture(DataObjectTest\Fan::class, "fan1");
505
        $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...
506
        $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...
507
        $obj2->write();
508
509
        $savedObj2 = DataObject::get_by_id(DataObjectTest\Fan::class, $obj2->ID);
510
        $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...
511
        $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...
512
    }
513
514
    /**
515
     * Test has many relationships
516
     *   - Test getComponents() gets the ComponentSet of the other side of the relation
517
     *   - Test the IDs on the DataObjects are set correctly
518
     */
519
    public function testHasManyRelationships()
520
    {
521
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
522
523
        // Test getComponents() gets the ComponentSet of the other side of the relation
524
        $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

524
        $this->assertTrue($team1->/** @scrutinizer ignore-call */ Comments()->count() == 2);
Loading history...
525
526
        $team1Comments = [
527
            ['Comment' => 'This is a team comment by Joe'],
528
            ['Comment' => 'This is a team comment by Bob'],
529
        ];
530
531
        // Test the IDs on the DataObjects are set correctly
532
        $this->assertListEquals($team1Comments, $team1->Comments());
533
534
        // Test that has_many can be infered from the has_one via getNonReciprocalComponent
535
        $this->assertListEquals(
536
            $team1Comments,
537
            $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

537
            /** @scrutinizer ignore-type */ $team1->inferReciprocalComponent(DataObjectTest\TeamComment::class, 'Team')
Loading history...
538
        );
539
540
        // Test that we can add and remove items that already exist in the database
541
        $newComment = new DataObjectTest\TeamComment();
542
        $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...
543
        $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...
544
        $newComment->write();
545
        $team1->Comments()->add($newComment);
546
        $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...
547
548
        $comment1 = $this->objFromFixture(DataObjectTest\TeamComment::class, 'comment1');
549
        $comment2 = $this->objFromFixture(DataObjectTest\TeamComment::class, 'comment2');
550
        $team1->Comments()->remove($comment2);
551
552
        $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

552
        $team1CommentIDs = $team1->Comments()->/** @scrutinizer ignore-call */ sort('ID')->column('ID');
Loading history...
553
        $this->assertEquals(array($comment1->ID, $newComment->ID), $team1CommentIDs);
554
555
        // Test that removing an item from a list doesn't remove it from the same
556
        // relation belonging to a different object
557
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
558
        $team2 = $this->objFromFixture(DataObjectTest\Team::class, 'team2');
559
        $team2->Comments()->remove($comment1);
560
        $team1CommentIDs = $team1->Comments()->sort('ID')->column('ID');
561
        $this->assertEquals(array($comment1->ID, $newComment->ID), $team1CommentIDs);
562
    }
563
564
565
    /**
566
     * Test has many relationships against polymorphic has_one fields
567
     *   - Test getComponents() gets the ComponentSet of the other side of the relation
568
     *   - Test the IDs on the DataObjects are set correctly
569
     */
570
    public function testHasManyPolymorphicRelationships()
571
    {
572
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
573
574
        // Test getComponents() gets the ComponentSet of the other side of the relation
575
        $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

575
        $this->assertTrue($team1->/** @scrutinizer ignore-call */ Fans()->count() == 2);
Loading history...
576
577
        // Test the IDs/Classes on the DataObjects are set correctly
578
        foreach ($team1->Fans() as $fan) {
579
            $this->assertEquals($team1->ID, $fan->FavouriteID, 'Fan has the correct FavouriteID');
580
            $this->assertEquals(DataObjectTest\Team::class, $fan->FavouriteClass, 'Fan has the correct FavouriteClass');
581
        }
582
583
        // Test that we can add and remove items that already exist in the database
584
        $newFan = new DataObjectTest\Fan();
585
        $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...
586
        $newFan->write();
587
        $team1->Fans()->add($newFan);
588
        $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...
589
        $this->assertEquals(
590
            DataObjectTest\Team::class,
591
            $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...
592
            'Newly created fan has the correct FavouriteClass'
593
        );
594
595
        $fan1 = $this->objFromFixture(DataObjectTest\Fan::class, 'fan1');
596
        $fan3 = $this->objFromFixture(DataObjectTest\Fan::class, 'fan3');
597
        $team1->Fans()->remove($fan3);
598
599
        $team1FanIDs = $team1->Fans()->sort('ID')->column('ID');
600
        $this->assertEquals(array($fan1->ID, $newFan->ID), $team1FanIDs);
601
602
        // Test that removing an item from a list doesn't remove it from the same
603
        // relation belonging to a different object
604
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
605
        $player1 = $this->objFromFixture(DataObjectTest\Player::class, 'player1');
606
        $player1->Fans()->remove($fan1);
607
        $team1FanIDs = $team1->Fans()->sort('ID')->column('ID');
608
        $this->assertEquals(array($fan1->ID, $newFan->ID), $team1FanIDs);
609
    }
610
611
612
    public function testHasOneRelationship()
613
    {
614
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
615
        $player1 = $this->objFromFixture(DataObjectTest\Player::class, 'player1');
616
        $player2 = $this->objFromFixture(DataObjectTest\Player::class, 'player2');
617
        $fan1 = $this->objFromFixture(DataObjectTest\Fan::class, 'fan1');
618
619
        // Test relation probing
620
        $this->assertFalse((bool)$team1->hasValue('Captain', null, false));
621
        $this->assertFalse((bool)$team1->hasValue('CaptainID', null, false));
622
623
        // Add a captain to team 1
624
        $team1->setField('CaptainID', $player1->ID);
625
        $team1->write();
626
627
        $this->assertTrue((bool)$team1->hasValue('Captain', null, false));
628
        $this->assertTrue((bool)$team1->hasValue('CaptainID', null, false));
629
630
        $this->assertEquals(
631
            $player1->ID,
632
            $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

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

1268
        $sponsor = $team->/** @scrutinizer ignore-call */ Sponsors()->first();
Loading history...
1269
        $this->assertEquals('Int', $sponsor->castingHelper('SponsorFee'), 'many_many_extraFields not casted correctly');
1270
    }
1271
1272
    public function testSummaryFieldsCustomLabels()
1273
    {
1274
        $team = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1275
        $summaryFields = $team->summaryFields();
1276
1277
        $this->assertEquals(
1278
            [
1279
                'Title' => 'Custom Title',
1280
                'Title.UpperCase' => 'Title',
1281
                'Captain.ShirtNumber' => 'Captain\'s shirt number',
1282
                'Captain.FavouriteTeam.Title' => 'Captain\'s favourite team',
1283
            ],
1284
            $summaryFields
1285
        );
1286
    }
1287
1288
    public function testDataObjectUpdate()
1289
    {
1290
        /* update() calls can use the dot syntax to reference has_one relations and other methods that return
1291
        * objects */
1292
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1293
        $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...
1294
1295
        $team1->update(
1296
            array(
1297
                'DatabaseField' => 'Something',
1298
                'Captain.FirstName' => 'Jim',
1299
                'Captain.Email' => '[email protected]',
1300
                'Captain.FavouriteTeam.Title' => 'New and improved team 1',
1301
            )
1302
        );
1303
1304
        /* Test the simple case of updating fields on the object itself */
1305
        $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...
1306
1307
        /* Setting Captain.Email and Captain.FirstName will have updated DataObjectTest_Captain.captain1 in
1308
        * the database.  Although update() doesn't usually write, it does write related records automatically. */
1309
        $captain1 = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
1310
        $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...
1311
        $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...
1312
1313
        /* Jim's favourite team is team 1; we need to reload the object to the the change that setting Captain.
1314
        * FavouriteTeam.Title made */
1315
        $reloadedTeam1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1316
        $this->assertEquals('New and improved team 1', $reloadedTeam1->Title);
1317
    }
1318
1319
    public function testDataObjectUpdateNew()
1320
    {
1321
        /* update() calls can use the dot syntax to reference has_one relations and other methods that return
1322
        * objects */
1323
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1324
        $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...
1325
1326
        $team1->update(
1327
            array(
1328
                'Captain.FirstName' => 'Jim',
1329
                'Captain.FavouriteTeam.Title' => 'New and improved team 1',
1330
            )
1331
        );
1332
        /* Test that the captain ID has been updated */
1333
        $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...
1334
1335
        /* Fetch the newly created captain */
1336
        $captain1 = DataObjectTest\Player::get()->byID($team1->CaptainID);
1337
        $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...
1338
1339
        /* Grab the favourite team and make sure it has the correct values */
1340
        $reloadedTeam1 = $captain1->FavouriteTeam();
1341
        $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...
1342
        $this->assertEquals('New and improved team 1', $reloadedTeam1->Title);
1343
    }
1344
1345
1346
    /**
1347
     * @expectedException \SilverStripe\ORM\ValidationException
1348
     */
1349
    public function testWritingInvalidDataObjectThrowsException()
1350
    {
1351
        $validatedObject = new DataObjectTest\ValidatedObject();
1352
        $validatedObject->write();
1353
    }
1354
1355
    public function testWritingValidDataObjectDoesntThrowException()
1356
    {
1357
        $validatedObject = new DataObjectTest\ValidatedObject();
1358
        $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...
1359
1360
        $validatedObject->write();
1361
        $this->assertTrue($validatedObject->isInDB(), "Validated object was not saved to database");
1362
    }
1363
1364
    public function testSubclassCreation()
1365
    {
1366
        /* Creating a new object of a subclass should set the ClassName field correctly */
1367
        $obj = new DataObjectTest\SubTeam();
1368
        $obj->write();
1369
        $this->assertEquals(
1370
            DataObjectTest\SubTeam::class,
1371
            DB::query("SELECT \"ClassName\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $obj->ID")->value()
1372
        );
1373
    }
1374
1375
    public function testForceInsert()
1376
    {
1377
        /* If you set an ID on an object and pass forceInsert = true, then the object should be correctly created */
1378
        $conn = DB::get_conn();
1379
        if (method_exists($conn, 'allowPrimaryKeyEditing')) {
1380
            $conn->allowPrimaryKeyEditing(DataObjectTest\Team::class, true);
1381
        }
1382
        $obj = new DataObjectTest\SubTeam();
1383
        $obj->ID = 1001;
1384
        $obj->Title = 'asdfasdf';
1385
        $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...
1386
        $obj->write(false, true);
1387
        if (method_exists($conn, 'allowPrimaryKeyEditing')) {
1388
            $conn->allowPrimaryKeyEditing(DataObjectTest\Team::class, false);
1389
        }
1390
1391
        $this->assertEquals(
1392
            DataObjectTest\SubTeam::class,
1393
            DB::query("SELECT \"ClassName\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $obj->ID")->value()
1394
        );
1395
1396
        /* Check that it actually saves to the database with the correct ID */
1397
        $this->assertEquals(
1398
            "1001",
1399
            DB::query(
1400
                "SELECT \"ID\" FROM \"DataObjectTest_SubTeam\" WHERE \"SubclassDatabaseField\" = 'asdfasdf'"
1401
            )->value()
1402
        );
1403
        $this->assertEquals(
1404
            "1001",
1405
            DB::query("SELECT \"ID\" FROM \"DataObjectTest_Team\" WHERE \"Title\" = 'asdfasdf'")->value()
1406
        );
1407
    }
1408
1409
    public function testHasOwnTable()
1410
    {
1411
        $schema = DataObject::getSchema();
1412
        /* Test DataObject::has_own_table() returns true if the object has $has_one or $db values */
1413
        $this->assertTrue($schema->classHasTable(DataObjectTest\Player::class));
1414
        $this->assertTrue($schema->classHasTable(DataObjectTest\Team::class));
1415
        $this->assertTrue($schema->classHasTable(DataObjectTest\Fixture::class));
1416
1417
        /* Root DataObject that always have a table, even if they lack both $db and $has_one */
1418
        $this->assertTrue($schema->classHasTable(DataObjectTest\FieldlessTable::class));
1419
1420
        /* Subclasses without $db or $has_one don't have a table */
1421
        $this->assertFalse($schema->classHasTable(DataObjectTest\FieldlessSubTable::class));
1422
1423
        /* Return false if you don't pass it a subclass of DataObject */
1424
        $this->assertFalse($schema->classHasTable(DataObject::class));
1425
        $this->assertFalse($schema->classHasTable(ViewableData::class));
1426
1427
        /* Invalid class name */
1428
        $this->assertFalse($schema->classHasTable("ThisIsntADataObject"));
1429
    }
1430
1431
    public function testMerge()
1432
    {
1433
        // test right merge of subclasses
1434
        $left = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam1');
1435
        $right = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam2_with_player_relation');
1436
        $leftOrigID = $left->ID;
1437
        $left->merge($right, 'right', false, false);
1438
        $this->assertEquals(
1439
            $left->Title,
1440
            'Subteam 2',
1441
            'merge() with "right" priority overwrites fields with existing values on subclasses'
1442
        );
1443
        $this->assertEquals(
1444
            $left->ID,
1445
            $leftOrigID,
1446
            'merge() with "right" priority doesnt overwrite database ID'
1447
        );
1448
1449
        // test overwriteWithEmpty flag on existing left values
1450
        $left = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam2_with_player_relation');
1451
        $right = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam3_with_empty_fields');
1452
        $left->merge($right, 'right', false, true);
1453
        $this->assertEquals(
1454
            $left->Title,
1455
            'Subteam 3',
1456
            'merge() with $overwriteWithEmpty overwrites non-empty fields on left object'
1457
        );
1458
1459
        // test overwriteWithEmpty flag on empty left values
1460
        $left = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam1');
1461
        // $SubclassDatabaseField is empty on here
1462
        $right = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam2_with_player_relation');
1463
        $left->merge($right, 'right', false, true);
1464
        $this->assertEquals(
1465
            $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...
1466
            null,
1467
            'merge() with $overwriteWithEmpty overwrites empty fields on left object'
1468
        );
1469
1470
        // @todo test "left" priority flag
1471
        // @todo test includeRelations flag
1472
        // @todo test includeRelations in combination with overwriteWithEmpty
1473
        // @todo test has_one relations
1474
        // @todo test has_many and many_many relations
1475
    }
1476
1477
    public function testPopulateDefaults()
1478
    {
1479
        $obj = new DataObjectTest\Fixture();
1480
        $this->assertEquals(
1481
            $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...
1482
            'Default Value',
1483
            'Defaults are populated for in-memory object from $defaults array'
1484
        );
1485
1486
        $this->assertEquals(
1487
            $obj->MyFieldWithAltDefault,
1488
            'Default Value',
1489
            'Defaults are populated from overloaded populateDefaults() method'
1490
        );
1491
    }
1492
1493
    /**
1494
     * @expectedException \InvalidArgumentException
1495
     */
1496
    public function testValidateModelDefinitionsFailsWithArray()
1497
    {
1498
        Config::modify()->merge(DataObjectTest\Team::class, 'has_one', array('NotValid' => array('NoArraysAllowed')));
1499
        DataObject::getSchema()->hasOneComponent(DataObjectTest\Team::class, 'NotValid');
1500
    }
1501
1502
    /**
1503
     * @expectedException \InvalidArgumentException
1504
     */
1505
    public function testValidateModelDefinitionsFailsWithIntKey()
1506
    {
1507
        Config::modify()->set(DataObjectTest\Team::class, 'has_many', array(0 => DataObjectTest\Player::class));
1508
        DataObject::getSchema()->hasManyComponent(DataObjectTest\Team::class, 0);
1509
    }
1510
1511
    /**
1512
     * @expectedException \InvalidArgumentException
1513
     */
1514
    public function testValidateModelDefinitionsFailsWithIntValue()
1515
    {
1516
        Config::modify()->merge(DataObjectTest\Team::class, 'many_many', array('Players' => 12));
1517
        DataObject::getSchema()->manyManyComponent(DataObjectTest\Team::class, 'Players');
1518
    }
1519
1520
    public function testNewClassInstance()
1521
    {
1522
        $dataObject = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1523
        $changedDO = $dataObject->newClassInstance(DataObjectTest\SubTeam::class);
1524
        $changedFields = $changedDO->getChangedFields();
1525
1526
        // Don't write the record, it will reset changed fields
1527
        $this->assertInstanceOf(DataObjectTest\SubTeam::class, $changedDO);
1528
        $this->assertEquals($changedDO->ClassName, DataObjectTest\SubTeam::class);
1529
        $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...
1530
        $this->assertContains('ClassName', array_keys($changedFields));
1531
        $this->assertEquals($changedFields['ClassName']['before'], DataObjectTest\Team::class);
1532
        $this->assertEquals($changedFields['ClassName']['after'], DataObjectTest\SubTeam::class);
1533
        $this->assertEquals($changedFields['RecordClassName']['before'], DataObjectTest\Team::class);
1534
        $this->assertEquals($changedFields['RecordClassName']['after'], DataObjectTest\SubTeam::class);
1535
1536
        $changedDO->write();
1537
1538
        $this->assertInstanceOf(DataObjectTest\SubTeam::class, $changedDO);
1539
        $this->assertEquals($changedDO->ClassName, DataObjectTest\SubTeam::class);
1540
1541
        // Test invalid classes fail
1542
        $this->expectException(InvalidArgumentException::class);
1543
        $this->expectExceptionMessage('Controller is not a valid subclass of DataObject');
1544
        /**
1545
         * @skipUpgrade
1546
         */
1547
        $dataObject->newClassInstance('Controller');
1548
    }
1549
1550
    public function testMultipleManyManyWithSameClass()
1551
    {
1552
        $team = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1553
        $company2 = $this->objFromFixture(DataObjectTest\EquipmentCompany::class, 'equipmentcompany2');
1554
        $sponsors = $team->Sponsors();
1555
        $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

1555
        /** @scrutinizer ignore-call */ 
1556
        $equipmentSuppliers = $team->EquipmentSuppliers();
Loading history...
1556
1557
        // Check that DataObject::many_many() works as expected
1558
        $manyManyComponent = DataObject::getSchema()->manyManyComponent(DataObjectTest\Team::class, 'Sponsors');
1559
        $this->assertEquals(ManyManyList::class, $manyManyComponent['relationClass']);
1560
        $this->assertEquals(
1561
            DataObjectTest\Team::class,
1562
            $manyManyComponent['parentClass'],
1563
            'DataObject::many_many() didn\'t find the correct base class'
1564
        );
1565
        $this->assertEquals(
1566
            DataObjectTest\EquipmentCompany::class,
1567
            $manyManyComponent['childClass'],
1568
            'DataObject::many_many() didn\'t find the correct target class for the relation'
1569
        );
1570
        $this->assertEquals(
1571
            'DataObjectTest_EquipmentCompany_SponsoredTeams',
1572
            $manyManyComponent['join'],
1573
            'DataObject::many_many() didn\'t find the correct relation table'
1574
        );
1575
        $this->assertEquals('DataObjectTest_TeamID', $manyManyComponent['parentField']);
1576
        $this->assertEquals('DataObjectTest_EquipmentCompanyID', $manyManyComponent['childField']);
1577
1578
        // Check that ManyManyList still works
1579
        $this->assertEquals(2, $sponsors->count(), 'Rows are missing from relation');
1580
        $this->assertEquals(1, $equipmentSuppliers->count(), 'Rows are missing from relation');
1581
1582
        // Check everything works when no relation is present
1583
        $teamWithoutSponsor = $this->objFromFixture(DataObjectTest\Team::class, 'team3');
1584
        $this->assertInstanceOf(ManyManyList::class, $teamWithoutSponsor->Sponsors());
1585
        $this->assertEquals(0, $teamWithoutSponsor->Sponsors()->count());
1586
1587
        // Test that belongs_many_many can be infered from with getNonReciprocalComponent
1588
        $this->assertListEquals(
1589
            [
1590
                ['Name' => 'Company corp'],
1591
                ['Name' => 'Team co.'],
1592
            ],
1593
            $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

1593
            /** @scrutinizer ignore-type */ $team->inferReciprocalComponent(DataObjectTest\EquipmentCompany::class, 'SponsoredTeams')
Loading history...
1594
        );
1595
1596
        // Test that many_many can be infered from getNonReciprocalComponent
1597
        $this->assertListEquals(
1598
            [
1599
                ['Title' => 'Team 1'],
1600
                ['Title' => 'Team 2'],
1601
                ['Title' => 'Subteam 1'],
1602
            ],
1603
            $company2->inferReciprocalComponent(DataObjectTest\Team::class, 'Sponsors')
1604
        );
1605
1606
        // Check many_many_extraFields still works
1607
        $equipmentCompany = $this->objFromFixture(DataObjectTest\EquipmentCompany::class, 'equipmentcompany1');
1608
        $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

1608
        $equipmentCompany->/** @scrutinizer ignore-call */ 
1609
                           SponsoredTeams()->add($teamWithoutSponsor, array('SponsorFee' => 1000));
Loading history...
1609
        $sponsoredTeams = $equipmentCompany->SponsoredTeams();
1610
        $this->assertEquals(
1611
            1000,
1612
            $sponsoredTeams->byID($teamWithoutSponsor->ID)->SponsorFee,
1613
            'Data from many_many_extraFields was not stored/extracted correctly'
1614
        );
1615
1616
        // Check subclasses correctly inherit multiple many_manys
1617
        $subTeam = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam1');
1618
        $this->assertEquals(
1619
            2,
1620
            $subTeam->Sponsors()->count(),
1621
            'Child class did not inherit multiple many_manys'
1622
        );
1623
        $this->assertEquals(
1624
            1,
1625
            $subTeam->EquipmentSuppliers()->count(),
1626
            'Child class did not inherit multiple many_manys'
1627
        );
1628
        // Team 2 has one EquipmentCompany sponsor and one SubEquipmentCompany
1629
        $team2 = $this->objFromFixture(DataObjectTest\Team::class, 'team2');
1630
        $this->assertEquals(
1631
            2,
1632
            $team2->Sponsors()->count(),
1633
            'Child class did not inherit multiple belongs_many_manys'
1634
        );
1635
1636
        // Check many_many_extraFields also works from the belongs_many_many side
1637
        $sponsors = $team2->Sponsors();
1638
        $sponsors->add($equipmentCompany, array('SponsorFee' => 750));
1639
        $this->assertEquals(
1640
            750,
1641
            $sponsors->byID($equipmentCompany->ID)->SponsorFee,
1642
            'Data from many_many_extraFields was not stored/extracted correctly'
1643
        );
1644
1645
        $subEquipmentCompany = $this->objFromFixture(DataObjectTest\SubEquipmentCompany::class, 'subequipmentcompany1');
1646
        $subTeam->Sponsors()->add($subEquipmentCompany, array('SponsorFee' => 1200));
1647
        $this->assertEquals(
1648
            1200,
1649
            $subTeam->Sponsors()->byID($subEquipmentCompany->ID)->SponsorFee,
1650
            'Data from inherited many_many_extraFields was not stored/extracted correctly'
1651
        );
1652
    }
1653
1654
    public function testManyManyExtraFields()
1655
    {
1656
        $team = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1657
        $schema = DataObject::getSchema();
1658
1659
        // Get all extra fields
1660
        $teamExtraFields = $team->manyManyExtraFields();
1661
        $this->assertEquals(
1662
            array(
1663
                'Players' => array('Position' => 'Varchar(100)')
1664
            ),
1665
            $teamExtraFields
1666
        );
1667
1668
        // Ensure fields from parent classes are included
1669
        $subTeam = singleton(DataObjectTest\SubTeam::class);
1670
        $teamExtraFields = $subTeam->manyManyExtraFields();
1671
        $this->assertEquals(
1672
            array(
1673
                'Players' => array('Position' => 'Varchar(100)'),
1674
                'FormerPlayers' => array('Position' => 'Varchar(100)')
1675
            ),
1676
            $teamExtraFields
1677
        );
1678
1679
        // Extra fields are immediately available on the Team class (defined in $many_many_extraFields)
1680
        $teamExtraFields = $schema->manyManyExtraFieldsForComponent(DataObjectTest\Team::class, 'Players');
1681
        $this->assertEquals(
1682
            $teamExtraFields,
1683
            array(
1684
                'Position' => 'Varchar(100)'
1685
            )
1686
        );
1687
1688
        // We'll have to go through the relation to get the extra fields on Player
1689
        $playerExtraFields = $schema->manyManyExtraFieldsForComponent(DataObjectTest\Player::class, 'Teams');
1690
        $this->assertEquals(
1691
            $playerExtraFields,
1692
            array(
1693
                'Position' => 'Varchar(100)'
1694
            )
1695
        );
1696
1697
        // Iterate through a many-many relationship and confirm that extra fields are included
1698
        $newTeam = new DataObjectTest\Team();
1699
        $newTeam->Title = "New team";
1700
        $newTeam->write();
1701
        $newTeamID = $newTeam->ID;
1702
1703
        $newPlayer = new DataObjectTest\Player();
1704
        $newPlayer->FirstName = "Sam";
1705
        $newPlayer->Surname = "Minnee";
1706
        $newPlayer->write();
1707
1708
        // The idea of Sam as a prop is essentially humourous.
1709
        $newTeam->Players()->add($newPlayer, array("Position" => "Prop"));
1710
1711
        // Requery and uncache everything
1712
        $newTeam->flushCache();
1713
        $newTeam = DataObject::get_by_id(DataObjectTest\Team::class, $newTeamID);
1714
1715
        // Check that the Position many_many_extraField is extracted.
1716
        $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

1716
        $player = $newTeam->/** @scrutinizer ignore-call */ Players()->first();
Loading history...
1717
        $this->assertEquals('Sam', $player->FirstName);
1718
        $this->assertEquals("Prop", $player->Position);
1719
1720
        // Check that ordering a many-many relation by an aggregate column doesn't fail
1721
        $player = $this->objFromFixture(DataObjectTest\Player::class, 'player2');
1722
        $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

1722
        $player->/** @scrutinizer ignore-call */ 
1723
                 Teams()->sort("count(DISTINCT \"DataObjectTest_Team_Players\".\"DataObjectTest_PlayerID\") DESC");
Loading history...
1723
    }
1724
1725
    /**
1726
     * Check that the queries generated for many-many relation queries can have unlimitedRowCount
1727
     * called on them.
1728
     */
1729
    public function testManyManyUnlimitedRowCount()
1730
    {
1731
        $player = $this->objFromFixture(DataObjectTest\Player::class, 'player2');
1732
        // TODO: What's going on here?
1733
        $this->assertEquals(2, $player->Teams()->dataQuery()->query()->unlimitedRowCount());
1734
    }
1735
1736
    /**
1737
     * Tests that singular_name() generates sensible defaults.
1738
     */
1739
    public function testSingularName()
1740
    {
1741
        $assertions = array(
1742
            DataObjectTest\Player::class => 'Player',
1743
            DataObjectTest\Team::class => 'Team',
1744
            DataObjectTest\Fixture::class => 'Fixture',
1745
        );
1746
1747
        foreach ($assertions as $class => $expectedSingularName) {
1748
            $this->assertEquals(
1749
                $expectedSingularName,
1750
                singleton($class)->singular_name(),
1751
                "Assert that the singular_name for '$class' is correct."
1752
            );
1753
        }
1754
    }
1755
1756
    /**
1757
     * Tests that plural_name() generates sensible defaults.
1758
     */
1759
    public function testPluralName()
1760
    {
1761
        $assertions = array(
1762
            DataObjectTest\Player::class => 'Players',
1763
            DataObjectTest\Team::class => 'Teams',
1764
            DataObjectTest\Fixture::class => 'Fixtures',
1765
            DataObjectTest\Play::class => 'Plays',
1766
            DataObjectTest\Bogey::class => 'Bogeys',
1767
            DataObjectTest\Ploy::class => 'Ploys',
1768
        );
1769
        i18n::set_locale('en_NZ');
1770
        foreach ($assertions as $class => $expectedPluralName) {
1771
            $this->assertEquals(
1772
                $expectedPluralName,
1773
                DataObject::singleton($class)->plural_name(),
1774
                "Assert that the plural_name for '$class' is correct."
1775
            );
1776
            $this->assertEquals(
1777
                $expectedPluralName,
1778
                DataObject::singleton($class)->i18n_plural_name(),
1779
                "Assert that the i18n_plural_name for '$class' is correct."
1780
            );
1781
        }
1782
    }
1783
1784
    public function testHasDatabaseField()
1785
    {
1786
        $team = singleton(DataObjectTest\Team::class);
1787
        $subteam = singleton(DataObjectTest\SubTeam::class);
1788
1789
        $this->assertTrue(
1790
            $team->hasDatabaseField('Title'),
1791
            "hasOwnDatabaseField() works with \$db fields"
1792
        );
1793
        $this->assertTrue(
1794
            $team->hasDatabaseField('CaptainID'),
1795
            "hasOwnDatabaseField() works with \$has_one fields"
1796
        );
1797
        $this->assertFalse(
1798
            $team->hasDatabaseField('NonExistentField'),
1799
            "hasOwnDatabaseField() doesn't detect non-existend fields"
1800
        );
1801
        $this->assertTrue(
1802
            $team->hasDatabaseField('ExtendedDatabaseField'),
1803
            "hasOwnDatabaseField() works with extended fields"
1804
        );
1805
        $this->assertFalse(
1806
            $team->hasDatabaseField('SubclassDatabaseField'),
1807
            "hasOwnDatabaseField() doesn't pick up fields in subclasses on parent class"
1808
        );
1809
1810
        $this->assertTrue(
1811
            $subteam->hasDatabaseField('SubclassDatabaseField'),
1812
            "hasOwnDatabaseField() picks up fields in subclasses"
1813
        );
1814
    }
1815
1816
    public function testFieldTypes()
1817
    {
1818
        $obj = new DataObjectTest\Fixture();
1819
        $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...
1820
        $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...
1821
        $obj->write();
1822
        $obj->flushCache();
1823
1824
        $obj = DataObject::get_by_id(DataObjectTest\Fixture::class, $obj->ID);
1825
        $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...
1826
        $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...
1827
    }
1828
1829
    public function testTwoSubclassesWithTheSameFieldNameWork()
1830
    {
1831
        // Create two objects of different subclasses, setting the values of fields that are
1832
        // defined separately in each subclass
1833
        $obj1 = new DataObjectTest\SubTeam();
1834
        $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...
1835
        $obj2 = new DataObjectTest\OtherSubclassWithSameField();
1836
        $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...
1837
1838
        // Write them to the database
1839
        $obj1->write();
1840
        $obj2->write();
1841
1842
        // Check that the values of those fields are properly read from the database
1843
        $values = DataObject::get(
1844
            DataObjectTest\Team::class,
1845
            "\"DataObjectTest_Team\".\"ID\" IN
1846
			($obj1->ID, $obj2->ID)"
1847
        )->column("SubclassDatabaseField");
1848
        $this->assertEquals(array_intersect($values, array('obj1', 'obj2')), $values);
1849
    }
1850
1851
    public function testClassNameSetForNewObjects()
1852
    {
1853
        $d = new DataObjectTest\Player();
1854
        $this->assertEquals(DataObjectTest\Player::class, $d->ClassName);
1855
    }
1856
1857
    public function testHasValue()
1858
    {
1859
        $team = new DataObjectTest\Team();
1860
        $this->assertFalse($team->hasValue('Title', null, false));
1861
        $this->assertFalse($team->hasValue('DatabaseField', null, false));
1862
1863
        $team->Title = 'hasValue';
1864
        $this->assertTrue($team->hasValue('Title', null, false));
1865
        $this->assertFalse($team->hasValue('DatabaseField', null, false));
1866
1867
        $team->Title = '<p></p>';
1868
        $this->assertTrue(
1869
            $team->hasValue('Title', null, false),
1870
            'Test that an empty paragraph is a value for non-HTML fields.'
1871
        );
1872
1873
        $team->DatabaseField = 'hasValue';
1874
        $this->assertTrue($team->hasValue('Title', null, false));
1875
        $this->assertTrue($team->hasValue('DatabaseField', null, false));
1876
    }
1877
1878
    public function testHasMany()
1879
    {
1880
        $company = new DataObjectTest\Company();
1881
1882
        $this->assertEquals(
1883
            array(
1884
                'CurrentStaff' => DataObjectTest\Staff::class,
1885
                'PreviousStaff' => DataObjectTest\Staff::class
1886
            ),
1887
            $company->hasMany(),
1888
            'has_many strips field name data by default.'
1889
        );
1890
1891
        $this->assertEquals(
1892
            DataObjectTest\Staff::class,
1893
            DataObject::getSchema()->hasManyComponent(DataObjectTest\Company::class, 'CurrentStaff'),
1894
            'has_many strips field name data by default on single relationships.'
1895
        );
1896
1897
        $this->assertEquals(
1898
            array(
1899
                'CurrentStaff' => DataObjectTest\Staff::class . '.CurrentCompany',
1900
                'PreviousStaff' => DataObjectTest\Staff::class . '.PreviousCompany'
1901
            ),
1902
            $company->hasMany(false),
1903
            'has_many returns field name data when $classOnly is false.'
1904
        );
1905
1906
        $this->assertEquals(
1907
            DataObjectTest\Staff::class . '.CurrentCompany',
1908
            DataObject::getSchema()->hasManyComponent(DataObjectTest\Company::class, 'CurrentStaff', false),
1909
            'has_many returns field name data on single records when $classOnly is false.'
1910
        );
1911
    }
1912
1913
    public function testGetRemoteJoinField()
1914
    {
1915
        $schema = DataObject::getSchema();
1916
1917
        // Company schema
1918
        $staffJoinField = $schema->getRemoteJoinField(
1919
            DataObjectTest\Company::class,
1920
            'CurrentStaff',
1921
            'has_many',
1922
            $polymorphic
1923
        );
1924
        $this->assertEquals('CurrentCompanyID', $staffJoinField);
1925
        $this->assertFalse($polymorphic, 'DataObjectTest_Company->CurrentStaff is not polymorphic');
1926
        $previousStaffJoinField = $schema->getRemoteJoinField(
1927
            DataObjectTest\Company::class,
1928
            'PreviousStaff',
1929
            'has_many',
1930
            $polymorphic
1931
        );
1932
        $this->assertEquals('PreviousCompanyID', $previousStaffJoinField);
1933
        $this->assertFalse($polymorphic, 'DataObjectTest_Company->PreviousStaff is not polymorphic');
1934
1935
        // CEO Schema
1936
        $this->assertEquals(
1937
            'CEOID',
1938
            $schema->getRemoteJoinField(
1939
                DataObjectTest\CEO::class,
1940
                'Company',
1941
                'belongs_to',
1942
                $polymorphic
1943
            )
1944
        );
1945
        $this->assertFalse($polymorphic, 'DataObjectTest_CEO->Company is not polymorphic');
1946
        $this->assertEquals(
1947
            'PreviousCEOID',
1948
            $schema->getRemoteJoinField(
1949
                DataObjectTest\CEO::class,
1950
                'PreviousCompany',
1951
                'belongs_to',
1952
                $polymorphic
1953
            )
1954
        );
1955
        $this->assertFalse($polymorphic, 'DataObjectTest_CEO->PreviousCompany is not polymorphic');
1956
1957
        // Team schema
1958
        $this->assertEquals(
1959
            'Favourite',
1960
            $schema->getRemoteJoinField(
1961
                DataObjectTest\Team::class,
1962
                'Fans',
1963
                'has_many',
1964
                $polymorphic
1965
            )
1966
        );
1967
        $this->assertTrue($polymorphic, 'DataObjectTest_Team->Fans is polymorphic');
1968
        $this->assertEquals(
1969
            'TeamID',
1970
            $schema->getRemoteJoinField(
1971
                DataObjectTest\Team::class,
1972
                'Comments',
1973
                'has_many',
1974
                $polymorphic
1975
            )
1976
        );
1977
        $this->assertFalse($polymorphic, 'DataObjectTest_Team->Comments is not polymorphic');
1978
    }
1979
1980
    public function testBelongsTo()
1981
    {
1982
        $company = new DataObjectTest\Company();
1983
        $ceo = new DataObjectTest\CEO();
1984
1985
        $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...
1986
        $company->write();
1987
        $ceo->write();
1988
1989
        // Test belongs_to assignment
1990
        $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...
1991
        $company->write();
1992
1993
        $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

1993
        $this->assertEquals($company->ID, $ceo->/** @scrutinizer ignore-call */ Company()->ID, 'belongs_to returns the right results.');
Loading history...
1994
1995
        // Test belongs_to can be infered via getNonReciprocalComponent
1996
        // Note: Will be returned as has_many since the belongs_to is ignored.
1997
        $this->assertListEquals(
1998
            [['Name' => 'New Company']],
1999
            $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

1999
            /** @scrutinizer ignore-type */ $ceo->inferReciprocalComponent(DataObjectTest\Company::class, 'CEO')
Loading history...
2000
        );
2001
2002
        // Test has_one to a belongs_to can be infered via getNonReciprocalComponent
2003
        $this->assertEquals(
2004
            $ceo->ID,
2005
            $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...
2006
        );
2007
2008
        // Test automatic creation of class where no assigment exists
2009
        $ceo = new DataObjectTest\CEO();
2010
        $ceo->write();
2011
2012
        $this->assertTrue(
2013
            $ceo->Company() instanceof DataObjectTest\Company,
2014
            'DataObjects across belongs_to relations are automatically created.'
2015
        );
2016
        $this->assertEquals($ceo->ID, $ceo->Company()->CEOID, 'Remote IDs are automatically set.');
2017
2018
        // Write object with components
2019
        $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...
2020
        $ceo->write(false, false, false, true);
2021
        $this->assertTrue($ceo->Company()->isInDB(), 'write() writes belongs_to components to the database.');
2022
2023
        $newCEO = DataObject::get_by_id(DataObjectTest\CEO::class, $ceo->ID);
2024
        $this->assertEquals(
2025
            $ceo->Company()->ID,
2026
            $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

2026
            $newCEO->/** @scrutinizer ignore-call */ 
2027
                     Company()->ID,
Loading history...
2027
            'belongs_to can be retrieved from the database.'
2028
        );
2029
    }
2030
2031
    public function testBelongsToPolymorphic()
2032
    {
2033
        $company = new DataObjectTest\Company();
2034
        $ceo = new DataObjectTest\CEO();
2035
2036
        $company->write();
2037
        $ceo->write();
2038
2039
        // Test belongs_to assignment
2040
        $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...
2041
        $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...
2042
        $company->write();
2043
2044
        $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

2044
        $this->assertEquals($company->ID, $ceo->/** @scrutinizer ignore-call */ CompanyOwned()->ID, 'belongs_to returns the right results.');
Loading history...
2045
        $this->assertInstanceOf(
2046
            DataObjectTest\Company::class,
2047
            $ceo->CompanyOwned(),
2048
            'belongs_to returns the right results.'
2049
        );
2050
2051
        // Test automatic creation of class where no assigment exists
2052
        $ceo = new DataObjectTest\CEO();
2053
        $ceo->write();
2054
2055
        $this->assertTrue(
2056
            $ceo->CompanyOwned() instanceof DataObjectTest\Company,
2057
            'DataObjects across polymorphic belongs_to relations are automatically created.'
2058
        );
2059
        $this->assertEquals($ceo->ID, $ceo->CompanyOwned()->OwnerID, 'Remote IDs are automatically set.');
2060
        $this->assertInstanceOf($ceo->CompanyOwned()->OwnerClass, $ceo, 'Remote class is automatically  set');
2061
2062
        // Write object with components
2063
        $ceo->write(false, false, false, true);
2064
        $this->assertTrue($ceo->CompanyOwned()->isInDB(), 'write() writes belongs_to components to the database.');
2065
2066
        $newCEO = DataObject::get_by_id(DataObjectTest\CEO::class, $ceo->ID);
2067
        $this->assertEquals(
2068
            $ceo->CompanyOwned()->ID,
2069
            $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

2069
            $newCEO->/** @scrutinizer ignore-call */ 
2070
                     CompanyOwned()->ID,
Loading history...
2070
            'polymorphic belongs_to can be retrieved from the database.'
2071
        );
2072
    }
2073
2074
    /**
2075
     * @expectedException LogicException
2076
     */
2077
    public function testInvalidate()
2078
    {
2079
        $do = new DataObjectTest\Fixture();
2080
        $do->write();
2081
2082
        $do->delete();
2083
2084
        $do->delete(); // Prohibit invalid object manipulation
2085
        $do->write();
2086
        $do->duplicate();
2087
    }
2088
2089
    public function testToMap()
2090
    {
2091
        $obj = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam1');
2092
2093
        $map = $obj->toMap();
2094
2095
        $this->assertArrayHasKey('ID', $map, 'Contains base fields');
2096
        $this->assertArrayHasKey('Title', $map, 'Contains fields from parent class');
2097
        $this->assertArrayHasKey('SubclassDatabaseField', $map, 'Contains fields from concrete class');
2098
2099
        $this->assertEquals(
2100
            $obj->ID,
2101
            $map['ID'],
2102
            'Contains values from base fields'
2103
        );
2104
        $this->assertEquals(
2105
            $obj->Title,
2106
            $map['Title'],
2107
            'Contains values from parent class fields'
2108
        );
2109
        $this->assertEquals(
2110
            $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...
2111
            $map['SubclassDatabaseField'],
2112
            'Contains values from concrete class fields'
2113
        );
2114
2115
        $newObj = new DataObjectTest\SubTeam();
0 ignored issues
show
Unused Code introduced by
The assignment to $newObj is dead and can be removed.
Loading history...
2116
        $this->assertArrayHasKey('Title', $map, 'Contains null fields');
2117
    }
2118
2119
    public function testIsEmpty()
2120
    {
2121
        $objEmpty = new DataObjectTest\Team();
2122
        $this->assertTrue($objEmpty->isEmpty(), 'New instance without populated defaults is empty');
2123
2124
        $objEmpty->Title = '0'; //
2125
        $this->assertFalse($objEmpty->isEmpty(), 'Zero value in attribute considered non-empty');
2126
    }
2127
2128
    public function testRelField()
2129
    {
2130
        $captain1 = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
2131
        // Test traversal of a single has_one
2132
        $this->assertEquals("Team 1", $captain1->relField('FavouriteTeam.Title'));
2133
        // Test direct field access
2134
        $this->assertEquals("Captain", $captain1->relField('FirstName'));
2135
2136
        // Test empty link
2137
        $captain2 = $this->objFromFixture(DataObjectTest\Player::class, 'captain2');
2138
        $this->assertEmpty($captain2->relField('FavouriteTeam.Title'));
2139
        $this->assertNull($captain2->relField('FavouriteTeam.ReturnsNull'));
2140
        $this->assertNull($captain2->relField('FavouriteTeam.ReturnsNull.Title'));
2141
2142
        $player = $this->objFromFixture(DataObjectTest\Player::class, 'player2');
2143
        // Test that we can traverse more than once, and that arbitrary methods are okay
2144
        $this->assertEquals("Team 1", $player->relField('Teams.First.Title'));
2145
2146
        $newPlayer = new DataObjectTest\Player();
2147
        $this->assertNull($newPlayer->relField('Teams.First.Title'));
2148
2149
        // Test that relField works on db field manipulations
2150
        $comment = $this->objFromFixture(DataObjectTest\TeamComment::class, 'comment3');
2151
        $this->assertEquals("PHIL IS A UNIQUE GUY, AND COMMENTS ON TEAM2", $comment->relField('Comment.UpperCase'));
2152
2153
        // relField throws exception on invalid properties
2154
        $this->expectException(LogicException::class);
2155
        $this->expectExceptionMessage("Not is not a relation/field on " . DataObjectTest\TeamComment::class);
2156
        $comment->relField('Not.A.Field');
2157
    }
2158
2159
    public function testRelObject()
2160
    {
2161
        $captain1 = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
2162
2163
        // Test traversal of a single has_one
2164
        $this->assertInstanceOf(DBVarchar::class, $captain1->relObject('FavouriteTeam.Title'));
2165
        $this->assertEquals("Team 1", $captain1->relObject('FavouriteTeam.Title')->getValue());
2166
2167
        // Test empty link
2168
        $captain2 = $this->objFromFixture(DataObjectTest\Player::class, 'captain2');
2169
        $this->assertEmpty($captain2->relObject('FavouriteTeam.Title')->getValue());
2170
        $this->assertNull($captain2->relObject('FavouriteTeam.ReturnsNull.Title'));
2171
2172
        // Test direct field access
2173
        $this->assertInstanceOf(DBBoolean::class, $captain1->relObject('IsRetired'));
2174
        $this->assertEquals(1, $captain1->relObject('IsRetired')->getValue());
2175
2176
        $player = $this->objFromFixture(DataObjectTest\Player::class, 'player2');
2177
        // Test that we can traverse more than once, and that arbitrary methods are okay
2178
        $this->assertInstanceOf(DBVarchar::class, $player->relObject('Teams.First.Title'));
2179
        $this->assertEquals("Team 1", $player->relObject('Teams.First.Title')->getValue());
2180
2181
        // relObject throws exception on invalid properties
2182
        $this->expectException(LogicException::class);
2183
        $this->expectExceptionMessage("Not is not a relation/field on " . DataObjectTest\Player::class);
2184
        $player->relObject('Not.A.Field');
2185
    }
2186
2187
    public function testLateStaticBindingStyle()
2188
    {
2189
        // Confirm that DataObjectTest_Player::get() operates as excepted
2190
        $this->assertEquals(4, DataObjectTest\Player::get()->count());
2191
        $this->assertInstanceOf(DataObjectTest\Player::class, DataObjectTest\Player::get()->first());
2192
2193
        // You can't pass arguments to LSB syntax - use the DataList methods instead.
2194
        $this->expectException(InvalidArgumentException::class);
2195
2196
        DataObjectTest\Player::get(null, "\"ID\" = 1");
2197
    }
2198
2199
    /**
2200
     * @expectedException \InvalidArgumentException
2201
     */
2202
    public function testBrokenLateStaticBindingStyle()
2203
    {
2204
        // If you call DataObject::get() you have to pass a first argument
2205
        DataObject::get();
2206
    }
2207
2208
    public function testBigIntField()
2209
    {
2210
        $staff = new DataObjectTest\Staff();
2211
        $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...
2212
        $staff->write();
2213
        $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...
2214
    }
2215
2216
    public function testGetOneMissingValueReturnsNull()
2217
    {
2218
2219
        // Test that missing values return null
2220
        $this->assertEquals(null, DataObject::get_one(
2221
            DataObjectTest\TeamComment::class,
2222
            ['"DataObjectTest_TeamComment"."Name"' => 'does not exists']
2223
        ));
2224
    }
2225
}
2226