This commit is contained in:
2021-04-12 00:38:51 -04:00
parent 190dfd7c34
commit 29d04ac4ad
2 changed files with 18 additions and 9 deletions

View File

@ -20,13 +20,19 @@ final class CreateSources extends AbstractMigration
{
$this->table('sources', [
'id' => false,
'primary_key' => ['currency_id', 'url'],
'primary_key' => ['id'],
'engine' => 'InnoDB',
'encoding' => 'utf8mb4',
'collation' => 'utf8mb4_general_ci',
'comment' => '',
'row_format' => 'DYNAMIC',
])
->addColumn('id', 'integer', [
'null' => false,
'limit' => '10',
'signed' => false,
'identity' => 'enable',
])
->addColumn('currency_id', 'integer', [
'null' => false,
'limit' => '10',
@ -47,6 +53,10 @@ final class CreateSources extends AbstractMigration
'encoding' => 'utf8mb4',
'after' => 'url',
])
->addIndex(['currency_id'], [
'name' => 'currency_id',
'unique' => false,
])
->create();
}
}

View File

@ -3,15 +3,16 @@ namespace ProVM\Money;
use Carbon\CarbonInterval;
use ProVM\Common\Alias\Model;
use ProVM\Common\Factory\Model as ModelFactory;
/**
* @property int $id
* @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 {
@ -22,7 +23,7 @@ class Source extends Model {
}
public function frecuency(\DateInterval $frecuency = null) {
if ($frecuency == null) {
return new \CarbonInterval($this->fecuency);
return CarbonInterval::createFromDateString($this->frecuency);
}
$this->frecuency = CarbonInterval::getDateIntervalSpec($frecuency);
}
@ -30,15 +31,16 @@ class Source extends Model {
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));
$input['frecuency'] = CarbonInterval::createFromDateString($input['frecuency']);
$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) {
if (!$source) {
$source = $factory->create(Source::class, $input);
$created = $source->save();
$result->created = $created;
}
$result->value = $source->asArray();
$result->source = $source->asArray();
return $result;
}
public function edit($info): bool {
@ -46,9 +48,6 @@ class Source extends Model {
$edited = false;
foreach ($data as $field => $value) {
if ($this->{$field} != $value) {
if ($field == 'currency_id' or $field == 'url') {
continue;
}
$this->{$field} = $value;
$edited = true;
}
@ -61,7 +60,7 @@ class Source extends Model {
public function asArray(): array {
$output = parent::asArray();
$output['currency'] = $this->currency()->asArray();
$output['frecuency'] = $this->frecuency()->format('Y-m-d H:i:s');
$output['frecuency'] = $this->frecuency()->spec();
return $output;
}
}