5 use Friendica\Database\Database;
6 use Friendica\Network\HTTPException;
7 use Psr\Log\LoggerInterface;
10 * The Model classes inheriting from this abstract class are meant to represent a single database record.
11 * The associated table name has to be provided in the child class, and the table is expected to have a unique `id` field.
15 abstract class BaseModel
19 /** @var LoggerInterface */
23 * Model record abstraction.
24 * Child classes never have to interact directly with it.
25 * Please use the magic getter instead.
32 * Used to limit/avoid updates if no data was changed.
36 private $originalData = [];
39 * @param Database $dba
40 * @param LoggerInterface $logger
41 * @param array $data Table row attributes
43 public function __construct(Database $dba, LoggerInterface $logger, array $data = [])
46 $this->logger = $logger;
48 $this->originalData = $data;
52 * Maps a data array (original/current) to a known field list of the chosen model
54 * This is useful to filter out additional attributes, which aren't part of the db-table (like readonly cached fields)
56 * @param array $data The data array to map to db-fields
58 * @return array the mapped data array
60 protected function mapFields(array $data)
65 public function getOriginalData()
67 return $this->mapFields($this->originalData);
70 public function resetOriginalData()
72 $this->originalData = $this->data;
76 * Performance-improved model creation in a loop
78 * @param BaseModel $prototype
82 public static function createFromPrototype(BaseModel $prototype, array $data)
84 $model = clone $prototype;
86 $model->originalData = $data;
92 * Magic isset method. Returns true if the field exists, either in the data prperty array or in any of the local properties.
93 * Used by array_column() on an array of objects.
98 public function __isset($name)
100 return in_array($name, array_merge(array_keys($this->data), array_keys(get_object_vars($this))));
104 * Magic getter. This allows to retrieve model fields with the following syntax:
105 * - $model->field (outside of class)
106 * - $this->field (inside of class)
110 * @throws HTTPException\InternalServerErrorException
112 public function __get($name)
116 if (!array_key_exists($name, $this->data)) {
117 throw new HTTPException\InternalServerErrorException('Field ' . $name . ' not found in ' . static::class);
120 return $this->data[$name];
124 * @param string $name
125 * @param mixed $value
127 public function __set($name, $value)
129 $this->data[$name] = $value;
132 public function toArray()
134 return $this->mapFields($this->data);
137 protected function checkValid()
139 if (empty($this->data['id'])) {
140 throw new HTTPException\InternalServerErrorException(static::class . ' record uninitialized');