Completed
Push — master ( c17796...052b15 )
by Damian
01:29
created

testWriteNoChangesDoesntUpdateLastEdited()   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.3142
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,
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
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')
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

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

408
        $this->assertEquals($team1ID, $captain1->/** @scrutinizer ignore-call */ FavouriteTeam()->ID);
Loading history...
409
410
        // Test that getNonReciprocalComponent can find has_one from the has_many end
411
        $this->assertEquals(
412
            $team1ID,
413
            $captain1->inferReciprocalComponent(DataObjectTest\Team::class, 'PlayerFans')->ID
414
        );
415
416
        // Check entity with polymorphic has-one
417
        $fan1 = $this->objFromFixture(DataObjectTest\Fan::class, "fan1");
418
        $this->assertTrue((bool)$fan1->hasValue('Favourite'));
419
420
        // There will be fields named (relname)ID and (relname)Class for polymorphic
421
        // entities
422
        $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...
423
        $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...
424
425
        // There will be a method called $obj->relname() that returns the object itself
426
        $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

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

511
        $this->assertTrue($team1->/** @scrutinizer ignore-call */ Comments()->count() == 2);
Loading history...
512
513
        $team1Comments = [
514
            ['Comment' => 'This is a team comment by Joe'],
515
            ['Comment' => 'This is a team comment by Bob'],
516
        ];
517
518
        // Test the IDs on the DataObjects are set correctly
519
        $this->assertListEquals($team1Comments, $team1->Comments());
520
521
        // Test that has_many can be infered from the has_one via getNonReciprocalComponent
522
        $this->assertListEquals(
523
            $team1Comments,
524
            $team1->inferReciprocalComponent(DataObjectTest\TeamComment::class, 'Team')
0 ignored issues
show
Bug introduced by
$team1->inferReciprocalC...Comment::class, 'Team') of type SilverStripe\ORM\DataObject is incompatible with the type SilverStripe\ORM\SS_List expected by parameter $list of SilverStripe\Dev\SapphireTest::assertListEquals(). ( Ignorable by Annotation )

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

524
            /** @scrutinizer ignore-type */ $team1->inferReciprocalComponent(DataObjectTest\TeamComment::class, 'Team')
Loading history...
525
        );
526
527
        // Test that we can add and remove items that already exist in the database
528
        $newComment = new DataObjectTest\TeamComment();
529
        $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...
530
        $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...
531
        $newComment->write();
532
        $team1->Comments()->add($newComment);
533
        $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...
534
535
        $comment1 = $this->objFromFixture(DataObjectTest\TeamComment::class, 'comment1');
536
        $comment2 = $this->objFromFixture(DataObjectTest\TeamComment::class, 'comment2');
537
        $team1->Comments()->remove($comment2);
538
539
        $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

539
        $team1CommentIDs = $team1->Comments()->/** @scrutinizer ignore-call */ sort('ID')->column('ID');
Loading history...
540
        $this->assertEquals(array($comment1->ID, $newComment->ID), $team1CommentIDs);
541
542
        // Test that removing an item from a list doesn't remove it from the same
543
        // relation belonging to a different object
544
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
545
        $team2 = $this->objFromFixture(DataObjectTest\Team::class, 'team2');
546
        $team2->Comments()->remove($comment1);
547
        $team1CommentIDs = $team1->Comments()->sort('ID')->column('ID');
548
        $this->assertEquals(array($comment1->ID, $newComment->ID), $team1CommentIDs);
549
    }
550
551
552
    /**
553
     * Test has many relationships against polymorphic has_one fields
554
     *   - Test getComponents() gets the ComponentSet of the other side of the relation
555
     *   - Test the IDs on the DataObjects are set correctly
556
     */
557
    public function testHasManyPolymorphicRelationships()
558
    {
559
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
560
561
        // Test getComponents() gets the ComponentSet of the other side of the relation
562
        $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

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

619
            $team1->/** @scrutinizer ignore-call */ 
620
                    Captain()->ID,
Loading history...
620
            'The captain exists for team 1'
621
        );
622
        $this->assertEquals(
623
            $player1->ID,
624
            $team1->getComponent('Captain')->ID,
625
            'The captain exists through the component getter'
626
        );
627
628
        $this->assertEquals(
629
            $team1->Captain()->FirstName,
630
            'Player 1',
631
            'Player 1 is the captain'
632
        );
633
        $this->assertEquals(
634
            $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...
635
            'Player 1',
636
            'Player 1 is the captain'
637
        );
638
639
        $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...
640
        $team1->write();
641
642
        $this->assertEquals($player2->ID, $team1->Captain()->ID);
643
        $this->assertEquals($player2->ID, $team1->getComponent('Captain')->ID);
644
        $this->assertEquals('Player 2', $team1->Captain()->FirstName);
645
        $this->assertEquals('Player 2', $team1->getComponent('Captain')->FirstName);
646
647
648
        // Set the favourite team for fan1
649
        $fan1->setField('FavouriteID', $team1->ID);
650
        $fan1->setField('FavouriteClass', get_class($team1));
651
652
        $this->assertEquals($team1->ID, $fan1->Favourite()->ID, 'The team is assigned to fan 1');
653
        $this->assertInstanceOf(get_class($team1), $fan1->Favourite(), 'The team is assigned to fan 1');
654
        $this->assertEquals(
655
            $team1->ID,
656
            $fan1->getComponent('Favourite')->ID,
657
            'The team exists through the component getter'
658
        );
659
        $this->assertInstanceOf(
660
            get_class($team1),
661
            $fan1->getComponent('Favourite'),
662
            'The team exists through the component getter'
663
        );
664
665
        $this->assertEquals(
666
            $fan1->Favourite()->Title,
667
            'Team 1',
668
            'Team 1 is the favourite'
669
        );
670
        $this->assertEquals(
671
            $fan1->getComponent('Favourite')->Title,
672
            'Team 1',
673
            'Team 1 is the favourite'
674
        );
675
    }
676
677
    /**
678
     * @todo Extend type change tests (e.g. '0'==NULL)
679
     */
680
    public function testChangedFields()
681
    {
682
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
683
        $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...
684
        $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...
685
686
        $this->assertEquals(
687
            $obj->getChangedFields(true, DataObject::CHANGE_STRICT),
688
            array(
689
                'FirstName' => array(
690
                    'before' => 'Captain',
691
                    'after' => 'Captain-changed',
692
                    'level' => DataObject::CHANGE_VALUE
693
                ),
694
                'IsRetired' => array(
695
                    'before' => 1,
696
                    'after' => true,
697
                    'level' => DataObject::CHANGE_STRICT
698
                )
699
            ),
700
            'Changed fields are correctly detected with strict type changes (level=1)'
701
        );
702
703
        $this->assertEquals(
704
            $obj->getChangedFields(true, DataObject::CHANGE_VALUE),
705
            array(
706
                'FirstName' => array(
707
                    'before' => 'Captain',
708
                    'after' => 'Captain-changed',
709
                    'level' => DataObject::CHANGE_VALUE
710
                )
711
            ),
712
            'Changed fields are correctly detected while ignoring type changes (level=2)'
713
        );
714
715
        $newObj = new DataObjectTest\Player();
716
        $newObj->FirstName = "New Player";
717
        $this->assertEquals(
718
            array(
719
                'FirstName' => array(
720
                    'before' => null,
721
                    'after' => 'New Player',
722
                    'level' => DataObject::CHANGE_VALUE
723
                )
724
            ),
725
            $newObj->getChangedFields(true, DataObject::CHANGE_VALUE),
726
            'Initialised fields are correctly detected as full changes'
727
        );
728
    }
729
730
    /**
731
     * @skipUpgrade
732
     */
733
    public function testIsChanged()
