1<?php 2 3namespace FYKOS\dokuwiki\Extension\PluginNewsFeed\ORM; 4 5use FYKOS\dokuwiki\Extension\PluginNewsFeed\Model\AbstractModel; 6use helper_plugin_sqlite; 7 8/** 9 * Class AbstractService 10 * @author Michal Červeňák <miso@fykos.cz> 11 */ 12abstract class AbstractService { 13 14 protected string $table; 15 /** @var string|AbstractModel */ 16 protected string $modelClassName; 17 18 protected helper_plugin_sqlite $sqlite; 19 20 public function __construct(helper_plugin_sqlite $sqlite, string $table, string $modelClassName) { 21 $this->table = $table; 22 $this->sqlite = $sqlite; 23 $this->modelClassName = $modelClassName; 24 } 25 26 public function getById(int $id): ?AbstractModel { 27 $res = $this->sqlite->query('SELECT * FROM ' . $this->table . ' WHERE ' . $this->table . '_id = ?', (int)$id)->fetch(); 28 if ($res) { 29 return ($this->modelClassName)::createFromArray($this->sqlite, $res); 30 } 31 return null; 32 } 33 34 public function create(array $data): bool { 35 $sql = 'INSERT INTO ' . $this->table . ' (' . join(',', array_keys($data)) . ') VALUES( ' . join(',', array_fill(0, count($data), '?')) . ')'; 36 37 return (bool)$this->sqlite->query($sql, 38 ...array_values($data) 39 ); 40 } 41 42 public function update(AbstractModel $model, array $data): void { 43 $sql = 'UPDATE ' . $this->table . ' SET ' . join(',', array_map(function ($key) { 44 return $key . '=?'; 45 }, array_keys($data))) . ' WHERE ' . $this->table . '_id' . '=?'; 46 $this->sqlite->query($sql, 47 ...array_values($data), 48 ...[ 49 $model->{$this->table . 'Id'}, 50 ] 51 ); 52 } 53 54 public function getMaxId(): int { 55 $res = $this->sqlite->query('SELECT max(' . $this->table . '_id) FROM ?', $this->table); 56 return (int)$this->sqlite->res2single($res); 57 } 58 59 public function getAll(): array { 60 $models = []; 61 $res = $this->sqlite->query('SELECT * FROM ?', $this->table); 62 foreach ($this->sqlite->res2arr($res) as $row) { 63 $streams[] = ($this->modelClassName)::createFromArray($this->sqlite, $row); 64 } 65 return $models; 66 } 67 68} 69