68 lines
2.1 KiB
PHP
68 lines
2.1 KiB
PHP
<?php
|
|
namespace ProVM\Money;
|
|
|
|
use Carbon\CarbonInterval;
|
|
use ProVM\Common\Alias\Model;
|
|
|
|
/**
|
|
* @property Currency $currency_id
|
|
* @property string $url
|
|
* @property \DateInterval $frecuency
|
|
*/
|
|
class Source extends Model {
|
|
public static $_table = 'sources';
|
|
public static $_id_column = ['currency_id', 'url'];
|
|
|
|
protected $currency;
|
|
public function currency(): ?Currency {
|
|
if ($this->currency === null) {
|
|
$this->currency = $this->childOf(Currency::class, [Model::SELF_KEY => 'currency_id']);
|
|
}
|
|
return $this->currency;
|
|
}
|
|
public function frecuency(\DateInterval $frecuency = null) {
|
|
if ($frecuency == null) {
|
|
return new \CarbonInterval($this->fecuency);
|
|
}
|
|
$this->frecuency = CarbonInterval::getDateIntervalSpec($frecuency);
|
|
}
|
|
|
|
protected static $fields = ['currency_id', 'url', 'frecuency'];
|
|
public static function add(ModelFactory $factory, $info) {
|
|
$input = array_intersect_key((array) $info, array_combine(self::$fields, self::$fields));
|
|
$source = $factory->find(Source::class)->where([['currency_id', $input['currency_id']], ['url', $input['url']]])->one();
|
|
$created = false;
|
|
$result = (object) compact('input', 'source', 'created');
|
|
if (!$value) {
|
|
$source = $factory->create(Source::class, $input);
|
|
$created = $source->save();
|
|
$result->created = $created;
|
|
}
|
|
$result->value = $source->asArray();
|
|
return $result;
|
|
}
|
|
public function edit($info): bool {
|
|
$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 == 'url') {
|
|
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['frecuency'] = $this->frecuency()->format('Y-m-d H:i:s');
|
|
return $output;
|
|
}
|
|
}
|