734
    {
735
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
736
        $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...
737
        $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...
738
        $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...
739
740
        // Now that DB fields are changed, isChanged is true
741
        $this->assertTrue($obj->isChanged('NonDBField'));
742
        $this->assertFalse($obj->isChanged('NonField'));
743
        $this->assertTrue($obj->isChanged('FirstName', DataObject::CHANGE_STRICT));
744
        $this->assertTrue($obj->isChanged('FirstName', DataObject::CHANGE_VALUE));
745
        $this->assertTrue($obj->isChanged('IsRetired', DataObject::CHANGE_STRICT));
746
        $this->assertFalse($obj->isChanged('IsRetired', DataObject::CHANGE_VALUE));
747
        $this->assertFalse($obj->isChanged('Email', 1), 'Doesnt change mark unchanged property');
748
        $this->assertFalse($obj->isChanged('Email', 2), 'Doesnt change mark unchanged property');
749
750
        $newObj = new DataObjectTest\Player();
751
        $newObj->FirstName = "New Player";
752
        $this->assertTrue($newObj->isChanged('FirstName', DataObject::CHANGE_STRICT));
753
        $this->assertTrue($newObj->isChanged('FirstName', DataObject::CHANGE_VALUE));
754
        $this->assertFalse($newObj->isChanged('Email', DataObject::CHANGE_STRICT));
755
        $this->assertFalse($newObj->isChanged('Email', DataObject::CHANGE_VALUE));
756
757
        $newObj->write();
758
        $this->assertFalse($newObj->ischanged());
759
        $this->assertFalse($newObj->isChanged('FirstName', DataObject::CHANGE_STRICT));
760
        $this->assertFalse($newObj->isChanged('FirstName', DataObject::CHANGE_VALUE));
761
        $this->assertFalse($newObj->isChanged('Email', DataObject::CHANGE_STRICT));
762
        $this->assertFalse($newObj->isChanged('Email', DataObject::CHANGE_VALUE));
763
764
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
765
        $obj->FirstName = null;
766
        $this->assertTrue($obj->isChanged('FirstName', DataObject::CHANGE_STRICT));
767
        $this->assertTrue($obj->isChanged('FirstName', DataObject::CHANGE_VALUE));
768
769
        /* Test when there's not field provided */
770
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain2');
771
        $this->assertFalse($obj->isChanged());
772
        $obj->NonDBField = 'new value';
773
        $this->assertFalse($obj->isChanged());
774
        $obj->FirstName = "New Player";
775
        $this->assertTrue($obj->isChanged());
776
777
        $obj->write();
778
        $this->assertFalse($obj->isChanged());
779
    }
780
781
    public function testRandomSort()
782
    {
783
        /* If we perform the same regularly sorted query twice, it should return the same results */
784
        $itemsA = DataObject::get(DataObjectTest\TeamComment::class, "", "ID");
785
        foreach ($itemsA as $item) {
786
            $keysA[] = $item->ID;
787
        }
788
789
        $itemsB = DataObject::get(DataObjectTest\TeamComment::class, "", "ID");
790
        foreach ($itemsB as $item) {
791
            $keysB[] = $item->ID;
792
        }
793
794
        /* Test when there's not field provided */
795
        $obj = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
796
        $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...
797
        $this->assertTrue($obj->isChanged());
798
799
        $obj->write();
800
        $this->assertFalse($obj->isChanged());
801
802
        /* If we perform the same random query twice, it shouldn't return the same results */
803
        $itemsA = DataObject::get(DataObjectTest\TeamComment::class, "", DB::get_conn()->random());
804
        $itemsB = DataObject::get(DataObjectTest\TeamComment::class, "", DB::get_conn()->random());
805
        $itemsC = DataObject::get(DataObjectTest\TeamComment::class, "", DB::get_conn()->random());
806
        $itemsD = DataObject::get(DataObjectTest\TeamComment::class, "", DB::get_conn()->random());
807
        foreach ($itemsA as $item) {
808
            $keysA[] = $item->ID;
809
        }
810
        foreach ($itemsB as $item) {
811
            $keysB[] = $item->ID;
812
        }
813
        foreach ($itemsC as $item) {
814
            $keysC[] = $item->ID;
815
        }
816
        foreach ($itemsD as $item) {
817
            $keysD[] = $item->ID;
818
        }
819
820
        // These shouldn't all be the same (run it 4 times to minimise chance of an accidental collision)
821
        // There's about a 1 in a billion chance of an accidental collision
822
        $this->assertTrue($keysA != $keysB || $keysB != $keysC || $keysC != $keysD);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $keysD seems to be defined by a foreach iteration on line 816. 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 813. 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 785. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
Comprehensibility Best Practice introduced by
The variable $keysB seems to be defined by a foreach iteration on line 790. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
823
    }
824
825
    public function testWriteSavesToHasOneRelations()
826
    {
827
        /* DataObject::write() should save to a has_one relationship if you set a field called (relname)ID */
828
        $team = new DataObjectTest\Team();
829
        $captainID = $this->idFromFixture(DataObjectTest\Player::class, 'player1');
830
        $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...
831
        $team->write();
832
        $this->assertEquals(
833
            $captainID,
834
            DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $team->ID")->value()
835
        );
836
837
        /* After giving it a value, you should also be able to set it back to null */
838
        $team->CaptainID = '';
839
        $team->write();
840
        $this->assertEquals(
841
            0,
842
            DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $team->ID")->value()
843
        );
844
845
        /* You should also be able to save a blank to it when it's first created */
846
        $team = new DataObjectTest\Team();
847
        $team->CaptainID = '';
848
        $team->write();
849
        $this->assertEquals(
850
            0,
851
            DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $team->ID")->value()
852
        );
853
854
        /* Ditto for existing records without a value */
855
        $existingTeam = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
856
        $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...
857
        $existingTeam->write();
858
        $this->assertEquals(
859
            0,
860
            DB::query("SELECT \"CaptainID\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $existingTeam->ID")->value()
861
        );
862
    }
863
864
    public function testCanAccessHasOneObjectsAsMethods()
865
    {
866
        /* If you have a has_one relation 'Captain' on $obj, and you set the $obj->CaptainID = (ID), then the
867
        * object itself should be accessible as $obj->Captain() */
868
        $team = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
869
        $captainID = $this->idFromFixture(DataObjectTest\Player::class, 'captain1');
870
871
        $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...
872
        $this->assertNotNull($team->Captain());
873
        $this->assertEquals($captainID, $team->Captain()->ID);
874
875
        // Test for polymorphic has_one relations
876
        $fan = $this->objFromFixture(DataObjectTest\Fan::class, 'fan1');
877
        $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...
878
        $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...
879
        $this->assertNotNull($fan->Favourite());
880
        $this->assertEquals($team->ID, $fan->Favourite()->ID);
881
        $this->assertInstanceOf(DataObjectTest\Team::class, $fan->Favourite());
882
    }
883
884
    public function testFieldNamesThatMatchMethodNamesWork()
885
    {
886
        /* Check that a field name that corresponds to a method on DataObject will still work */
887
        $obj = new DataObjectTest\Fixture();
888
        $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...
889
        $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...
890
        $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...
891
        $obj->write();
892
893
        $this->assertNotNull($obj->ID);
894
        $this->assertEquals(
895
            'value1',
896
            DB::query("SELECT \"Data\" FROM \"DataObjectTest_Fixture\" WHERE \"ID\" = $obj->ID")->value()
897
        );
898
        $this->assertEquals(
899
            'value2',
900
            DB::query("SELECT \"DbObject\" FROM \"DataObjectTest_Fixture\" WHERE \"ID\" = $obj->ID")->value()
901
        );
902
        $this->assertEquals(
903
            'value3',
904
            DB::query("SELECT \"Duplicate\" FROM \"DataObjectTest_Fixture\" WHERE \"ID\" = $obj->ID")->value()
905
        );
906
    }
907
908
    /**
909
     * @todo Re-enable all test cases for field existence after behaviour has been fixed
910
     */
911
    public function testFieldExistence()
