the browser-facing portion of osu!
at master 67 lines 1.6 kB view raw
1<?php 2 3// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. 4// See the LICENCE file in the repository root for full licence text. 5 6declare(strict_types=1); 7 8namespace App\Models\Traits; 9 10use Carbon\Carbon; 11 12trait FasterAttributes 13{ 14 public function getRawAttribute(string $key) 15 { 16 return $this->attributes[$key] ?? null; 17 } 18 19 protected function getArray(string $key): ?array 20 { 21 $value = $this->getRawAttribute($key); 22 23 return $value === null ? null : json_decode($value, true); 24 } 25 26 protected function getNullableBool(string $key) 27 { 28 $raw = $this->getRawAttribute($key); 29 30 return $raw === null ? null : (bool) $raw; 31 } 32 33 /** 34 * Fast Time Attribute to Json Transformer 35 * 36 * Key must be suffixed with `_json`. 37 * This is only usable for models with default dateFormat (`Y-m-d H:i:s`). 38 */ 39 protected function getJsonTimeFast(string $key): ?string 40 { 41 $value = $this->getRawAttribute(substr($key, 0, -5)); 42 43 if ($value === null) { 44 return null; 45 } 46 47 // From: "2020-10-10 10:10:10" 48 // To: "2020-10-10T10:10:10Z" 49 $value[10] = 'T'; 50 51 return "{$value}Z"; 52 } 53 54 /** 55 * Fast Time Attribute Getter (kind of) 56 * 57 * This is only usable for models with default dateFormat (`Y-m-d H:i:s`). 58 */ 59 protected function getTimeFast(string $key): ?Carbon 60 { 61 $value = $this->getRawAttribute($key); 62 63 return $value === null 64 ? null 65 : Carbon::createFromFormat('Y-m-d H:i:s', $value); 66 } 67}