Currency.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. // Copyright 2019-2022 Hackware SpA <human@hackware.cl>
  3. // This file is part of "Hackware Web Services Wallet" and licensed under
  4. // the terms of the GNU Affero General Public License version 3, or (at your
  5. // option) a later version. You should have received a copy of this license
  6. // along with the software. If not, see <https://www.gnu.org/licenses/>.
  7. namespace Hawese\Wallet;
  8. use Hawese\Core\Exceptions\ModelObjectNotFoundException;
  9. use Illuminate\Database\Query\Builder;
  10. class Currency extends TableModel
  11. {
  12. public static $table = 'currencies';
  13. public static $attributes = [
  14. 'id' => ['nullable', 'integer', 'min:1'],
  15. 'code' => ['required', 'size:3'],
  16. 'rate' => ['required', 'regex:/^\d{1,6}(?:\.\d{1,6})?$/'],
  17. 'step' => ['required', 'regex:/^\d{1,4}(?:\.\d{1,4})?$/'],
  18. 'created_at' => ['nullable', 'date'],
  19. ];
  20. /**
  21. * Select only the latest element per currency `code`
  22. */
  23. public static function select(
  24. ?array $attributes = null,
  25. bool $withDeleted = false
  26. ): Builder {
  27. $ids = app('db')
  28. ->table(self::$table)
  29. ->select(app('db')->raw('MAX(id) as id'))
  30. ->groupBy('code')
  31. ->pluck('id');
  32. return parent::select($attributes)
  33. ->whereIn('id', $ids);
  34. }
  35. /**
  36. * Return only the latest object with this `code`
  37. */
  38. public static function findByCode($code) : self
  39. {
  40. $query = 'SELECT * FROM ' . self::$table . ' ' .
  41. 'WHERE code = ? ORDER BY id DESC LIMIT 1';
  42. $row = app('db')->selectOne($query, [$code]);
  43. if ($row) {
  44. return new self($row);
  45. }
  46. throw new ModelObjectNotFoundException(static::class, ['code'], $code);
  47. }
  48. public function update($fields = []) : bool
  49. {
  50. return false;
  51. }
  52. public function delete() : bool
  53. {
  54. return false;
  55. }
  56. }