912
    {
913
        $teamInstance = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
914
        $teamSingleton = singleton(DataObjectTest\Team::class);
915
916
        $subteamInstance = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam1');
917
        $schema = DataObject::getSchema();
918
919
        /* hasField() singleton checks */
920
        $this->assertTrue(
921
            $teamSingleton->hasField('ID'),
922
            'hasField() finds built-in fields in singletons'
923
        );
924
        $this->assertTrue(
925
            $teamSingleton->hasField('Title'),
926
            'hasField() finds custom fields in singletons'
927
        );
928
929
        /* hasField() instance checks */
930
        $this->assertFalse(
931
            $teamInstance->hasField('NonExistingField'),
932
            'hasField() doesnt find non-existing fields in instances'
933
        );
934
        $this->assertTrue(
935
            $teamInstance->hasField('ID'),
936
            'hasField() finds built-in fields in instances'
937
        );
938
        $this->assertTrue(
939
            $teamInstance->hasField('Created'),
940
            'hasField() finds built-in fields in instances'
941
        );
942
        $this->assertTrue(
943
            $teamInstance->hasField('DatabaseField'),
944
            'hasField() finds custom fields in instances'
945
        );
946
        //$this->assertFalse($teamInstance->hasField('SubclassDatabaseField'),
0 ignored issues
show
Unused Code Comprehensibility introduced by
82% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
947
        //'hasField() doesnt find subclass fields in parentclass instances');
948
        $this->assertTrue(
949
            $teamInstance->hasField('DynamicField'),
950
            'hasField() finds dynamic getters in instances'
951
        );
952
        $this->assertTrue(
953
            $teamInstance->hasField('HasOneRelationshipID'),
954
            'hasField() finds foreign keys in instances'
955
        );
956
        $this->assertTrue(
957
            $teamInstance->hasField('ExtendedDatabaseField'),
958
            'hasField() finds extended fields in instances'
959
        );
960
        $this->assertTrue(
961
            $teamInstance->hasField('ExtendedHasOneRelationshipID'),
962
            'hasField() finds extended foreign keys in instances'
963
        );
964
        //$this->assertTrue($teamInstance->hasField('ExtendedDynamicField'),
0 ignored issues
show
Unused Code Comprehensibility introduced by
82% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
965
        //'hasField() includes extended dynamic getters in instances');
966
967
        /* hasField() subclass checks */
968
        $this->assertTrue(
969
            $subteamInstance->hasField('ID'),
970
            'hasField() finds built-in fields in subclass instances'
971
        );
972
        $this->assertTrue(
973
            $subteamInstance->hasField('Created'),
974
            'hasField() finds built-in fields in subclass instances'
975
        );
976
        $this->assertTrue(
977
            $subteamInstance->hasField('DatabaseField'),
978
            'hasField() finds custom fields in subclass instances'
979
        );
980
        $this->assertTrue(
981
            $subteamInstance->hasField('SubclassDatabaseField'),
982
            'hasField() finds custom fields in subclass instances'
983
        );
984
        $this->assertTrue(
985
            $subteamInstance->hasField('DynamicField'),
986
            'hasField() finds dynamic getters in subclass instances'
987
        );
988
        $this->assertTrue(
989
            $subteamInstance->hasField('HasOneRelationshipID'),
990
            'hasField() finds foreign keys in subclass instances'
991
        );
992
        $this->assertTrue(
993
            $subteamInstance->hasField('ExtendedDatabaseField'),
994
            'hasField() finds extended fields in subclass instances'
995
        );
996
        $this->assertTrue(
997
            $subteamInstance->hasField('ExtendedHasOneRelationshipID'),
998
            'hasField() finds extended foreign keys in subclass instances'
999
        );
1000
1001
        /* hasDatabaseField() singleton checks */
1002
        //$this->assertTrue($teamSingleton->hasDatabaseField('ID'),
0 ignored issues
show
Unused Code Comprehensibility introduced by
82% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1003
        //'hasDatabaseField() finds built-in fields in singletons');
1004
        $this->assertNotEmpty(
1005
            $schema->fieldSpec(DataObjectTest\Team::class, 'Title'),
1006
            'hasDatabaseField() finds custom fields in singletons'
1007
        );
1008
1009
        /* hasDatabaseField() instance checks */
1010
        $this->assertNull(
1011
            $schema->fieldSpec(DataObjectTest\Team::class, 'NonExistingField'),
1012
            'hasDatabaseField() doesnt find non-existing fields in instances'
1013
        );
1014
        //$this->assertNotEmpty($schema->fieldSpec(DataObjectTest_Team::class, 'ID'),
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1015
        //'hasDatabaseField() finds built-in fields in instances');
1016
        $this->assertNotEmpty(
1017
            $schema->fieldSpec(DataObjectTest\Team::class, 'Created'),
1018
            'hasDatabaseField() finds built-in fields in instances'
1019
        );
1020
        $this->assertNotEmpty(
1021
            $schema->fieldSpec(DataObjectTest\Team::class, 'DatabaseField'),
1022
            'hasDatabaseField() finds custom fields in instances'
1023
        );
1024
        $this->assertNull(
1025
            $schema->fieldSpec(DataObjectTest\Team::class, 'SubclassDatabaseField'),
1026
            'hasDatabaseField() doesnt find subclass fields in parentclass instances'
1027
        );
1028
        //$this->assertNull($schema->fieldSpec(DataObjectTest_Team::class, 'DynamicField'),
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1029
        //'hasDatabaseField() doesnt dynamic getters in instances');
1030
        $this->assertNotEmpty(
1031
            $schema->fieldSpec(DataObjectTest\Team::class, 'HasOneRelationshipID'),
1032
            'hasDatabaseField() finds foreign keys in instances'
1033
        );
1034
        $this->assertNotEmpty(
1035
            $schema->fieldSpec(DataObjectTest\Team::class, 'ExtendedDatabaseField'),
1036
            'hasDatabaseField() finds extended fields in instances'
1037
        );
1038
        $this->assertNotEmpty(
1039
            $schema->fieldSpec(DataObjectTest\Team::class, 'ExtendedHasOneRelationshipID'),
1040
            'hasDatabaseField() finds extended foreign keys in instances'
1041
        );
1042
        $this->assertNull(
1043
            $schema->fieldSpec(DataObjectTest\Team::class, 'ExtendedDynamicField'),
1044
            'hasDatabaseField() doesnt include extended dynamic getters in instances'
1045
        );
1046
1047
        /* hasDatabaseField() subclass checks */
1048
        $this->assertNotEmpty(
1049
            $schema->fieldSpec(DataObjectTest\SubTeam::class, 'DatabaseField'),
1050
            'hasField() finds custom fields in subclass instances'
1051
        );
1052
        $this->assertNotEmpty(
1053
            $schema->fieldSpec(DataObjectTest\SubTeam::class, 'SubclassDatabaseField'),
1054
            'hasField() finds custom fields in subclass instances'
1055
        );
1056
    }
1057
1058
    /**
1059
     * @todo Re-enable all test cases for field inheritance aggregation after behaviour has been fixed
1060
     */
1061
    public function testFieldInheritance()
1062
    {
1063
        $schema = DataObject::getSchema();
1064
1065
        // Test logical fields (including composite)
1066
        $teamSpecifications = $schema->fieldSpecs(DataObjectTest\Team::class);
1067
        $this->assertEquals(
1068
            array(
1069
                'ID',
1070
                'ClassName',
1071
                'LastEdited',
1072
                'Created',
1073
                'Title',
1074
                'DatabaseField',
1075
                'ExtendedDatabaseField',
1076
                'CaptainID',
1077
                'FounderID',
1078
                'HasOneRelationshipID',
1079
                'ExtendedHasOneRelationshipID'
1080
            ),
1081
            array_keys($teamSpecifications),
1082
            'fieldSpecifications() contains all fields defined on instance: base, extended and foreign keys'
1083
        );
1084
1085
        $teamFields = $schema->databaseFields(DataObjectTest\Team::class, false);
1086
        $this->assertEquals(
1087
            array(
1088
                'ID',
1089
                'ClassName',
1090
                'LastEdited',
1091
                'Created',
1092
                'Title',
1093
                'DatabaseField',
1094
                'ExtendedDatabaseField',
1095
                'CaptainID',
1096
                'FounderID',
1097
                'HasOneRelationshipID',
1098
                'ExtendedHasOneRelationshipID'
1099
            ),
1100
            array_keys($teamFields),
1101
            'databaseFields() contains only fields defined on instance, including base, extended and foreign keys'
1102
        );
1103
1104
        $subteamSpecifications = $schema->fieldSpecs(DataObjectTest\SubTeam::class);
1105
        $this->assertEquals(
1106
            array(
1107
                'ID',
1108
                'ClassName',
1109
                'LastEdited',
1110
                'Created',
1111
                'Title',
1112
                'DatabaseField',
1113
                'ExtendedDatabaseField',
1114
                'CaptainID',
1115
                'FounderID',
1116
                'HasOneRelationshipID',
1117
                'ExtendedHasOneRelationshipID',
1118
                'SubclassDatabaseField',
1119
                'ParentTeamID',
1120
            ),
1121
            array_keys($subteamSpecifications),
1122
            'fieldSpecifications() on subclass contains all fields, including base, extended  and foreign keys'
1123
        );
1124
1125
        $subteamFields = $schema->databaseFields(DataObjectTest\SubTeam::class, false);
1126
        $this->assertEquals(
1127
            array(
1128
                'ID',
1129
                'SubclassDatabaseField',
1130
                'ParentTeamID',
1131
            ),
1132
            array_keys($subteamFields),
1133
            'databaseFields() on subclass contains only fields defined on instance'
1134
        );
1135
    }
1136
1137
    public function testSearchableFields()
1138
    {
1139
        $player = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
1140
        $fields = $player->searchableFields();
1141
        $this->assertArrayHasKey(
1142
            'IsRetired',
1143
            $fields,
1144
            'Fields defined by $searchable_fields static are correctly detected'
1145
        );
1146
        $this->assertArrayHasKey(
1147
            'ShirtNumber',
1148
            $fields,
1149
            'Fields defined by $searchable_fields static are correctly detected'
1150
        );
1151
1152
        $team = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1153
        $fields = $team->searchableFields();
1154
        $this->assertArrayHasKey(
1155
            'Title',
1156
            $fields,
1157
            'Fields can be inherited from the $summary_fields static, including methods called on fields'
1158
        );
1159
        $this->assertArrayHasKey(
1160
            'Captain.ShirtNumber',
1161
            $fields,
1162
            'Fields on related objects can be inherited from the $summary_fields static'
1163
        );
1164
        $this->assertArrayHasKey(
1165
            'Captain.FavouriteTeam.Title',
1166
            $fields,
1167
            'Fields on related objects can be inherited from the $summary_fields static'
1168
        );
1169
1170
        $testObj = new DataObjectTest\Fixture();
1171
        $fields = $testObj->searchableFields();
1172
        $this->assertEmpty($fields);
1173
    }
