1<?php
2
3namespace FYKOS\dokuwiki\Extension\PluginNewsFeed\ORM;
4
5use FYKOS\dokuwiki\Extension\PluginNewsFeed\Model\AbstractModel;
6use FYKOS\dokuwiki\Extension\PluginNewsFeed\Model\ModelPriority;
7use helper_plugin_sqlite;
8
9/**
10 * Class ServiceNews
11 * @author Michal Červeňák <miso@fykos.cz>
12 * @property ModelPriority $modelClassName
13 */
14class ServicePriority extends AbstractService {
15
16    public function __construct(helper_plugin_sqlite $sqlite) {
17        parent::__construct($sqlite, 'priority', ModelPriority::class);
18    }
19
20    public function findByNewsAndStream(int $newsId, int $streamId): ?ModelPriority {
21        $res = $this->sqlite->query('SELECT * FROM ? WHERE stream_id=? AND news_id =?', $this->table, $streamId, $newsId)->fetch();
22        return $res ? ($this->modelClassName)::createFromArray($this->sqlite, $res) : null;
23    }
24
25    public function update(AbstractModel $model, array $data): void {
26        if ((time() < strtotime($data['priority_from'])) || (time() > strtotime($data['priority_to']))) {
27            $data['priority_value'] = 0;
28        }
29        parent::update($model, $data);
30    }
31
32    public function store(int $newsId, int $streamId): void {
33        $model = $this->findByNewsAndStream($newsId, $streamId);
34        if ($model) {
35            $this->update($model, ['news_id' => $newsId, 'stream_id' => $streamId]);
36        } else {
37            $this->create(['news_id' => $newsId, 'stream_id' => $streamId, 'priority' => 0]);
38        }
39    }
40}
41