Files
money/src/Value.php

74 lines
2.3 KiB
PHP

<?php
namespace ProVM\Money;
use ProVM\Common\Alias\Model;
use ProVM\Common\Define\Model\DateTime;
use ProVM\Common\Factory\Model as ModelFactory;
/**
* @property Currency $currency_id
* @property \DateTime $date_time
* @property double $value
* @property Currency $base_id
*/
class Value extends Model {
use DateTime;
public static $_table = 'values';
public static $_id_column = ['currency_id', 'base_id', 'date_time'];
protected $currency;
public function currency(): ?Currency {
if ($this->currency === null) {
$this->currency = $this->childOf(Currency::class, [Model::SELF_KEY => 'currency_id']);
}
return $this->currency;
}
protected $base;
public function base(): ?Currency {
if ($this->base === null) {
$this->base = $this->childOf(Currency::class, [Model::SELF_KEY => 'base_id']);
}
return $this->base;
}
protected static $fields = ['currency_id', 'date_time', 'value', 'base_id'];
public static function add(ModelFactory $factory, $info) {
$input = array_intersect_key((array) $info, array_combine(self::$fields, self::$fields));
$value = $factory->find(Value::class)->where([['currency_id', $input['currency_id']], ['date_time', $input['date_time']], ['base_id', $input['base_id']]])->one();
$created = false;
$result = (object) compact('input', 'value', 'created');
if (!$value) {
$value = $factory->create(Value::class, $input);
$created = $value->save();
$result->created = $created;
}
$result->value = $value->asArray();
return $result;
}
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 == 'currency_id' or $field == 'base_id') {
continue;
}
$this->{$field} = $value;
$edited = true;
}
}
if ($edited) {
$edited = $this->save();
}
return $edited;
}
public function asArray(): array {
$output = parent::asArray();
$output['currency'] = $this->currency()->asArray();
$output['base'] = $this->base()->asArray();
$output['date_time'] = $this->dateTime()->format('Y-m-d H:i:s');
return $output;
}
}