1174
1175
    public function testCastingHelper()
1176
    {
1177
        $team = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1178
1179
        $this->assertEquals('Varchar', $team->castingHelper('Title'), 'db field wasn\'t casted correctly');
1180
        $this->assertEquals('HTMLVarchar', $team->castingHelper('DatabaseField'), 'db field wasn\'t casted correctly');
1181
1182
        $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

1182
        $sponsor = $team->/** @scrutinizer ignore-call */ Sponsors()->first();
Loading history...
1183
        $this->assertEquals('Int', $sponsor->castingHelper('SponsorFee'), 'many_many_extraFields not casted correctly');
1184
    }
1185
1186
    public function testSummaryFieldsCustomLabels()
1187
    {
1188
        $team = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1189
        $summaryFields = $team->summaryFields();
1190
1191
        $this->assertEquals(
1192
            [
1193
                'Title' => 'Custom Title',
1194
                'Title.UpperCase' => 'Title',
1195
                'Captain.ShirtNumber' => 'Captain\'s shirt number',
1196
                'Captain.FavouriteTeam.Title' => 'Captain\'s favourite team',
1197
            ],
1198
            $summaryFields
1199
        );
1200
    }
1201
1202
    public function testDataObjectUpdate()
1203
    {
1204
        /* update() calls can use the dot syntax to reference has_one relations and other methods that return
1205
        * objects */
1206
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1207
        $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...
1208
1209
        $team1->update(
1210
            array(
1211
                'DatabaseField' => 'Something',
1212
                'Captain.FirstName' => 'Jim',
1213
                'Captain.Email' => '[email protected]',
1214
                'Captain.FavouriteTeam.Title' => 'New and improved team 1',
1215
            )
1216
        );
1217
1218
        /* Test the simple case of updating fields on the object itself */
1219
        $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...
1220
1221
        /* Setting Captain.Email and Captain.FirstName will have updated DataObjectTest_Captain.captain1 in
1222
        * the database.  Although update() doesn't usually write, it does write related records automatically. */
1223
        $captain1 = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
1224
        $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...
1225
        $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...
1226
1227
        /* Jim's favourite team is team 1; we need to reload the object to the the change that setting Captain.
1228
        * FavouriteTeam.Title made */
1229
        $reloadedTeam1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1230
        $this->assertEquals('New and improved team 1', $reloadedTeam1->Title);
1231
    }
1232
1233
    public function testDataObjectUpdateNew()
1234
    {
1235
        /* update() calls can use the dot syntax to reference has_one relations and other methods that return
1236
        * objects */
1237
        $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1238
        $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...
1239
1240
        $team1->update(
1241
            array(
1242
                'Captain.FirstName' => 'Jim',
1243
                'Captain.FavouriteTeam.Title' => 'New and improved team 1',
1244
            )
1245
        );
1246
        /* Test that the captain ID has been updated */
1247
        $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...
1248
1249
        /* Fetch the newly created captain */
1250
        $captain1 = DataObjectTest\Player::get()->byID($team1->CaptainID);
1251
        $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...
1252
1253
        /* Grab the favourite team and make sure it has the correct values */
1254
        $reloadedTeam1 = $captain1->FavouriteTeam();
1255
        $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...
1256
        $this->assertEquals('New and improved team 1', $reloadedTeam1->Title);
1257
    }
1258
1259
1260
    /**
1261
     * @expectedException \SilverStripe\ORM\ValidationException
1262
     */
1263
    public function testWritingInvalidDataObjectThrowsException()
1264
    {
1265
        $validatedObject = new DataObjectTest\ValidatedObject();
1266
        $validatedObject->write();
1267
    }
1268
1269
    public function testWritingValidDataObjectDoesntThrowException()
1270
    {
1271
        $validatedObject = new DataObjectTest\ValidatedObject();
1272
        $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...
1273
1274
        $validatedObject->write();
1275
        $this->assertTrue($validatedObject->isInDB(), "Validated object was not saved to database");
1276
    }
1277
1278
    public function testSubclassCreation()
1279
    {
1280
        /* Creating a new object of a subclass should set the ClassName field correctly */
1281
        $obj = new DataObjectTest\SubTeam();
1282
        $obj->write();
1283
        $this->assertEquals(
1284
            DataObjectTest\SubTeam::class,
1285
            DB::query("SELECT \"ClassName\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $obj->ID")->value()
1286
        );
1287
    }
1288
1289
    public function testForceInsert()
1290
    {
1291
        /* If you set an ID on an object and pass forceInsert = true, then the object should be correctly created */
1292
        $conn = DB::get_conn();
1293
        if (method_exists($conn, 'allowPrimaryKeyEditing')) {
1294
            $conn->allowPrimaryKeyEditing(DataObjectTest\Team::class, true);
1295
        }
1296
        $obj = new DataObjectTest\SubTeam();
1297
        $obj->ID = 1001;
1298
        $obj->Title = 'asdfasdf';
1299
        $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...
1300
        $obj->write(false, true);
1301
        if (method_exists($conn, 'allowPrimaryKeyEditing')) {
1302
            $conn->allowPrimaryKeyEditing(DataObjectTest\Team::class, false);
1303
        }
1304
1305
        $this->assertEquals(
1306
            DataObjectTest\SubTeam::class,
1307
            DB::query("SELECT \"ClassName\" FROM \"DataObjectTest_Team\" WHERE \"ID\" = $obj->ID")->value()
1308
        );
1309
1310
        /* Check that it actually saves to the database with the correct ID */
1311
        $this->assertEquals(
1312
            "1001",
1313
            DB::query(
1314
                "SELECT \"ID\" FROM \"DataObjectTest_SubTeam\" WHERE \"SubclassDatabaseField\" = 'asdfasdf'"
1315
            )->value()
1316
        );
1317
        $this->assertEquals(
1318
            "1001",
1319
            DB::query("SELECT \"ID\" FROM \"DataObjectTest_Team\" WHERE \"Title\" = 'asdfasdf'")->value()
1320
        );
1321
    }
1322
1323
    public function testHasOwnTable()
1324
    {
1325
        $schema = DataObject::getSchema();
1326
        /* Test DataObject::has_own_table() returns true if the object has $has_one or $db values */
1327
        $this->assertTrue($schema->classHasTable(DataObjectTest\Player::class));
1328
        $this->assertTrue($schema->classHasTable(DataObjectTest\Team::class));
1329
        $this->assertTrue($schema->classHasTable(DataObjectTest\Fixture::class));
1330
1331
        /* Root DataObject that always have a table, even if they lack both $db and $has_one */
1332
        $this->assertTrue($schema->classHasTable(DataObjectTest\FieldlessTable::class));
1333
1334
        /* Subclasses without $db or $has_one don't have a table */
1335
        $this->assertFalse($schema->classHasTable(DataObjectTest\FieldlessSubTable::class));
1336
1337
        /* Return false if you don't pass it a subclass of DataObject */
1338
        $this->assertFalse($schema->classHasTable(DataObject::class));
1339
        $this->assertFalse($schema->classHasTable(ViewableData::class));
1340
1341
        /* Invalid class name */
1342
        $this->assertFalse($schema->classHasTable("ThisIsntADataObject"));
1343
    }
1344
1345
    public function testMerge()
1346
    {
1347
        // test right merge of subclasses
1348
        $left = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam1');
1349
        $right = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam2_with_player_relation');
1350
        $leftOrigID = $left->ID;
1351
        $left->merge($right, 'right', false, false);
1352
        $this->assertEquals(
1353
            $left->Title,
1354
            'Subteam 2',
1355
            'merge() with "right" priority overwrites fields with existing values on subclasses'
1356
        );
1357
        $this->assertEquals(
1358
            $left->ID,
1359
            $leftOrigID,
1360
            'merge() with "right" priority doesnt overwrite database ID'
1361
        );
1362
1363
        // test overwriteWithEmpty flag on existing left values
1364
        $left = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam2_with_player_relation');
1365
        $right = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam3_with_empty_fields');
1366
        $left->merge($right, 'right', false, true);
1367
        $this->assertEquals(
1368
            $left->Title,
1369
            'Subteam 3',
1370
            'merge() with $overwriteWithEmpty overwrites non-empty fields on left object'
1371
        );
1372
1373
        // test overwriteWithEmpty flag on empty left values
1374
        $left = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam1');
1375
        // $SubclassDatabaseField is empty on here
1376
        $right = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam2_with_player_relation');
1377
        $left->merge($right, 'right', false, true);
1378
        $this->assertEquals(
1379
            $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...
1380
            null,
1381
            'merge() with $overwriteWithEmpty overwrites empty fields on left object'
1382
        );
1383
1384
        // @todo test "left" priority flag
1385
        // @todo test includeRelations flag
1386
        // @todo test includeRelations in combination with overwriteWithEmpty
1387
        // @todo test has_one relations
1388
        // @todo test has_many and many_many relations
1389
    }
