TableModel.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. <?php
  2. // Copyright 2019 Hackware SpA <human@hackware.cl>
  3. // "Hackware Web Services Core" is released under the MIT License terms.
  4. namespace Hawese\Core;
  5. use Hawese\Core\Exceptions\ModelObjectNotFoundException;
  6. use Hawese\Core\Exceptions\ModelValidationException;
  7. use Hawese\Core\Exceptions\UnknownForeignObjectException;
  8. use Illuminate\Contracts\Support\Arrayable;
  9. use Illuminate\Contracts\Support\Jsonable;
  10. use Illuminate\Database\Query\Builder;
  11. use Illuminate\Support\Carbon;
  12. use Illuminate\Support\Collection;
  13. use Illuminate\Validation\ValidationException;
  14. use ArrayAccess;
  15. use Exception;
  16. use JsonSerializable;
  17. /**
  18. * Base class for CRUD database models.
  19. *
  20. * You always need to define the static `$table` and `$attributes` props.
  21. *
  22. * - Supports find($pk), insert(), update() and delete() operations.
  23. * - select() will return a Laravel's Query Builder object.
  24. * - processCollection() will process each element of a Query Builder produced
  25. * resultset with this class and allow you to `appendForeignObjects`.
  26. * - If you use the `created_at`, `updated_at` and/or `deleted_at` `$attributes`
  27. * in your class declaration, it will automagically fill those fields.
  28. */
  29. abstract class TableModel implements
  30. ArrayAccess,
  31. JsonSerializable,
  32. Arrayable,
  33. Jsonable
  34. {
  35. public static $table;
  36. public static $attributes = []; // ['prop1' => ['validations'], ...]
  37. protected $appends = []; // Append JSONable attributes at runtime
  38. protected $hidden = ['deleted_at']; // Hide from serialization
  39. public static $primary_key = 'id';
  40. protected static $incrementing = true;
  41. public static $foreign_keys = []; // ['foreign_key' => Class::class, ...]
  42. protected $data = []; // Where $attributes values are saved
  43. protected $current_primary_key;
  44. /**
  45. * Bootstrapping
  46. * =============
  47. */
  48. /**
  49. * @param (array|object)[] $data Associative data with object attributes.
  50. */
  51. public function __construct($data = null)
  52. {
  53. $this->data = array_fill_keys(static::attributes(), null);
  54. if (isset($data)) {
  55. foreach ($data as $key => $value) {
  56. $this->{$key} = $value;
  57. }
  58. }
  59. $this->current_primary_key = $this->{static::$primary_key};
  60. }
  61. /**
  62. * Magic accesors.
  63. *
  64. * Custom getters must be camelCased and start with `get` followed by
  65. * `AttributeName`.
  66. *
  67. * ```php
  68. * protected function getCustomAttribute()
  69. * {
  70. * return $this->data['custom_attribute'];
  71. * }
  72. * ```
  73. */
  74. public function __get(string $name)
  75. {
  76. $getter = 'get' . self::snakeToPascalCase($name);
  77. if (method_exists(static::class, $getter)) {
  78. return $this->{$getter}();
  79. }
  80. if (in_array($name, $this->instanceAttributes())) {
  81. return $this->data[$name] ?? null;
  82. }
  83. $trace = debug_backtrace();
  84. trigger_error(
  85. 'Undefined property via __get(): ' . $name .
  86. ' in ' . $trace[0]['file'] .
  87. ' on line ' . $trace[0]['line'],
  88. E_USER_NOTICE
  89. );
  90. return null;
  91. }
  92. /**
  93. * Magic mutators.
  94. *
  95. * Custom setters must be camelCased and start with `set` followed by
  96. * `AttributeName`, `$new_value` must be assigned to the local
  97. * `$data['attribute_name']` store.
  98. *
  99. * ```php
  100. * protected function setCustomAttribute($new_value)
  101. * {
  102. * $this->data['custom_attribute'] = $new_value;
  103. * }
  104. * ```
  105. */
  106. public function __set(string $name, $value)
  107. {
  108. $setter = 'set' . self::snakeToPascalCase($name);
  109. if (method_exists(static::class, $setter)) {
  110. return $this->{$setter}($value);
  111. }
  112. if (in_array($name, $this->instanceAttributes())) {
  113. return $this->data[$name] = $value;
  114. }
  115. $trace = debug_backtrace();
  116. trigger_error(
  117. 'Undefined property via __set(): ' . $name .
  118. ' in ' . $trace[0]['file'] .
  119. ' on line ' . $trace[0]['line'],
  120. E_USER_NOTICE
  121. );
  122. }
  123. public function __isset(string $name)
  124. {
  125. return isset($this->data[$name]);
  126. }
  127. /**
  128. * Implements ArrayAccess.
  129. *
  130. * So you can ->pluck() on a collection or do these kind of nice things
  131. */
  132. public function offsetExists($offset)
  133. {
  134. return !!$this->{$offset};
  135. }
  136. public function offsetGet($offset)
  137. {
  138. return $this->{$offset};
  139. }
  140. public function offsetSet($offset, $value)
  141. {
  142. $this->{$offset} = $value;
  143. }
  144. public function offsetUnset($offset)
  145. {
  146. unset($this->data[$offset]);
  147. }
  148. /**
  149. * Implements toArray
  150. */
  151. public function toArray()
  152. {
  153. $data = [];
  154. // Process getters
  155. foreach ($this->instanceAttributes() as $attribute) {
  156. if ($this->{$attribute} instanceof Carbon) {
  157. // for $(crea|upda|dele)ted_at
  158. $data[$attribute] = $this->{$attribute}->format('c');
  159. } elseif ($this->{$attribute} instanceof Arrayable) {
  160. // for $foreign_keys
  161. $data[$attribute] = $this->{$attribute}->toArray();
  162. } else {
  163. $data[$attribute] = $this->{$attribute};
  164. }
  165. }
  166. // Forget hidden attributes
  167. // Not in toJson(), since in that context is not possible to determine
  168. // foreign object's hidden attributes.
  169. foreach ($this->hidden as $attribute) {
  170. unset($data[$attribute]);
  171. }
  172. return $data;
  173. }
  174. /**
  175. * Implements JsonSerializable
  176. */
  177. public function jsonSerialize()
  178. {
  179. return $this->toArray();
  180. }
  181. /**
  182. * Implements Jsonable
  183. */
  184. public function toJson($options = 0)
  185. {
  186. return json_encode($this->jsonSerialize(), $options);
  187. }
  188. /**
  189. * Automagically use carbon on $(crea|upda|dele)ted_at
  190. */
  191. protected function dateSetter($attribute, $date) : void
  192. {
  193. if ($date instanceof Carbon || empty($date)) {
  194. $this->data[$attribute] = $date;
  195. } else {
  196. $this->data[$attribute] = new Carbon($date);
  197. }
  198. }
  199. public function setCreatedAt($value) : void
  200. {
  201. $this->dateSetter('created_at', $value);
  202. }
  203. public function setUpdatedAt($value) : void
  204. {
  205. $this->dateSetter('updated_at', $value);
  206. }
  207. public function setDeletedAt($value) : void
  208. {
  209. $this->dateSetter('deleted_at', $value);
  210. }
  211. /**
  212. * Return previously loaded relationship or load it now
  213. */
  214. protected function foreignObjectGetter($attribute)
  215. {
  216. if (array_key_exists($attribute, $this->data)) {
  217. return $this->data[$attribute];
  218. }
  219. $foreign_key = static::guessFK($attribute);
  220. return static::$foreign_keys[$foreign_key]::find($this->{$foreign_key});
  221. }
  222. /**
  223. * Main functionality
  224. * ==================
  225. */
  226. public static function select(?array $attributes = null) : Builder
  227. {
  228. if (!$attributes) {
  229. $attributes = static::attributes();
  230. }
  231. return app('db')
  232. ->table(static::$table)
  233. ->select(
  234. preg_filter('/^/', static::$table . '.', $attributes)
  235. );
  236. }
  237. /**
  238. * @params string $value checks against this value for equality.
  239. * @params string|array $fields field to compare, defaults to
  240. * static::$primary_key, if array is provided will try with any of
  241. * the provided fields.
  242. */
  243. public static function find(string $value, $fields = null) : self
  244. {
  245. $fields = $fields ?? static::$primary_key;
  246. if (!is_array($fields)) {
  247. $fields = [$fields];
  248. }
  249. $query = 'SELECT * FROM ' . static::$table . ' WHERE ';
  250. $query_fields = $fields;
  251. array_walk($query_fields, function (&$field) {
  252. $field = static::$table . ".$field = ? ";
  253. });
  254. $query .= implode(' OR ', $query_fields);
  255. if (in_array('deleted_at', static::attributes())) {
  256. $query .= 'AND deleted_at IS NULL';
  257. }
  258. $row = app('db')->selectOne(
  259. $query,
  260. array_fill(0, count($fields), $value)
  261. );
  262. if ($row) {
  263. return new static($row);
  264. }
  265. throw new ModelObjectNotFoundException(
  266. static::class,
  267. implode(' or ', $fields),
  268. $value
  269. );
  270. }
  271. /**
  272. * @return mixed primary key value
  273. */
  274. public function insert()
  275. {
  276. $this->validate();
  277. $fields_to_insert = static::attributes();
  278. if (in_array('created_at', $this->instanceAttributes())) {
  279. $this->created_at = new Carbon();
  280. }
  281. $query = 'INSERT INTO ' . static::$table . ' (';
  282. $query .= implode(
  283. ',',
  284. preg_filter('/^/', static::$table . '.', $fields_to_insert)
  285. );
  286. $query .= ') VALUES (';
  287. $query .= trim(str_repeat('?,', count($fields_to_insert)), ',');
  288. $query .= ')';
  289. app('db')->insert(
  290. $query,
  291. array_map(
  292. function ($field) {
  293. return $this->{$field};
  294. },
  295. $fields_to_insert
  296. )
  297. );
  298. if (static::$incrementing) {
  299. $this->{static::$primary_key} = app('db')->getPdo()->lastInsertId();
  300. }
  301. return $this->{static::$primary_key};
  302. }
  303. public function update($fields = []) : bool
  304. {
  305. $this->validate();
  306. if (empty($fields)) {
  307. $fields = array_filter(
  308. static::attributes(),
  309. function ($attribute) {
  310. return isset($this->data[$attribute]);
  311. }
  312. );
  313. }
  314. if (in_array('updated_at', $this->instanceAttributes())) {
  315. if (!in_array('updated_at', $fields)) {
  316. array_push($fields, 'updated_at');
  317. }
  318. $this->updated_at = new Carbon();
  319. }
  320. $query = 'UPDATE ' . static::$table . ' SET';
  321. $query .= trim(array_reduce(
  322. $fields,
  323. function ($carry, $item) {
  324. return $carry . ' ' . static::$table . ".$item=?,";
  325. },
  326. ''
  327. ), ',');
  328. $query .= ' WHERE ' . static::$primary_key . ' = ?';
  329. $operation = app('db')->update(
  330. $query,
  331. array_merge(
  332. array_map(
  333. function ($field) {
  334. return $this->{$field};
  335. },
  336. $fields
  337. ),
  338. [$this->current_primary_key]
  339. )
  340. );
  341. if ($operation) {
  342. $this->current_primary_key = $this->{static::$primary_key};
  343. }
  344. return $operation;
  345. }
  346. public function delete() : bool
  347. {
  348. return static::staticDelete([$this->{static::$primary_key}]);
  349. }
  350. /**
  351. * Delete (potentially massively) based on primary key
  352. */
  353. public static function staticDelete(array $primary_keys): bool
  354. {
  355. $question_marks = self::commaStrRepeat('?', count($primary_keys));
  356. if (in_array('deleted_at', static::attributes())) {
  357. $deleted_at = new Carbon();
  358. return app('db')->update(
  359. 'UPDATE ' . static::$table . ' SET' .
  360. ' deleted_at=? WHERE ' . static::$table . '.' .
  361. static::$primary_key . " IN ($question_marks)",
  362. array_merge([Carbon::now()], $primary_keys)
  363. );
  364. }
  365. return app('db')->delete(
  366. 'DELETE FROM ' . static::$table .
  367. ' WHERE ' . static::$table . '.' . static::$primary_key .
  368. " IN ($question_marks)",
  369. $primary_keys
  370. );
  371. }
  372. public function validate()
  373. {
  374. try {
  375. return app('validator')
  376. ->make($this->data, static::$attributes)
  377. ->validate();
  378. } catch (ValidationException $e) {
  379. throw new ModelValidationException(
  380. static::class,
  381. $e->validator,
  382. $e->response,
  383. $e->errorBag
  384. );
  385. }
  386. }
  387. /**
  388. * Convert QueryBuilder's `get()` objects into this class' objects.
  389. *
  390. * This will allow to process getters and setters and give superpowers to
  391. * each object.
  392. *
  393. * @param Collection $objects Collection of plain objects.
  394. * @return Collection Collection of this class' objects.
  395. */
  396. public static function processCollection(
  397. Collection $objects
  398. ) : TableModelCollection {
  399. return new TableModelCollection($objects, static::class);
  400. }
  401. /**
  402. * Helpers
  403. * =======
  404. */
  405. public static function attributes() : array
  406. {
  407. return array_keys(static::$attributes);
  408. }
  409. public function instanceAttributes() : array
  410. {
  411. return array_merge(static::attributes(), $this->appends);
  412. }
  413. public static function foreignKeys() : array
  414. {
  415. return array_keys(static::$foreign_keys);
  416. }
  417. /*
  418. public static function foreignKeyObjectAttributes() : array
  419. {
  420. return array_map(function($foreign_key) {
  421. return preg_replace('/_[^_]*$/', '', $foreign_key);
  422. }, array_keys(static::$foreign_keys));
  423. }
  424. */
  425. public static function guessFK($attribute) : string
  426. {
  427. foreach (static::foreignKeys() as $foreign_key) {
  428. if (preg_match(
  429. '/^' . $attribute . '_[^_]+$/',
  430. $foreign_key,
  431. $matches
  432. )) {
  433. return $matches[0];
  434. }
  435. }
  436. throw new UnknownForeignObjectException(static::class, $attribute);
  437. }
  438. // Append attribute dynamically, so it can be get and set on a instance
  439. public function append($attribute) : void
  440. {
  441. array_push($this->appends, $attribute);
  442. }
  443. /**
  444. * General helpers
  445. * ===============
  446. *
  447. * This helpers might be useful out of this context too
  448. */
  449. protected static function snakeToPascalCase(string $str)
  450. {
  451. return str_replace('_', '', ucwords($str, '_'));
  452. }
  453. protected static function commaStrRepeat(string $input, int $multiplier)
  454. {
  455. if ($multiplier == 0) {
  456. return "";
  457. }
  458. return str_repeat("$input,", $multiplier - 1) . $input;
  459. }
  460. protected static function bcAbs(string $value)
  461. {
  462. return trim($value, '-');
  463. }
  464. }