-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathDatabaseModelCustomCastingTest.php
More file actions
650 lines (528 loc) · 20.7 KB
/
DatabaseModelCustomCastingTest.php
File metadata and controls
650 lines (528 loc) · 20.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
<?php
declare(strict_types=1);
/**
* This file is part of Hyperf.
*
* @link https://www.hyperf.io
* @document https://hyperf.wiki
* @contact group@hyperf.io
* @license https://github.com/hyperf/hyperf/blob/master/LICENSE
*/
namespace HyperfTest\Database;
use Hyperf\Collection\Arr;
use Hyperf\Collection\Collection;
use Hyperf\Contract\Arrayable;
use Hyperf\Contract\Castable;
use Hyperf\Contract\CastsAttributes;
use Hyperf\Contract\CastsInboundAttributes;
use Hyperf\Database\Exception\InvalidCastException;
use Hyperf\Database\Model\Casts\ArrayObject;
use Hyperf\Database\Model\Casts\AsArrayObject;
use Hyperf\Database\Model\Casts\AsCollection;
use Hyperf\Database\Model\CastsValue;
use Hyperf\Database\Model\Model;
use HyperfTest\Database\Stubs\ContainerStub;
use JsonSerializable;
use Mockery;
use PHPUnit\Framework\Attributes\CoversNothing;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use stdClass;
/**
* @internal
* @coversNothing
*/
#[CoversNothing]
class DatabaseModelCustomCastingTest extends TestCase
{
protected function setUp(): void
{
ContainerStub::unsetContainer();
}
protected function tearDown(): void
{
Mockery::close();
UserInfoCaster::$setCount = 0;
UserInfoCaster::$getCount = 0;
}
public function testBasicCustomCasting()
{
$model = new TestModelWithCustomCast();
$model->uppercase = 'taylor';
$this->assertSame('TAYLOR', $model->uppercase);
$this->assertSame('TAYLOR', $model->getAttributes()['uppercase']);
$this->assertSame('TAYLOR', $model->toArray()['uppercase']);
$unserializedModel = unserialize(serialize($model));
$this->assertSame('TAYLOR', $unserializedModel->uppercase);
$this->assertSame('TAYLOR', $unserializedModel->getAttributes()['uppercase']);
$this->assertSame('TAYLOR', $unserializedModel->toArray()['uppercase']);
$model->syncOriginal();
$model->uppercase = 'dries';
$this->assertEquals('TAYLOR', $model->getOriginal('uppercase'));
$model = new TestModelWithCustomCast();
$model->uppercase = 'taylor';
$model->syncOriginal();
$model->uppercase = 'dries';
$model->getOriginal();
$this->assertEquals('DRIES', $model->uppercase);
$model = new TestModelWithCustomCast();
$model->address = $address = new Address('110 Kingsbrook St.', 'My Childhood House');
$address->lineOne = '117 Spencer St.';
$this->assertSame('117 Spencer St.', $model->syncAttributes()->getAttributes()['address_line_one']);
$model = new TestModelWithCustomCast();
$model->setRawAttributes([
'address_line_one' => '110 Kingsbrook St.',
'address_line_two' => 'My Childhood House',
]);
$this->assertSame('110 Kingsbrook St.', $model->address->lineOne);
$this->assertSame('My Childhood House', $model->address->lineTwo);
$this->assertSame('110 Kingsbrook St.', $model->toArray()['address_line_one']);
$this->assertSame('My Childhood House', $model->toArray()['address_line_two']);
$model->address->lineOne = '117 Spencer St.';
$this->assertFalse(isset($model->toArray()['address']));
$this->assertSame('117 Spencer St.', $model->toArray()['address_line_one']);
$this->assertSame('My Childhood House', $model->toArray()['address_line_two']);
$this->assertSame('117 Spencer St.', json_decode($model->toJson(), true)['address_line_one']);
$this->assertSame('My Childhood House', json_decode($model->toJson(), true)['address_line_two']);
$model->address = null;
$this->assertNull($model->toArray()['address_line_one']);
$this->assertNull($model->toArray()['address_line_two']);
$model->options = ['foo' => 'bar'];
$this->assertEquals(['foo' => 'bar'], $model->options);
$this->assertEquals(['foo' => 'bar'], $model->options);
$model->options = ['foo' => 'bar'];
$model->options = ['foo' => 'bar'];
$this->assertEquals(['foo' => 'bar'], $model->options);
$this->assertEquals(['foo' => 'bar'], $model->options);
$this->assertEquals(json_encode(['foo' => 'bar']), $model->getAttributes()['options']);
$model = new TestModelWithCustomCast(['options' => []]);
$model->syncOriginal();
$model->options = ['foo' => 'bar'];
$this->assertTrue($model->isDirty('options'));
}
public function testOneWayCasting()
{
// CastsInboundAttributes is used for casting that is unidirectional... only use case I can think of is one-way hashing...
$model = new TestModelWithCustomCast();
$model->password = 'secret';
$this->assertEquals(hash('sha256', 'secret'), $model->password);
$this->assertEquals(hash('sha256', 'secret'), $model->getAttributes()['password']);
$this->assertEquals(hash('sha256', 'secret'), $model->getAttributes()['password']);
$this->assertEquals(hash('sha256', 'secret'), $model->password);
$model->password = 'secret2';
$this->assertEquals(hash('sha256', 'secret2'), $model->password);
$this->assertEquals(hash('sha256', 'secret2'), $model->getAttributes()['password']);
$this->assertEquals(hash('sha256', 'secret2'), $model->getAttributes()['password']);
$this->assertEquals(hash('sha256', 'secret2'), $model->password);
}
public function testSettingRawAttributesClearsTheCastCache()
{
$model = new TestModelWithCustomCast();
$model->setRawAttributes([
'address_line_one' => '110 Kingsbrook St.',
'address_line_two' => 'My Childhood House',
]);
$this->assertSame('110 Kingsbrook St.', $model->address->lineOne);
$model->setRawAttributes([
'address_line_one' => '117 Spencer St.',
'address_line_two' => 'My Childhood House',
]);
$this->assertSame('117 Spencer St.', $model->address->lineOne);
}
public function testWithCastableInterface()
{
$model = new TestModelWithCustomCast();
$model->setRawAttributes([
'value_object_with_caster' => serialize(new ValueObject('hello')),
]);
$this->assertInstanceOf(ValueObject::class, $model->value_object_with_caster);
$model->setRawAttributes([
'value_object_caster_with_argument' => null,
]);
$this->assertEquals('argument', $model->value_object_caster_with_argument);
$model->setRawAttributes([
'value_object_caster_with_caster_instance' => serialize(new ValueObject('hello')),
]);
$this->assertInstanceOf(ValueObject::class, $model->value_object_caster_with_caster_instance);
}
public function testGetAttribute()
{
$model = new TestModelWithCustomCast();
$model->mergeCasts([
'mockery' => MockeryAttribute::class,
]);
$mockery = Mockery::mock(CastsAttributes::class);
$mockery->shouldReceive('get')->withAnyArgs()->andReturn(function ($_, $key, $value, $attributes) {
$obj = new stdClass();
$obj->value = $attributes[$key . '_origin'] - 1;
return $obj;
});
$mockery->shouldReceive('set')->withAnyArgs()->once()->andReturnUsing(function ($_, $key, $value, $attributes) {
return [
$key . '_origin' => $value->value + 1,
];
});
MockeryAttribute::$attribute = $mockery;
$std = new stdClass();
$std->value = 1;
$model->mockery = $std;
$this->assertSame(1, $model->mockery->value);
}
public function testResolveCasterClass()
{
$model = new TestModelWithCustomCast();
$ref = new ReflectionClass($model);
$method = $ref->getMethod('resolveCasterClass');
CastUsing::$castsAttributes = UppercaseCaster::class;
$this->assertNotSame($method->invokeArgs($model, ['cast_using']), $method->invokeArgs($model, ['cast_using']));
CastUsing::$castsAttributes = new UppercaseCaster();
$this->assertSame($method->invokeArgs($model, ['cast_using']), $method->invokeArgs($model, ['cast_using']));
}
public function testIsSynchronized()
{
$model = new TestModelWithCustomCast();
$model->user = $user = new UserInfo($model, ['name' => 'Hyperf', 'gender' => 1]);
$model->syncOriginal();
$attributes = $model->getAttributes();
$this->assertSame(['name' => 'Hyperf', 'gender' => 1], Arr::only($attributes, ['name', 'gender']));
$user->name = 'Nano';
$attributes = $model->getAttributes();
$this->assertSame(['name' => 'Nano', 'gender' => 1], Arr::only($attributes, ['name', 'gender']));
$this->assertSame(['name' => 'Nano'], $model->getDirty());
$this->assertSame(2, UserInfoCaster::$setCount);
$this->assertSame(0, UserInfoCaster::$getCount);
}
public function testCastsValueSupportNull()
{
$model = new TestModelWithCustomCast();
$model->user = $user = new UserInfo($model, ['name' => 'Hyperf', 'gender' => 1]);
$attributes = $model->getAttributes();
$this->assertSame(['name' => 'Hyperf', 'gender' => 1, 'role_id' => 0], $attributes);
$this->assertSame(0, $user->role_id);
$user->role_id = 1;
$this->assertSame(['name' => 'Hyperf', 'gender' => 1, 'role_id' => 1], $model->getAttributes());
unset($user->role_id);
$this->assertSame(['name' => 'Hyperf', 'gender' => 1, 'role_id' => null], $model->getAttributes());
$this->assertSame(null, $user->role_id);
unset($user->not_found);
$this->assertSame(['name' => 'Hyperf', 'gender' => 1, 'role_id' => null], $model->getAttributes());
}
public function testThrowExceptionWhenCastClassNotExist()
{
$this->expectException(InvalidCastException::class);
$this->expectExceptionMessage('Call to undefined cast [HyperfTest\Database\InvalidCaster] on column [invalid_caster] in model [HyperfTest\Database\TestModelWithCustomCast].');
$model = new TestModelWithCustomCast();
$model->invalid_caster = 'foo';
}
public function testAsArrayObjectCasting()
{
$model = new TestModelWithArrayObjectCast();
// Test setting array data
$data = ['name' => 'Hyperf', 'version' => '3.1', 'features' => ['fast', 'modern']];
$model->config = $data;
$this->assertInstanceOf(ArrayObject::class, $model->config);
$this->assertEquals($data, $model->config->toArray());
$this->assertEquals(json_encode($data), $model->getAttributes()['config']);
// Test ArrayObject methods
$this->assertEquals('Hyperf', $model->config['name']);
$this->assertEquals('3.1', $model->config['version']);
$this->assertCount(3, $model->config);
// Test collect method
$collection = $model->config->collect();
$this->assertInstanceOf(Collection::class, $collection);
$this->assertEquals($data, $collection->toArray());
// Test modification
$model->config['type'] = 'framework';
$this->assertEquals('framework', $model->config['type']);
$this->assertCount(4, $model->config);
// Test JSON serialization
$this->assertEquals($model->config->toArray(), $model->config->jsonSerialize());
// Test with null value
$model->config = null;
$this->assertNull($model->config);
// Test with empty array
$model->config = [];
$this->assertInstanceOf(ArrayObject::class, $model->config);
$this->assertCount(0, $model->config);
$this->assertEquals([], $model->config->toArray());
}
public function testAsArrayObjectCastingFromDatabase()
{
$model = new TestModelWithArrayObjectCast();
// Simulate loading from database
$jsonData = json_encode(['database' => 'mysql', 'driver' => 'swoole']);
$model->setRawAttributes(['config' => $jsonData]);
$this->assertInstanceOf(ArrayObject::class, $model->config);
$this->assertEquals('mysql', $model->config['database']);
$this->assertEquals('swoole', $model->config['driver']);
$this->assertEquals(['database' => 'mysql', 'driver' => 'swoole'], $model->config->toArray());
}
public function testAsArrayObjectCastingInvalidJson()
{
$model = new TestModelWithArrayObjectCast();
$this->expectExceptionMessage('Syntax error');
// Test with invalid JSON - should return null
$model->setRawAttributes(['config' => 'invalid json']);
$this->assertNull($model->config);
// Test with non-array JSON - should return null
$model->setRawAttributes(['config' => json_encode('string value')]);
$this->assertNull($model->config);
$model->setRawAttributes(['config' => json_encode(123)]);
$this->assertNull($model->config);
}
public function testArrayObjectCollectMethod()
{
$data = ['a' => 1, 'b' => 2, 'c' => 3];
$arrayObject = new ArrayObject($data);
$collection = $arrayObject->collect();
$this->assertInstanceOf(Collection::class, $collection);
$this->assertEquals($data, $collection->toArray());
// Test collection methods work
$filtered = $arrayObject->collect()->filter(fn ($value) => $value > 1);
$this->assertEquals(['b' => 2, 'c' => 3], $filtered->toArray());
}
public function testArrayObjectInterfaces()
{
$data = ['key' => 'value', 'number' => 42];
$arrayObject = new ArrayObject($data);
// Test Arrayable interface
$this->assertInstanceOf(Arrayable::class, $arrayObject);
$this->assertEquals($data, $arrayObject->toArray());
// Test JsonSerializable interface
$this->assertInstanceOf(JsonSerializable::class, $arrayObject);
$this->assertEquals($data, $arrayObject->jsonSerialize());
// Test array access
$this->assertEquals('value', $arrayObject['key']);
$this->assertEquals(42, $arrayObject['number']);
// Test modification
$arrayObject['new_key'] = 'new_value';
$this->assertEquals('new_value', $arrayObject['new_key']);
}
public function testArrayObjectSerialization()
{
$model = new TestModelWithArrayObjectCast();
$data = ['serialized' => true, 'data' => [1, 2, 3]];
$model->config = $data;
// Test model serialization/unserialization
$serialized = serialize($model);
$unserialized = unserialize($serialized);
$this->assertInstanceOf(ArrayObject::class, $unserialized->config);
$this->assertEquals($data, $unserialized->config->toArray());
$this->assertEquals(json_encode($data), $unserialized->getAttributes()['config']);
}
public function testCastsAsCollection()
{
$m = new TestModelWithCustomCast();
$m->fill([
'as_collection' => [['id' => 1, 'name' => 'hyperf'], ['id' => 2, 'name' => 'swoole']],
'as_collection2' => [['id' => 3, 'name' => 'hyperf'], ['id' => 4, 'name' => 'swoole']],
]);
/** @var Collection $collection */
$collection = $m->as_collection;
$this->assertSame(1, $collection->first()['id']);
$this->assertSame(2, $collection->last()['id']);
/** @var Collection $collection */
$collection = $m->as_collection2;
$this->assertSame(3, $collection->first()->id);
$this->assertSame(4, $collection->last()->id);
}
}
class TestModelWithCustomCast extends Model
{
/**
* The attributes that aren't mass assignable.
*/
protected array $guarded = [];
/**
* The attributes that should be cast to native types.
*/
protected array $casts = [
'address' => AddressCaster::class,
'user' => UserInfoCaster::class,
'password' => HashCaster::class,
'other_password' => HashCaster::class . ':md5',
'uppercase' => UppercaseCaster::class,
'options' => JsonCaster::class,
'value_object_with_caster' => ValueObject::class,
'value_object_caster_with_argument' => ValueObject::class . ':argument',
'value_object_caster_with_caster_instance' => ValueObjectWithCasterInstance::class,
'cast_using' => CastUsing::class,
'invalid_caster' => InvalidCaster::class,
'as_collection' => AsCollection::class,
'as_collection2' => AsCollection::class,
];
public function getCasts(): array
{
$casts = parent::getCasts();
$casts['as_collection2'] = AsCollection::using(Collection::class, [TestModelValue::class, 'from']);
return $casts;
}
}
class TestModelValue
{
public function __construct(public int $id, public string $name)
{
}
public static function from(array $item)
{
return new TestModelValue($item['id'], $item['name']);
}
}
class TestModelWithArrayObjectCast extends Model
{
/**
* The attributes that aren't mass assignable.
*/
protected array $guarded = [];
/**
* The attributes that should be cast to native types.
*/
protected array $casts = [
'config' => AsArrayObject::class,
'settings' => AsArrayObject::class,
'metadata' => AsArrayObject::class,
];
}
class CastUsing implements Castable
{
/**
* @var CastsAttributes
*/
public static $castsAttributes;
public static function castUsing()
{
return self::$castsAttributes;
}
}
class HashCaster implements CastsInboundAttributes
{
public function __construct($algorithm = 'sha256')
{
$this->algorithm = $algorithm;
}
public function set($model, $key, $value, $attributes)
{
return [$key => hash($this->algorithm, $value)];
}
}
class UppercaseCaster implements CastsAttributes
{
public function get($model, $key, $value, $attributes)
{
return strtoupper($value);
}
public function set($model, $key, $value, $attributes)
{
return [$key => strtoupper($value)];
}
}
class AddressCaster implements CastsAttributes
{
public function get($model, $key, $value, $attributes)
{
return new Address($attributes['address_line_one'], $attributes['address_line_two']);
}
public function set($model, $key, $value, $attributes)
{
return ['address_line_one' => $value->lineOne, 'address_line_two' => $value->lineTwo];
}
}
class UserInfoCaster implements CastsAttributes
{
public static $setCount = 0;
public static $getCount = 0;
public function get($model, string $key, $value, array $attributes)
{
++self::$getCount;
return new UserInfo($model, Arr::only($attributes, ['name', 'gender']));
}
public function set($model, string $key, $value, array $attributes)
{
++self::$setCount;
return [
'name' => $value->name,
'gender' => $value->gender,
'role_id' => $value->role_id,
];
}
}
class JsonCaster implements CastsAttributes
{
public function get($model, $key, $value, $attributes)
{
return json_decode($value, true);
}
public function set($model, $key, $value, $attributes)
{
return json_encode($value);
}
}
class ValueObjectCaster implements CastsAttributes
{
private $argument;
public function __construct($argument = null)
{
$this->argument = $argument;
}
public function get($model, $key, $value, $attributes)
{
if ($this->argument) {
return $this->argument;
}
return unserialize($value);
}
public function set($model, $key, $value, $attributes)
{
return serialize($value);
}
}
class MockeryAttribute implements CastsAttributes
{
/**
* @var CastsAttributes
*/
public static $attribute;
public function get($model, string $key, $value, array $attributes)
{
return self::$attribute->get($model, $key, $value, $attributes);
}
public function set($model, string $key, $value, array $attributes)
{
return self::$attribute->set($model, $key, $value, $attributes);
}
}
class ValueObject implements Castable
{
public static function castUsing()
{
return ValueObjectCaster::class;
}
}
class ValueObjectWithCasterInstance extends ValueObject
{
public static function castUsing()
{
return new ValueObjectCaster();
}
}
class Address
{
public $lineOne;
public $lineTwo;
public function __construct($lineOne, $lineTwo)
{
$this->lineOne = $lineOne;
$this->lineTwo = $lineTwo;
}
}
/**
* @property string $name
* @property int $gender
* @property null|int $role_id
*/
class UserInfo extends CastsValue
{
protected array $items = [
'role_id' => 0,
];
}