1390
1391
    public function testPopulateDefaults()
1392
    {
1393
        $obj = new DataObjectTest\Fixture();
1394
        $this->assertEquals(
1395
            $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...
1396
            'Default Value',
1397
            'Defaults are populated for in-memory object from $defaults array'
1398
        );
1399
1400
        $this->assertEquals(
1401
            $obj->MyFieldWithAltDefault,
1402
            'Default Value',
1403
            'Defaults are populated from overloaded populateDefaults() method'
1404
        );
1405
    }
1406
1407
    /**
1408
     * @expectedException \InvalidArgumentException
1409
     */
1410
    public function testValidateModelDefinitionsFailsWithArray()
1411
    {
1412
        Config::modify()->merge(DataObjectTest\Team::class, 'has_one', array('NotValid' => array('NoArraysAllowed')));
1413
        DataObject::getSchema()->hasOneComponent(DataObjectTest\Team::class, 'NotValid');
1414
    }
1415
1416
    /**
1417
     * @expectedException \InvalidArgumentException
1418
     */
1419
    public function testValidateModelDefinitionsFailsWithIntKey()
1420
    {
1421
        Config::modify()->set(DataObjectTest\Team::class, 'has_many', array(0 => DataObjectTest\Player::class));
1422
        DataObject::getSchema()->hasManyComponent(DataObjectTest\Team::class, 0);
1423
    }
1424
1425
    /**
1426
     * @expectedException \InvalidArgumentException
1427
     */
1428
    public function testValidateModelDefinitionsFailsWithIntValue()
1429
    {
1430
        Config::modify()->merge(DataObjectTest\Team::class, 'many_many', array('Players' => 12));
1431
        DataObject::getSchema()->manyManyComponent(DataObjectTest\Team::class, 'Players');
1432
    }
1433
1434
    public function testNewClassInstance()
1435
    {
1436
        $dataObject = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1437
        $changedDO = $dataObject->newClassInstance(DataObjectTest\SubTeam::class);
1438
        $changedFields = $changedDO->getChangedFields();
1439
1440
        // Don't write the record, it will reset changed fields
1441
        $this->assertInstanceOf(DataObjectTest\SubTeam::class, $changedDO);
1442
        $this->assertEquals($changedDO->ClassName, DataObjectTest\SubTeam::class);
1443
        $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...
1444
        $this->assertContains('ClassName', array_keys($changedFields));
1445
        $this->assertEquals($changedFields['ClassName']['before'], DataObjectTest\Team::class);
1446
        $this->assertEquals($changedFields['ClassName']['after'], DataObjectTest\SubTeam::class);
1447
        $this->assertEquals($changedFields['RecordClassName']['before'], DataObjectTest\Team::class);
1448
        $this->assertEquals($changedFields['RecordClassName']['after'], DataObjectTest\SubTeam::class);
1449
1450
        $changedDO->write();
1451
1452
        $this->assertInstanceOf(DataObjectTest\SubTeam::class, $changedDO);
1453
        $this->assertEquals($changedDO->ClassName, DataObjectTest\SubTeam::class);
1454
1455
        // Test invalid classes fail
1456
        $this->expectException(InvalidArgumentException::class);
1457
        $this->expectExceptionMessage('Controller is not a valid subclass of DataObject');
1458
        /**
1459
         * @skipUpgrade
1460
         */
1461
        $dataObject->newClassInstance('Controller');
1462
    }
1463
1464
    public function testMultipleManyManyWithSameClass()
1465
    {
1466
        $team = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1467
        $company2 = $this->objFromFixture(DataObjectTest\EquipmentCompany::class, 'equipmentcompany2');
1468
        $sponsors = $team->Sponsors();
1469
        $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

1469
        /** @scrutinizer ignore-call */ 
1470
        $equipmentSuppliers = $team->EquipmentSuppliers();
Loading history...
1470
1471
        // Check that DataObject::many_many() works as expected
1472
        $manyManyComponent = DataObject::getSchema()->manyManyComponent(DataObjectTest\Team::class, 'Sponsors');
1473
        $this->assertEquals(ManyManyList::class, $manyManyComponent['relationClass']);
1474
        $this->assertEquals(
1475
            DataObjectTest\Team::class,
1476
            $manyManyComponent['parentClass'],
1477
            'DataObject::many_many() didn\'t find the correct base class'
1478
        );
1479
        $this->assertEquals(
1480
            DataObjectTest\EquipmentCompany::class,
1481
            $manyManyComponent['childClass'],
1482
            'DataObject::many_many() didn\'t find the correct target class for the relation'
1483
        );
1484
        $this->assertEquals(
1485
            'DataObjectTest_EquipmentCompany_SponsoredTeams',
1486
            $manyManyComponent['join'],
1487
            'DataObject::many_many() didn\'t find the correct relation table'
1488
        );
1489
        $this->assertEquals('DataObjectTest_TeamID', $manyManyComponent['parentField']);
1490
        $this->assertEquals('DataObjectTest_EquipmentCompanyID', $manyManyComponent['childField']);
1491
1492
        // Check that ManyManyList still works
1493
        $this->assertEquals(2, $sponsors->count(), 'Rows are missing from relation');
1494
        $this->assertEquals(1, $equipmentSuppliers->count(), 'Rows are missing from relation');
1495
1496
        // Check everything works when no relation is present
1497
        $teamWithoutSponsor = $this->objFromFixture(DataObjectTest\Team::class, 'team3');
1498
        $this->assertInstanceOf(ManyManyList::class, $teamWithoutSponsor->Sponsors());
1499
        $this->assertEquals(0, $teamWithoutSponsor->Sponsors()->count());
1500
1501
        // Test that belongs_many_many can be infered from with getNonReciprocalComponent
1502
        $this->assertListEquals(
1503
            [
1504
                ['Name' => 'Company corp'],
1505
                ['Name' => 'Team co.'],
1506
            ],
1507
            $team->inferReciprocalComponent(DataObjectTest\EquipmentCompany::class, 'SponsoredTeams')
0 ignored issues
show
Bug introduced by
$team->inferReciprocalCo...lass, 'SponsoredTeams') of type SilverStripe\ORM\DataObject is incompatible with the type SilverStripe\ORM\SS_List expected by parameter $list of SilverStripe\Dev\SapphireTest::assertListEquals(). ( Ignorable by Annotation )

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

1507
            /** @scrutinizer ignore-type */ $team->inferReciprocalComponent(DataObjectTest\EquipmentCompany::class, 'SponsoredTeams')
Loading history...
1508
        );
1509
1510
        // Test that many_many can be infered from getNonReciprocalComponent
1511
        $this->assertListEquals(
1512
            [
1513
                ['Title' => 'Team 1'],
1514
                ['Title' => 'Team 2'],
1515
                ['Title' => 'Subteam 1'],
1516
            ],
1517
            $company2->inferReciprocalComponent(DataObjectTest\Team::class, 'Sponsors')
1518
        );
1519
1520
        // Check many_many_extraFields still works
1521
        $equipmentCompany = $this->objFromFixture(DataObjectTest\EquipmentCompany::class, 'equipmentcompany1');
1522
        $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

1522
        $equipmentCompany->/** @scrutinizer ignore-call */ 
1523
                           SponsoredTeams()->add($teamWithoutSponsor, array('SponsorFee' => 1000));
Loading history...
1523
        $sponsoredTeams = $equipmentCompany->SponsoredTeams();
1524
        $this->assertEquals(
1525
            1000,
1526
            $sponsoredTeams->byID($teamWithoutSponsor->ID)->SponsorFee,
1527
            'Data from many_many_extraFields was not stored/extracted correctly'
1528
        );
1529
1530
        // Check subclasses correctly inherit multiple many_manys
1531
        $subTeam = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam1');
1532
        $this->assertEquals(
1533
            2,
1534
            $subTeam->Sponsors()->count(),
1535
            'Child class did not inherit multiple many_manys'
1536
        );
1537
        $this->assertEquals(
1538
            1,
1539
            $subTeam->EquipmentSuppliers()->count(),
1540
            'Child class did not inherit multiple many_manys'
1541
        );
1542
        // Team 2 has one EquipmentCompany sponsor and one SubEquipmentCompany
1543
        $team2 = $this->objFromFixture(DataObjectTest\Team::class, 'team2');
