DatabaseEloquentModelAttributeCastingTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. <?php
  2. namespace Illuminate\Tests\Integration\Database;
  3. use Illuminate\Database\Eloquent\Casts\Attribute;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Schema\Blueprint;
  6. use Illuminate\Support\Carbon;
  7. use Illuminate\Support\Facades\Date;
  8. use Illuminate\Support\Facades\Schema;
  9. use Illuminate\Support\Str;
  10. class DatabaseEloquentModelAttributeCastingTest extends DatabaseTestCase
  11. {
  12. protected function defineDatabaseMigrationsAfterDatabaseRefreshed()
  13. {
  14. Schema::create('test_eloquent_model_with_custom_casts', function (Blueprint $table) {
  15. $table->increments('id');
  16. $table->timestamps();
  17. });
  18. }
  19. public function testBasicCustomCasting()
  20. {
  21. $model = new TestEloquentModelWithAttributeCast;
  22. $model->uppercase = 'taylor';
  23. $this->assertSame('TAYLOR', $model->uppercase);
  24. $this->assertSame('TAYLOR', $model->getAttributes()['uppercase']);
  25. $this->assertSame('TAYLOR', $model->toArray()['uppercase']);
  26. $unserializedModel = unserialize(serialize($model));
  27. $this->assertSame('TAYLOR', $unserializedModel->uppercase);
  28. $this->assertSame('TAYLOR', $unserializedModel->getAttributes()['uppercase']);
  29. $this->assertSame('TAYLOR', $unserializedModel->toArray()['uppercase']);
  30. $model->syncOriginal();
  31. $model->uppercase = 'dries';
  32. $this->assertSame('TAYLOR', $model->getOriginal('uppercase'));
  33. $model = new TestEloquentModelWithAttributeCast;
  34. $model->uppercase = 'taylor';
  35. $model->syncOriginal();
  36. $model->uppercase = 'dries';
  37. $model->getOriginal();
  38. $this->assertSame('DRIES', $model->uppercase);
  39. $model = new TestEloquentModelWithAttributeCast;
  40. $model->address = $address = new AttributeCastAddress('110 Kingsbrook St.', 'My Childhood House');
  41. $address->lineOne = '117 Spencer St.';
  42. $this->assertSame('117 Spencer St.', $model->getAttributes()['address_line_one']);
  43. $model = new TestEloquentModelWithAttributeCast;
  44. $model->setRawAttributes([
  45. 'address_line_one' => '110 Kingsbrook St.',
  46. 'address_line_two' => 'My Childhood House',
  47. ]);
  48. $this->assertSame('110 Kingsbrook St.', $model->address->lineOne);
  49. $this->assertSame('My Childhood House', $model->address->lineTwo);
  50. $this->assertSame('110 Kingsbrook St.', $model->toArray()['address_line_one']);
  51. $this->assertSame('My Childhood House', $model->toArray()['address_line_two']);
  52. $model->address->lineOne = '117 Spencer St.';
  53. $this->assertFalse(isset($model->toArray()['address']));
  54. $this->assertSame('117 Spencer St.', $model->toArray()['address_line_one']);
  55. $this->assertSame('My Childhood House', $model->toArray()['address_line_two']);
  56. $this->assertSame('117 Spencer St.', json_decode($model->toJson(), true)['address_line_one']);
  57. $this->assertSame('My Childhood House', json_decode($model->toJson(), true)['address_line_two']);
  58. $model->address = null;
  59. $this->assertNull($model->toArray()['address_line_one']);
  60. $this->assertNull($model->toArray()['address_line_two']);
  61. $model->options = ['foo' => 'bar'];
  62. $this->assertEquals(['foo' => 'bar'], $model->options);
  63. $this->assertEquals(['foo' => 'bar'], $model->options);
  64. $model->options = ['foo' => 'bar'];
  65. $model->options = ['foo' => 'bar'];
  66. $this->assertEquals(['foo' => 'bar'], $model->options);
  67. $this->assertEquals(['foo' => 'bar'], $model->options);
  68. $this->assertSame(json_encode(['foo' => 'bar']), $model->getAttributes()['options']);
  69. $model = new TestEloquentModelWithAttributeCast(['options' => []]);
  70. $model->syncOriginal();
  71. $model->options = ['foo' => 'bar'];
  72. $this->assertTrue($model->isDirty('options'));
  73. $model = new TestEloquentModelWithAttributeCast;
  74. $model->birthday_at = now();
  75. $this->assertIsString($model->toArray()['birthday_at']);
  76. }
  77. public function testGetOriginalWithCastValueObjects()
  78. {
  79. $model = new TestEloquentModelWithAttributeCast([
  80. 'address' => new AttributeCastAddress('110 Kingsbrook St.', 'My Childhood House'),
  81. ]);
  82. $model->syncOriginal();
  83. $model->address = new AttributeCastAddress('117 Spencer St.', 'Another house.');
  84. $this->assertSame('117 Spencer St.', $model->address->lineOne);
  85. $this->assertSame('110 Kingsbrook St.', $model->getOriginal('address')->lineOne);
  86. $this->assertSame('117 Spencer St.', $model->address->lineOne);
  87. $model = new TestEloquentModelWithAttributeCast([
  88. 'address' => new AttributeCastAddress('110 Kingsbrook St.', 'My Childhood House'),
  89. ]);
  90. $model->syncOriginal();
  91. $model->address = new AttributeCastAddress('117 Spencer St.', 'Another house.');
  92. $this->assertSame('117 Spencer St.', $model->address->lineOne);
  93. $this->assertSame('110 Kingsbrook St.', $model->getOriginal()['address_line_one']);
  94. $this->assertSame('117 Spencer St.', $model->address->lineOne);
  95. $this->assertSame('110 Kingsbrook St.', $model->getOriginal()['address_line_one']);
  96. $model = new TestEloquentModelWithAttributeCast([
  97. 'address' => new AttributeCastAddress('110 Kingsbrook St.', 'My Childhood House'),
  98. ]);
  99. $model->syncOriginal();
  100. $model->address = null;
  101. $this->assertNull($model->address);
  102. $this->assertInstanceOf(AttributeCastAddress::class, $model->getOriginal('address'));
  103. $this->assertNull($model->address);
  104. }
  105. public function testOneWayCasting()
  106. {
  107. $model = new TestEloquentModelWithAttributeCast;
  108. $this->assertNull($model->password);
  109. $model->password = 'secret';
  110. $this->assertEquals(hash('sha256', 'secret'), $model->password);
  111. $this->assertEquals(hash('sha256', 'secret'), $model->getAttributes()['password']);
  112. $this->assertEquals(hash('sha256', 'secret'), $model->getAttributes()['password']);
  113. $this->assertEquals(hash('sha256', 'secret'), $model->password);
  114. $model->password = 'secret2';
  115. $this->assertEquals(hash('sha256', 'secret2'), $model->password);
  116. $this->assertEquals(hash('sha256', 'secret2'), $model->getAttributes()['password']);
  117. $this->assertEquals(hash('sha256', 'secret2'), $model->getAttributes()['password']);
  118. $this->assertEquals(hash('sha256', 'secret2'), $model->password);
  119. }
  120. public function testSettingRawAttributesClearsTheCastCache()
  121. {
  122. $model = new TestEloquentModelWithAttributeCast;
  123. $model->setRawAttributes([
  124. 'address_line_one' => '110 Kingsbrook St.',
  125. 'address_line_two' => 'My Childhood House',
  126. ]);
  127. $this->assertSame('110 Kingsbrook St.', $model->address->lineOne);
  128. $model->setRawAttributes([
  129. 'address_line_one' => '117 Spencer St.',
  130. 'address_line_two' => 'My Childhood House',
  131. ]);
  132. $this->assertSame('117 Spencer St.', $model->address->lineOne);
  133. }
  134. public function testCastsThatOnlyHaveGetterDoNotPeristAnythingToModelOnSave()
  135. {
  136. $model = new TestEloquentModelWithAttributeCast;
  137. $model->virtual;
  138. $model->getAttributes();
  139. $this->assertTrue(empty($model->getDirty()));
  140. }
  141. public function testCastsThatOnlyHaveGetterThatReturnsPrimitivesAreNotCached()
  142. {
  143. $model = new TestEloquentModelWithAttributeCast;
  144. $previous = null;
  145. foreach (range(0, 10) as $ignored) {
  146. $this->assertNotSame($previous, $previous = $model->virtualString);
  147. }
  148. }
  149. public function testCastsThatOnlyHaveGetterThatReturnsObjectAreCached()
  150. {
  151. $model = new TestEloquentModelWithAttributeCast;
  152. $previous = $model->virtualObject;
  153. foreach (range(0, 10) as $ignored) {
  154. $this->assertSame($previous, $previous = $model->virtualObject);
  155. }
  156. }
  157. public function testCastsThatOnlyHaveGetterThatReturnsDateTimeAreCached()
  158. {
  159. $model = new TestEloquentModelWithAttributeCast;
  160. $previous = $model->virtualDateTime;
  161. foreach (range(0, 10) as $ignored) {
  162. $this->assertSame($previous, $previous = $model->virtualDateTime);
  163. }
  164. }
  165. public function testCastsThatOnlyHaveGetterThatReturnsObjectAreNotCached()
  166. {
  167. $model = new TestEloquentModelWithAttributeCast;
  168. $previous = $model->virtualObjectWithoutCaching;
  169. foreach (range(0, 10) as $ignored) {
  170. $this->assertNotSame($previous, $previous = $model->virtualObjectWithoutCaching);
  171. }
  172. }
  173. public function testCastsThatOnlyHaveGetterThatReturnsDateTimeAreNotCached()
  174. {
  175. $model = new TestEloquentModelWithAttributeCast;
  176. $previous = $model->virtualDateTimeWithoutCaching;
  177. foreach (range(0, 10) as $ignored) {
  178. $this->assertNotSame($previous, $previous = $model->virtualDateTimeWithoutCaching);
  179. }
  180. }
  181. public function testCastsThatOnlyHaveGetterThatReturnsObjectAreNotCachedFluent()
  182. {
  183. $model = new TestEloquentModelWithAttributeCast;
  184. $previous = $model->virtualObjectWithoutCachingFluent;
  185. foreach (range(0, 10) as $ignored) {
  186. $this->assertNotSame($previous, $previous = $model->virtualObjectWithoutCachingFluent);
  187. }
  188. }
  189. public function testCastsThatOnlyHaveGetterThatReturnsDateTimeAreNotCachedFluent()
  190. {
  191. $model = new TestEloquentModelWithAttributeCast;
  192. $previous = $model->virtualDateTimeWithoutCachingFluent;
  193. foreach (range(0, 10) as $ignored) {
  194. $this->assertNotSame($previous, $previous = $model->virtualDateTimeWithoutCachingFluent);
  195. }
  196. }
  197. }
  198. class TestEloquentModelWithAttributeCast extends Model
  199. {
  200. /**
  201. * The attributes that aren't mass assignable.
  202. *
  203. * @var string[]
  204. */
  205. protected $guarded = [];
  206. public function uppercase(): Attribute
  207. {
  208. return new Attribute(
  209. function ($value) {
  210. return strtoupper($value);
  211. },
  212. function ($value) {
  213. return strtoupper($value);
  214. }
  215. );
  216. }
  217. public function address(): Attribute
  218. {
  219. return new Attribute(
  220. function ($value, $attributes) {
  221. if (is_null($attributes['address_line_one'])) {
  222. return;
  223. }
  224. return new AttributeCastAddress($attributes['address_line_one'], $attributes['address_line_two']);
  225. },
  226. function ($value) {
  227. if (is_null($value)) {
  228. return [
  229. 'address_line_one' => null,
  230. 'address_line_two' => null,
  231. ];
  232. }
  233. return ['address_line_one' => $value->lineOne, 'address_line_two' => $value->lineTwo];
  234. }
  235. );
  236. }
  237. public function options(): Attribute
  238. {
  239. return new Attribute(
  240. function ($value) {
  241. return json_decode($value, true);
  242. },
  243. function ($value) {
  244. return json_encode($value);
  245. }
  246. );
  247. }
  248. public function birthdayAt(): Attribute
  249. {
  250. return new Attribute(
  251. function ($value) {
  252. return Carbon::parse($value);
  253. },
  254. function ($value) {
  255. return $value->format('Y-m-d');
  256. }
  257. );
  258. }
  259. public function password(): Attribute
  260. {
  261. return new Attribute(null, function ($value) {
  262. return hash('sha256', $value);
  263. });
  264. }
  265. public function virtual(): Attribute
  266. {
  267. return new Attribute(
  268. function () {
  269. return collect();
  270. }
  271. );
  272. }
  273. public function virtualString(): Attribute
  274. {
  275. return new Attribute(
  276. function () {
  277. return Str::random(10);
  278. }
  279. );
  280. }
  281. public function virtualObject(): Attribute
  282. {
  283. return new Attribute(
  284. function () {
  285. return new AttributeCastAddress(Str::random(10), Str::random(10));
  286. }
  287. );
  288. }
  289. public function virtualDateTime(): Attribute
  290. {
  291. return new Attribute(
  292. function () {
  293. return Date::now()->addSeconds(mt_rand(0, 10000));
  294. }
  295. );
  296. }
  297. public function virtualObjectWithoutCachingFluent(): Attribute
  298. {
  299. return (new Attribute(
  300. function () {
  301. return new AttributeCastAddress(Str::random(10), Str::random(10));
  302. }
  303. ))->withoutObjectCaching();
  304. }
  305. public function virtualDateTimeWithoutCachingFluent(): Attribute
  306. {
  307. return (new Attribute(
  308. function () {
  309. return Date::now()->addSeconds(mt_rand(0, 10000));
  310. }
  311. ))->withoutObjectCaching();
  312. }
  313. public function virtualObjectWithoutCaching(): Attribute
  314. {
  315. return Attribute::get(function () {
  316. return new AttributeCastAddress(Str::random(10), Str::random(10));
  317. })->withoutObjectCaching();
  318. }
  319. public function virtualDateTimeWithoutCaching(): Attribute
  320. {
  321. return Attribute::get(function () {
  322. return Date::now()->addSeconds(mt_rand(0, 10000));
  323. })->withoutObjectCaching();
  324. }
  325. }
  326. class AttributeCastAddress
  327. {
  328. public $lineOne;
  329. public $lineTwo;
  330. public function __construct($lineOne, $lineTwo)
  331. {
  332. $this->lineOne = $lineOne;
  333. $this->lineTwo = $lineTwo;
  334. }
  335. }