2021-03-15 17:41:39 -03:00
|
|
|
<?php
|
|
|
|
namespace ProVM\Money;
|
|
|
|
|
|
|
|
use ProVM\Common\Alias\Model;
|
2021-03-16 00:42:09 -03:00
|
|
|
use ProVM\Common\Factory\Model as ModelFactory;
|
2021-03-15 17:41:39 -03:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @property int $id
|
|
|
|
* @property string $code
|
|
|
|
* @property string $name
|
|
|
|
*/
|
|
|
|
class Currency extends Model {
|
|
|
|
public static $_table = 'currencies';
|
|
|
|
|
|
|
|
protected $values;
|
|
|
|
public function values(): ?array {
|
|
|
|
if ($this->values === null) {
|
|
|
|
$this->values = $this->parentOf(Value::class, [Model::CHILD_KEY => 'currency_id']);
|
2021-03-19 22:49:09 -03:00
|
|
|
if ($this->values) {
|
|
|
|
usort($this->values, function($a, $b) {
|
|
|
|
return $b->dateTime()->timestamp - $a->dateTime()->timestamp;
|
|
|
|
});
|
|
|
|
}
|
2021-03-15 17:41:39 -03:00
|
|
|
}
|
2021-03-16 00:42:09 -03:00
|
|
|
return $this->values;
|
|
|
|
}
|
2021-03-19 22:49:09 -03:00
|
|
|
protected $latest;
|
|
|
|
public function latest(): ?Value {
|
|
|
|
if ($this->latest === null) {
|
|
|
|
$this->latest = $this->values()[0];
|
|
|
|
}
|
|
|
|
return $this->latest;
|
|
|
|
}
|
2021-03-16 00:42:09 -03:00
|
|
|
|
|
|
|
protected static $fields = ['code', 'name'];
|
|
|
|
public static function add(ModelFactory $factory, $info) {
|
|
|
|
$input = array_intersect_key((array) $info, array_combine(self::$fields, self::$fields));
|
|
|
|
$currency = $factory->find(Currency::class)->where([['code', $input['code']]])->one();
|
|
|
|
$created = false;
|
|
|
|
$result = (object) compact('input', 'currency', 'created');
|
|
|
|
if (!$currency) {
|
|
|
|
$currency = $factory->create(Currency::class, $input);
|
|
|
|
$created = $currency->save();
|
|
|
|
$result->created = $created;
|
|
|
|
}
|
|
|
|
$result->currency = $currency->asArray();
|
|
|
|
return $result;
|
|
|
|
}
|
|
|
|
protected function checkCode(string $code): bool {
|
|
|
|
return ($this->find(Currency::class)->where([['code', $code]])->one()) ? true : false;
|
|
|
|
}
|
|
|
|
public function edit($info) {
|
|
|
|
$data = array_intersect_key((array) $info, array_combine(self::$fields, self::$fields));
|
|
|
|
$edited = false;
|
|
|
|
foreach ($data as $field => $value) {
|
|
|
|
if ($this->{$field} != $value) {
|
|
|
|
if ($field == 'code' and $this->checkCode($value)) {
|
|
|
|
throw \Exception('Currency code ' . $value . ' is already in the database.');
|
|
|
|
}
|
|
|
|
$this->{$field} = $value;
|
|
|
|
$edited = true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if ($edited) {
|
|
|
|
$edited = $this->save();
|
|
|
|
}
|
|
|
|
return $edited;
|
|
|
|
}
|
|
|
|
public function addValue($info) {
|
|
|
|
$arr = (array) $info;
|
|
|
|
$arr['currency_id'] = (int) $this->id;
|
|
|
|
$result = Value::add($this->factory, $arr);
|
|
|
|
return $result;
|
2021-03-15 17:41:39 -03:00
|
|
|
}
|
|
|
|
}
|