1544
        $this->assertEquals(
1545
            2,
1546
            $team2->Sponsors()->count(),
1547
            'Child class did not inherit multiple belongs_many_manys'
1548
        );
1549
1550
        // Check many_many_extraFields also works from the belongs_many_many side
1551
        $sponsors = $team2->Sponsors();
1552
        $sponsors->add($equipmentCompany, array('SponsorFee' => 750));
1553
        $this->assertEquals(
1554
            750,
1555
            $sponsors->byID($equipmentCompany->ID)->SponsorFee,
1556
            'Data from many_many_extraFields was not stored/extracted correctly'
1557
        );
1558
1559
        $subEquipmentCompany = $this->objFromFixture(DataObjectTest\SubEquipmentCompany::class, 'subequipmentcompany1');
1560
        $subTeam->Sponsors()->add($subEquipmentCompany, array('SponsorFee' => 1200));
1561
        $this->assertEquals(
1562
            1200,
1563
            $subTeam->Sponsors()->byID($subEquipmentCompany->ID)->SponsorFee,
1564
            'Data from inherited many_many_extraFields was not stored/extracted correctly'
1565
        );
1566
    }
1567
1568
    public function testManyManyExtraFields()
1569
    {
1570
        $team = $this->objFromFixture(DataObjectTest\Team::class, 'team1');
1571
        $schema = DataObject::getSchema();
1572
1573
        // Get all extra fields
1574
        $teamExtraFields = $team->manyManyExtraFields();
1575
        $this->assertEquals(
1576
            array(
1577
                'Players' => array('Position' => 'Varchar(100)')
1578
            ),
1579
            $teamExtraFields
1580
        );
1581
1582
        // Ensure fields from parent classes are included
1583
        $subTeam = singleton(DataObjectTest\SubTeam::class);
1584
        $teamExtraFields = $subTeam->manyManyExtraFields();
1585
        $this->assertEquals(
1586
            array(
1587
                'Players' => array('Position' => 'Varchar(100)'),
1588
                'FormerPlayers' => array('Position' => 'Varchar(100)')
1589
            ),
1590
            $teamExtraFields
1591
        );
1592
1593
        // Extra fields are immediately available on the Team class (defined in $many_many_extraFields)
1594
        $teamExtraFields = $schema->manyManyExtraFieldsForComponent(DataObjectTest\Team::class, 'Players');
1595
        $this->assertEquals(
1596
            $teamExtraFields,
1597
            array(
1598
                'Position' => 'Varchar(100)'
1599
            )
1600
        );
1601
1602
        // We'll have to go through the relation to get the extra fields on Player
1603
        $playerExtraFields = $schema->manyManyExtraFieldsForComponent(DataObjectTest\Player::class, 'Teams');
1604
        $this->assertEquals(
1605
            $playerExtraFields,
1606
            array(
1607
                'Position' => 'Varchar(100)'
1608
            )
1609
        );
1610
1611
        // Iterate through a many-many relationship and confirm that extra fields are included
1612
        $newTeam = new DataObjectTest\Team();
1613
        $newTeam->Title = "New team";
1614
        $newTeam->write();
1615
        $newTeamID = $newTeam->ID;
1616
1617
        $newPlayer = new DataObjectTest\Player();
1618
        $newPlayer->FirstName = "Sam";
1619
        $newPlayer->Surname = "Minnee";
1620
        $newPlayer->write();
1621
1622
        // The idea of Sam as a prop is essentially humourous.
1623
        $newTeam->Players()->add($newPlayer, array("Position" => "Prop"));
1624
1625
        // Requery and uncache everything
1626
        $newTeam->flushCache();
1627
        $newTeam = DataObject::get_by_id(DataObjectTest\Team::class, $newTeamID);
1628
1629
        // Check that the Position many_many_extraField is extracted.
1630
        $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

1630
        $player = $newTeam->/** @scrutinizer ignore-call */ Players()->first();
Loading history...
1631
        $this->assertEquals('Sam', $player->FirstName);
1632
        $this->assertEquals("Prop", $player->Position);
1633
1634
        // Check that ordering a many-many relation by an aggregate column doesn't fail
1635
        $player = $this->objFromFixture(DataObjectTest\Player::class, 'player2');
1636
        $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

1636
        $player->/** @scrutinizer ignore-call */ 
1637
                 Teams()->sort("count(DISTINCT \"DataObjectTest_Team_Players\".\"DataObjectTest_PlayerID\") DESC");
Loading history...
1637
    }
1638
1639
    /**
1640
     * Check that the queries generated for many-many relation queries can have unlimitedRowCount
1641
     * called on them.
1642
     */
1643
    public function testManyManyUnlimitedRowCount()
1644
    {
1645
        $player = $this->objFromFixture(DataObjectTest\Player::class, 'player2');
1646
        // TODO: What's going on here?
1647
        $this->assertEquals(2, $player->Teams()->dataQuery()->query()->unlimitedRowCount());
1648
    }
1649
1650
    /**
1651
     * Tests that singular_name() generates sensible defaults.
1652
     */
1653
    public function testSingularName()
1654
    {
1655
        $assertions = array(
1656
            DataObjectTest\Player::class => 'Player',
1657
            DataObjectTest\Team::class => 'Team',
1658
            DataObjectTest\Fixture::class => 'Fixture',
1659
        );
1660
1661
        foreach ($assertions as $class => $expectedSingularName) {
1662
            $this->assertEquals(
1663
                $expectedSingularName,
1664
                singleton($class)->singular_name(),
1665
                "Assert that the singular_name for '$class' is correct."
1666
            );
1667
        }
1668
    }
1669
1670
    /**
1671
     * Tests that plural_name() generates sensible defaults.
1672
     */
1673
    public function testPluralName()
1674
    {
1675
        $assertions = array(
1676
            DataObjectTest\Player::class => 'Players',
1677
            DataObjectTest\Team::class => 'Teams',
1678
            DataObjectTest\Fixture::class => 'Fixtures',
1679
            DataObjectTest\Play::class => 'Plays',
1680
            DataObjectTest\Bogey::class => 'Bogeys',
1681
            DataObjectTest\Ploy::class => 'Ploys',
1682
        );
1683
        i18n::set_locale('en_NZ');
1684
        foreach ($assertions as $class => $expectedPluralName) {
1685
            $this->assertEquals(
1686
                $expectedPluralName,
1687
                DataObject::singleton($class)->plural_name(),
1688
                "Assert that the plural_name for '$class' is correct."
1689
            );
1690
            $this->assertEquals(
1691
                $expectedPluralName,
1692
                DataObject::singleton($class)->i18n_plural_name(),
1693
                "Assert that the i18n_plural_name for '$class' is correct."
1694
            );
1695
        }
1696
    }
1697
1698
    public function testHasDatabaseField()
1699
    {
1700
        $team = singleton(DataObjectTest\Team::class);
1701
        $subteam = singleton(DataObjectTest\SubTeam::class);
1702
1703
        $this->assertTrue(
1704
            $team->hasDatabaseField('Title'),
1705
            "hasOwnDatabaseField() works with \$db fields"
1706
        );
1707
        $this->assertTrue(
1708
            $team->hasDatabaseField('CaptainID'),
1709
            "hasOwnDatabaseField() works with \$has_one fields"
1710
        );
1711
        $this->assertFalse(
1712
            $team->hasDatabaseField('NonExistentField'),
1713
            "hasOwnDatabaseField() doesn't detect non-existend fields"
1714
        );
1715
        $this->assertTrue(
1716
            $team->hasDatabaseField('ExtendedDatabaseField'),
1717
            "hasOwnDatabaseField() works with extended fields"
1718
        );
1719
        $this->assertFalse(
1720
            $team->hasDatabaseField('SubclassDatabaseField'),
1721
            "hasOwnDatabaseField() doesn't pick up fields in subclasses on parent class"
1722
        );
1723
1724
        $this->assertTrue(
1725
            $subteam->hasDatabaseField('SubclassDatabaseField'),
1726
            "hasOwnDatabaseField() picks up fields in subclasses"
1727
        );
1728
    }
1729
1730
    public function testFieldTypes()
1731
    {
1732
        $obj = new DataObjectTest\Fixture();
1733
        $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...
1734
        $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...
1735
        $obj->write();
1736
        $obj->flushCache();
1737
1738
        $obj = DataObject::get_by_id(DataObjectTest\Fixture::class, $obj->ID);
1739
        $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...
1740
        $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...
1741
    }
1742
1743
    public function testTwoSubclassesWithTheSameFieldNameWork()
