Currency.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. // Copyright 2019 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 Illuminate\Database\Query\Builder;
  9. class Currency extends TableModel
  10. {
  11. public static $table = 'currencies';
  12. public static $attributes = [
  13. 'id' => ['nullable', 'integer', 'min:1'],
  14. 'code' => ['required', 'size:3'],
  15. 'rate' => ['required', 'regex:/^\d{1,6}(?:\.\d{1,6})?$/'],
  16. 'step' => ['required', 'regex:/^\d{1,4}(?:\.\d{1,4})?$/'],
  17. 'created_at' => ['nullable', 'date'],
  18. ];
  19. /**
  20. * Select only the latest element per currency `code`
  21. */
  22. public static function select(?array $attributes = null) : Builder
  23. {
  24. $ids = app('db')
  25. ->table(self::$table)
  26. ->select(app('db')->raw('MAX(id) as id'))
  27. ->groupBy('code')
  28. ->pluck('id');
  29. return parent::select($attributes)
  30. ->whereIn('id', $ids);
  31. }
  32. /**
  33. * Return only the latest object with this `code`
  34. */
  35. public static function findByCode($code) : self
  36. {
  37. $query = 'SELECT * FROM ' . self::$table . ' ' .
  38. 'WHERE code = ? ORDER BY id DESC LIMIT 1';
  39. $row = app('db')->selectOne($query, [$code]);
  40. return new self($row);
  41. }
  42. public function update($fields = []) : bool
  43. {
  44. return false;
  45. }
  46. public function delete() : bool
  47. {
  48. return false;
  49. }
  50. }