1744
    {
1745
        // Create two objects of different subclasses, setting the values of fields that are
1746
        // defined separately in each subclass
1747
        $obj1 = new DataObjectTest\SubTeam();
1748
        $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...
1749
        $obj2 = new DataObjectTest\OtherSubclassWithSameField();
1750
        $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...
1751
1752
        // Write them to the database
1753
        $obj1->write();
1754
        $obj2->write();
1755
1756
        // Check that the values of those fields are properly read from the database
1757
        $values = DataObject::get(
1758
            DataObjectTest\Team::class,
1759
            "\"DataObjectTest_Team\".\"ID\" IN
1760
			($obj1->ID, $obj2->ID)"
1761
        )->column("SubclassDatabaseField");
1762
        $this->assertEquals(array_intersect($values, array('obj1', 'obj2')), $values);
1763
    }
1764
1765
    public function testClassNameSetForNewObjects()
1766
    {
1767
        $d = new DataObjectTest\Player();
1768
        $this->assertEquals(DataObjectTest\Player::class, $d->ClassName);
1769
    }
1770
1771
    public function testHasValue()
1772
    {
1773
        $team = new DataObjectTest\Team();
1774
        $this->assertFalse($team->hasValue('Title', null, false));
1775
        $this->assertFalse($team->hasValue('DatabaseField', null, false));
1776
1777
        $team->Title = 'hasValue';
1778
        $this->assertTrue($team->hasValue('Title', null, false));
1779
        $this->assertFalse($team->hasValue('DatabaseField', null, false));
1780
1781
        $team->Title = '<p></p>';
1782
        $this->assertTrue(
1783
            $team->hasValue('Title', null, false),
1784
            'Test that an empty paragraph is a value for non-HTML fields.'
1785
        );
1786
1787
        $team->DatabaseField = 'hasValue';
1788
        $this->assertTrue($team->hasValue('Title', null, false));
1789
        $this->assertTrue($team->hasValue('DatabaseField', null, false));
1790
    }
1791
1792
    public function testHasMany()
1793
    {
1794
        $company = new DataObjectTest\Company();
1795
1796
        $this->assertEquals(
1797
            array(
1798
                'CurrentStaff' => DataObjectTest\Staff::class,
1799
                'PreviousStaff' => DataObjectTest\Staff::class
1800
            ),
1801
            $company->hasMany(),
1802
            'has_many strips field name data by default.'
1803
        );
1804
1805
        $this->assertEquals(
1806
            DataObjectTest\Staff::class,
1807
            DataObject::getSchema()->hasManyComponent(DataObjectTest\Company::class, 'CurrentStaff'),
1808
            'has_many strips field name data by default on single relationships.'
1809
        );
1810
1811
        $this->assertEquals(
1812
            array(
1813
                'CurrentStaff' => DataObjectTest\Staff::class . '.CurrentCompany',
1814
                'PreviousStaff' => DataObjectTest\Staff::class . '.PreviousCompany'
1815
            ),
1816
            $company->hasMany(false),
1817
            'has_many returns field name data when $classOnly is false.'
1818
        );
1819
1820
        $this->assertEquals(
1821
            DataObjectTest\Staff::class . '.CurrentCompany',
1822
            DataObject::getSchema()->hasManyComponent(DataObjectTest\Company::class, 'CurrentStaff', false),
1823
            'has_many returns field name data on single records when $classOnly is false.'
1824
        );
1825
    }
1826
1827
    public function testGetRemoteJoinField()
1828
    {
1829
        $schema = DataObject::getSchema();
1830
1831
        // Company schema
1832
        $staffJoinField = $schema->getRemoteJoinField(
1833
            DataObjectTest\Company::class,
1834
            'CurrentStaff',
1835
            'has_many',
1836
            $polymorphic
1837
        );
1838
        $this->assertEquals('CurrentCompanyID', $staffJoinField);
1839
        $this->assertFalse($polymorphic, 'DataObjectTest_Company->CurrentStaff is not polymorphic');
1840
        $previousStaffJoinField = $schema->getRemoteJoinField(
1841
            DataObjectTest\Company::class,
1842
            'PreviousStaff',
1843
            'has_many',
1844
            $polymorphic
1845
        );
1846
        $this->assertEquals('PreviousCompanyID', $previousStaffJoinField);
1847
        $this->assertFalse($polymorphic, 'DataObjectTest_Company->PreviousStaff is not polymorphic');
1848
1849
        // CEO Schema
1850
        $this->assertEquals(
1851
            'CEOID',
1852
            $schema->getRemoteJoinField(
1853
                DataObjectTest\CEO::class,
1854
                'Company',
1855
                'belongs_to',
1856
                $polymorphic
1857
            )
1858
        );
1859
        $this->assertFalse($polymorphic, 'DataObjectTest_CEO->Company is not polymorphic');
1860
        $this->assertEquals(
1861
            'PreviousCEOID',
1862
            $schema->getRemoteJoinField(
1863
                DataObjectTest\CEO::class,
1864
                'PreviousCompany',
1865
                'belongs_to',
1866
                $polymorphic
1867
            )
1868
        );
1869
        $this->assertFalse($polymorphic, 'DataObjectTest_CEO->PreviousCompany is not polymorphic');
1870
1871
        // Team schema
1872
        $this->assertEquals(
1873
            'Favourite',
1874
            $schema->getRemoteJoinField(
1875
                DataObjectTest\Team::class,
1876
                'Fans',
1877
                'has_many',
1878
                $polymorphic
1879
            )
1880
        );
1881
        $this->assertTrue($polymorphic, 'DataObjectTest_Team->Fans is polymorphic');
1882
        $this->assertEquals(
1883
            'TeamID',
1884
            $schema->getRemoteJoinField(
1885
                DataObjectTest\Team::class,
1886
                'Comments',
1887
                'has_many',
1888
                $polymorphic
1889
            )
1890
        );
1891
        $this->assertFalse($polymorphic, 'DataObjectTest_Team->Comments is not polymorphic');
1892
    }
1893
1894
    public function testBelongsTo()
1895
    {
1896
        $company = new DataObjectTest\Company();
1897
        $ceo = new DataObjectTest\CEO();
1898
1899
        $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...
1900
        $company->write();
1901
        $ceo->write();
1902
1903
        // Test belongs_to assignment
1904
        $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...
1905
        $company->write();
1906
1907
        $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

1907
        $this->assertEquals($company->ID, $ceo->/** @scrutinizer ignore-call */ Company()->ID, 'belongs_to returns the right results.');
Loading history...
1908
1909
        // Test belongs_to can be infered via getNonReciprocalComponent
1910
        // Note: Will be returned as has_many since the belongs_to is ignored.
1911
        $this->assertListEquals(
1912
            [['Name' => 'New Company']],
1913
            $ceo->inferReciprocalComponent(DataObjectTest\Company::class, 'CEO')
0 ignored issues
show
Bug introduced by
$ceo->inferReciprocalCom...\Company::class, 'CEO') of type SilverStripe\ORM\DataObject is incompatible with the type SilverStripe\ORM\SS_List expected by parameter $list of SilverStripe\Dev\SapphireTest::assertListEquals(). ( Ignorable by Annotation )

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

1913
            /** @scrutinizer ignore-type */ $ceo->inferReciprocalComponent(DataObjectTest\Company::class, 'CEO')
Loading history...
1914
        );
1915
1916
        // Test has_one to a belongs_to can be infered via getNonReciprocalComponent
1917
        $this->assertEquals(
1918
            $ceo->ID,
1919
            $company->inferReciprocalComponent(DataObjectTest\CEO::class, 'Company')->ID
1920
        );
1921
1922
        // Test automatic creation of class where no assigment exists
1923
        $ceo = new DataObjectTest\CEO();
1924
        $ceo->write();
1925
1926
        $this->assertTrue(
1927
            $ceo->Company() instanceof DataObjectTest\Company,
1928
            'DataObjects across belongs_to relations are automatically created.'
1929
        );
1930
        $this->assertEquals($ceo->ID, $ceo->Company()->CEOID, 'Remote IDs are automatically set.');
1931
1932
        // Write object with components
1933
        $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...
1934
        $ceo->write(false, false, false, true);
1935
        $this->assertTrue($ceo->Company()->isInDB(), 'write() writes belongs_to components to the database.');
1936
1937
        $newCEO = DataObject::get_by_id(DataObjectTest\CEO::class, $ceo->ID);
1938
        $this->assertEquals(
1939
            $ceo->Company()->ID,
1940
            $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

1940
            $newCEO->/** @scrutinizer ignore-call */ 
1941
                     Company()->ID,
Loading history...
1941
            'belongs_to can be retrieved from the database.'
1942
        );
1943
    }
1944
1945
    public function testBelongsToPolymorphic()
1946
    {
1947
        $company = new DataObjectTest\Company();
1948
        $ceo = new DataObjectTest\CEO();
1949
1950
        $company->write();
1951
        $ceo->write();
1952
1953
        // Test belongs_to assignment
1954
        $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...
1955
        $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...
1956
        $company->write();
1957
1958
        $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

1958
        $this->assertEquals($company->ID, $ceo->/** @scrutinizer ignore-call */ CompanyOwned()->ID, 'belongs_to returns the right results.');
Loading history...
1959
        $this->assertInstanceOf(
1960
            DataObjectTest\Company::class,
1961
            $ceo->CompanyOwned(),
1962
            'belongs_to returns the right results.'
1963
        );
1964
1965
        // Test automatic creation of class where no assigment exists
1966
        $ceo = new DataObjectTest\CEO();
1967
        $ceo->write();
1968
1969
        $this->assertTrue(
1970
            $ceo->CompanyOwned() instanceof DataObjectTest\Company,
1971
            'DataObjects across polymorphic belongs_to relations are automatically created.'
1972
        );
1973
        $this->assertEquals($ceo->ID, $ceo->CompanyOwned()->OwnerID, 'Remote IDs are automatically set.');
1974
        $this->assertInstanceOf($ceo->CompanyOwned()->OwnerClass, $ceo, 'Remote class is automatically  set');
1975
1976
        // Write object with components
1977
        $ceo->write(false, false, false, true);
1978
        $this->assertTrue($ceo->CompanyOwned()->isInDB(), 'write() writes belongs_to components to the database.');
1979
1980
        $newCEO = DataObject::get_by_id(DataObjectTest\CEO::class, $ceo->ID);
1981
        $this->assertEquals(
1982
            $ceo->CompanyOwned()->ID,
1983
            $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

1983
            $newCEO->/** @scrutinizer ignore-call */ 
1984
                     CompanyOwned()->ID,
Loading history...
1984
            'polymorphic belongs_to can be retrieved from the database.'
1985
        );
1986
    }
1987
1988
    /**
1989
     * @expectedException LogicException
1990
     */
1991
    public function testInvalidate()
1992
    {
1993
        $do = new DataObjectTest\Fixture();
1994
        $do->write();
1995
1996
        $do->delete();
1997
1998
        $do->delete(); // Prohibit invalid object manipulation
1999
        $do->write();
2000
        $do->duplicate();
2001
    }
2002
2003
    public function testToMap()
2004
    {
2005
        $obj = $this->objFromFixture(DataObjectTest\SubTeam::class, 'subteam1');
2006
2007
        $map = $obj->toMap();
2008
2009
        $this->assertArrayHasKey('ID', $map, 'Contains base fields');
2010
        $this->assertArrayHasKey('Title', $map, 'Contains fields from parent class');
2011
        $this->assertArrayHasKey('SubclassDatabaseField', $map, 'Contains fields from concrete class');
2012
2013
        $this->assertEquals(
2014
            $obj->ID,
2015
            $map['ID'],
2016
            'Contains values from base fields'
2017
        );
2018
        $this->assertEquals(
2019
            $obj->Title,
2020
            $map['Title'],
2021
            'Contains values from parent class fields'
2022
        );
2023
        $this->assertEquals(
2024
            $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...
2025
            $map['SubclassDatabaseField'],
2026
            'Contains values from concrete class fields'
2027
        );
2028
2029
        $newObj = new DataObjectTest\SubTeam();
0 ignored issues
show
Unused Code introduced by
The assignment to $newObj is dead and can be removed.
Loading history...
2030
        $this->assertArrayHasKey('Title', $map, 'Contains null fields');
2031
    }
2032
2033
    public function testIsEmpty()
2034
    {
2035
        $objEmpty = new DataObjectTest\Team();
2036
        $this->assertTrue($objEmpty->isEmpty(), 'New instance without populated defaults is empty');
2037
2038
        $objEmpty->Title = '0'; //
2039
        $this->assertFalse($objEmpty->isEmpty(), 'Zero value in attribute considered non-empty');
2040
    }
2041
2042
    public function testRelField()
2043
    {
2044
        $captain1 = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
2045
        // Test traversal of a single has_one
2046
        $this->assertEquals("Team 1", $captain1->relField('FavouriteTeam.Title'));
2047
        // Test direct field access
2048
        $this->assertEquals("Captain", $captain1->relField('FirstName'));
2049
2050
        // Test empty link
2051
        $captain2 = $this->objFromFixture(DataObjectTest\Player::class, 'captain2');
2052
        $this->assertEmpty($captain2->relField('FavouriteTeam.Title'));
2053
        $this->assertNull($captain2->relField('FavouriteTeam.ReturnsNull'));
2054
        $this->assertNull($captain2->relField('FavouriteTeam.ReturnsNull.Title'));
2055
2056
        $player = $this->objFromFixture(DataObjectTest\Player::class, 'player2');
2057
        // Test that we can traverse more than once, and that arbitrary methods are okay
2058
        $this->assertEquals("Team 1", $player->relField('Teams.First.Title'));
2059
2060
        $newPlayer = new DataObjectTest\Player();
2061
        $this->assertNull($newPlayer->relField('Teams.First.Title'));
2062
2063
        // Test that relField works on db field manipulations
2064
        $comment = $this->objFromFixture(DataObjectTest\TeamComment::class, 'comment3');
2065
        $this->assertEquals("PHIL IS A UNIQUE GUY, AND COMMENTS ON TEAM2", $comment->relField('Comment.UpperCase'));
2066
2067
        // relField throws exception on invalid properties
2068
        $this->expectException(LogicException::class);
2069
        $this->expectExceptionMessage("Not is not a relation/field on " . DataObjectTest\TeamComment::class);
2070
        $comment->relField('Not.A.Field');
2071
    }
2072
2073
    public function testRelObject()
2074
    {
2075
        $captain1 = $this->objFromFixture(DataObjectTest\Player::class, 'captain1');
2076
2077
        // Test traversal of a single has_one
2078
        $this->assertInstanceOf(DBVarchar::class, $captain1->relObject('FavouriteTeam.Title'));
2079
        $this->assertEquals("Team 1", $captain1->relObject('FavouriteTeam.Title')->getValue());
0 ignored issues
show
Bug introduced by
The method getValue() 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

2079
        $this->assertEquals("Team 1", $captain1->relObject('FavouriteTeam.Title')->/** @scrutinizer ignore-call */ getValue());
Loading history...
2080
2081
        // Test empty link
2082
        $captain2 = $this->objFromFixture(DataObjectTest\Player::class, 'captain2');
2083
        $this->assertEmpty($captain2->relObject('FavouriteTeam.Title')->getValue());
2084
        $this->assertNull($captain2->relObject('FavouriteTeam.ReturnsNull.Title'));
2085
2086
        // Test direct field access
2087
        $this->assertInstanceOf(DBBoolean::class, $captain1->relObject('IsRetired'));
2088
        $this->assertEquals(1, $captain1->relObject('IsRetired')->getValue());
2089
2090
        $player = $this->objFromFixture(DataObjectTest\Player::class, 'player2');
2091
        // Test that we can traverse more than once, and that arbitrary methods are okay
2092
        $this->assertInstanceOf(DBVarchar::class, $player->relObject('Teams.First.Title'));
2093
        $this->assertEquals("Team 1", $player->relObject('Teams.First.Title')->getValue());
2094
2095
        // relObject throws exception on invalid properties
2096
        $this->expectException(LogicException::class);
2097
        $this->expectExceptionMessage("Not is not a relation/field on " . DataObjectTest\Player::class);
2098
        $player->relObject('Not.A.Field');
2099
    }
2100
2101
    public function testLateStaticBindingStyle()
2102
    {
2103
        // Confirm that DataObjectTest_Player::get() operates as excepted
2104
        $this->assertEquals(4, DataObjectTest\Player::get()->count());
2105
        $this->assertInstanceOf(DataObjectTest\Player::class, DataObjectTest\Player::get()->first());
2106
2107
        // You can't pass arguments to LSB syntax - use the DataList methods instead.
2108
        $this->expectException(InvalidArgumentException::class);
2109
2110
        DataObjectTest\Player::get(null, "\"ID\" = 1");
2111
    }
2112
2113
    /**
2114
     * @expectedException \InvalidArgumentException
2115
     */
2116
    public function testBrokenLateStaticBindingStyle()
2117
    {
2118
        // If you call DataObject::get() you have to pass a first argument
2119
        DataObject::get();
2120
    }
2121
2122
    public function testBigIntField()
2123
    {
2124
        $staff = new DataObjectTest\Staff();
2125
        $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...
2126
        $staff->write();
2127
        $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...
2128
    }
2129
2130
    public function testGetOneMissingValueReturnsNull()
2131
    {
2132
2133
        // Test that missing values return null
2134
        $this->assertEquals(null, DataObject::get_one(
2135
            DataObjectTest\TeamComment::class,
2136
            ['"DataObjectTest_TeamComment"."Name"' => 'does not exists']
2137
        ));
2138
    }
2139
}
2140