Entity.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCP\AppFramework\Db;
  8. use OCP\DB\Types;
  9. use function lcfirst;
  10. use function substr;
  11. /**
  12. * @method int getId()
  13. * @method void setId(int $id)
  14. * @since 7.0.0
  15. * @psalm-consistent-constructor
  16. */
  17. abstract class Entity {
  18. /**
  19. * @var int
  20. */
  21. public $id;
  22. private array $_updatedFields = [];
  23. /** @var array<string, \OCP\DB\Types::*> */
  24. private array $_fieldTypes = ['id' => 'integer'];
  25. /**
  26. * Simple alternative constructor for building entities from a request
  27. * @param array $params the array which was obtained via $this->params('key')
  28. * in the controller
  29. * @since 7.0.0
  30. */
  31. public static function fromParams(array $params): static {
  32. $instance = new static();
  33. foreach ($params as $key => $value) {
  34. $method = 'set' . ucfirst($key);
  35. $instance->$method($value);
  36. }
  37. return $instance;
  38. }
  39. /**
  40. * Maps the keys of the row array to the attributes
  41. * @param array $row the row to map onto the entity
  42. * @since 7.0.0
  43. */
  44. public static function fromRow(array $row): static {
  45. $instance = new static();
  46. foreach ($row as $key => $value) {
  47. $prop = $instance->columnToProperty($key);
  48. $instance->setter($prop, [$value]);
  49. }
  50. $instance->resetUpdatedFields();
  51. return $instance;
  52. }
  53. /**
  54. * @return array<string, \OCP\DB\Types::*> with attribute and type
  55. * @since 7.0.0
  56. */
  57. public function getFieldTypes(): array {
  58. return $this->_fieldTypes;
  59. }
  60. /**
  61. * Marks the entity as clean needed for setting the id after the insertion
  62. * @since 7.0.0
  63. */
  64. public function resetUpdatedFields(): void {
  65. $this->_updatedFields = [];
  66. }
  67. /**
  68. * Generic setter for properties
  69. *
  70. * @throws \InvalidArgumentException
  71. * @since 7.0.0
  72. *
  73. */
  74. protected function setter(string $name, array $args): void {
  75. // setters should only work for existing attributes
  76. if (!property_exists($this, $name)) {
  77. throw new \BadFunctionCallException($name . ' is not a valid attribute');
  78. }
  79. if ($args[0] === $this->$name) {
  80. return;
  81. }
  82. $this->markFieldUpdated($name);
  83. // if type definition exists, cast to correct type
  84. if ($args[0] !== null && array_key_exists($name, $this->_fieldTypes)) {
  85. $type = $this->_fieldTypes[$name];
  86. if ($type === Types::BLOB) {
  87. // (B)LOB is treated as string when we read from the DB
  88. if (is_resource($args[0])) {
  89. $args[0] = stream_get_contents($args[0]);
  90. }
  91. $type = Types::STRING;
  92. }
  93. switch ($type) {
  94. case Types::BIGINT:
  95. case Types::SMALLINT:
  96. settype($args[0], Types::INTEGER);
  97. break;
  98. case Types::BINARY:
  99. case Types::DECIMAL:
  100. case Types::TEXT:
  101. settype($args[0], Types::STRING);
  102. break;
  103. case Types::TIME:
  104. case Types::DATE:
  105. case Types::DATETIME:
  106. case Types::DATETIME_TZ:
  107. if (!$args[0] instanceof \DateTime) {
  108. $args[0] = new \DateTime($args[0]);
  109. }
  110. break;
  111. case Types::TIME_IMMUTABLE:
  112. case Types::DATE_IMMUTABLE:
  113. case Types::DATETIME_IMMUTABLE:
  114. case Types::DATETIME_TZ_IMMUTABLE:
  115. if (!$args[0] instanceof \DateTimeImmutable) {
  116. $args[0] = new \DateTimeImmutable($args[0]);
  117. }
  118. break;
  119. case Types::JSON:
  120. if (!is_array($args[0])) {
  121. $args[0] = json_decode($args[0], true);
  122. }
  123. break;
  124. default:
  125. settype($args[0], $type);
  126. }
  127. }
  128. $this->$name = $args[0];
  129. }
  130. /**
  131. * Generic getter for properties
  132. * @since 7.0.0
  133. */
  134. protected function getter(string $name): mixed {
  135. // getters should only work for existing attributes
  136. if (property_exists($this, $name)) {
  137. return $this->$name;
  138. } else {
  139. throw new \BadFunctionCallException($name .
  140. ' is not a valid attribute');
  141. }
  142. }
  143. /**
  144. * Each time a setter is called, push the part after set
  145. * into an array: for instance setId will save Id in the
  146. * updated fields array so it can be easily used to create the
  147. * getter method
  148. * @since 7.0.0
  149. */
  150. public function __call(string $methodName, array $args) {
  151. if (str_starts_with($methodName, 'set')) {
  152. $this->setter(lcfirst(substr($methodName, 3)), $args);
  153. } elseif (str_starts_with($methodName, 'get')) {
  154. return $this->getter(lcfirst(substr($methodName, 3)));
  155. } elseif ($this->isGetterForBoolProperty($methodName)) {
  156. return $this->getter(lcfirst(substr($methodName, 2)));
  157. } else {
  158. throw new \BadFunctionCallException($methodName .
  159. ' does not exist');
  160. }
  161. }
  162. /**
  163. * @param string $methodName
  164. * @return bool
  165. * @since 18.0.0
  166. */
  167. protected function isGetterForBoolProperty(string $methodName): bool {
  168. if (str_starts_with($methodName, 'is')) {
  169. $fieldName = lcfirst(substr($methodName, 2));
  170. return isset($this->_fieldTypes[$fieldName]) && str_starts_with($this->_fieldTypes[$fieldName], 'bool');
  171. }
  172. return false;
  173. }
  174. /**
  175. * Mark am attribute as updated
  176. * @param string $attribute the name of the attribute
  177. * @since 7.0.0
  178. */
  179. protected function markFieldUpdated(string $attribute): void {
  180. $this->_updatedFields[$attribute] = true;
  181. }
  182. /**
  183. * Transform a database columnname to a property
  184. *
  185. * @param string $columnName the name of the column
  186. * @return string the property name
  187. * @since 7.0.0
  188. */
  189. public function columnToProperty(string $columnName): string {
  190. $parts = explode('_', $columnName);
  191. $property = '';
  192. foreach ($parts as $part) {
  193. if ($property === '') {
  194. $property = $part;
  195. } else {
  196. $property .= ucfirst($part);
  197. }
  198. }
  199. return $property;
  200. }
  201. /**
  202. * Transform a property to a database column name
  203. *
  204. * @param string $property the name of the property
  205. * @return string the column name
  206. * @since 7.0.0
  207. */
  208. public function propertyToColumn(string $property): string {
  209. $parts = preg_split('/(?=[A-Z])/', $property);
  210. $column = '';
  211. foreach ($parts as $part) {
  212. if ($column === '') {
  213. $column = $part;
  214. } else {
  215. $column .= '_' . lcfirst($part);
  216. }
  217. }
  218. return $column;
  219. }
  220. /**
  221. * @return array array of updated fields for update query
  222. * @since 7.0.0
  223. */
  224. public function getUpdatedFields(): array {
  225. return $this->_updatedFields;
  226. }
  227. /**
  228. * Adds type information for a field so that it's automatically cast to
  229. * that value once its being returned from the database
  230. *
  231. * @param string $fieldName the name of the attribute
  232. * @param \OCP\DB\Types::* $type the type which will be used to match a cast
  233. * @since 31.0.0 Parameter $type is now restricted to {@see \OCP\DB\Types} constants. The formerly accidentally supported types 'int'|'bool'|'double' are mapped to Types::INTEGER|Types::BOOLEAN|Types::FLOAT accordingly.
  234. * @since 7.0.0
  235. */
  236. protected function addType(string $fieldName, string $type): void {
  237. /** @psalm-suppress TypeDoesNotContainType */
  238. if (in_array($type, ['bool', 'double', 'int', 'array', 'object'], true)) {
  239. // Mapping legacy strings to the actual types
  240. $type = match ($type) {
  241. 'int' => Types::INTEGER,
  242. 'bool' => Types::BOOLEAN,
  243. 'double' => Types::FLOAT,
  244. 'array',
  245. 'object' => Types::STRING,
  246. };
  247. }
  248. $this->_fieldTypes[$fieldName] = $type;
  249. }
  250. /**
  251. * Slugify the value of a given attribute
  252. * Warning: This doesn't result in a unique value
  253. *
  254. * @param string $attributeName the name of the attribute, which value should be slugified
  255. * @return string slugified value
  256. * @since 7.0.0
  257. * @deprecated 24.0.0
  258. */
  259. public function slugify(string $attributeName): string {
  260. // toSlug should only work for existing attributes
  261. if (property_exists($this, $attributeName)) {
  262. $value = $this->$attributeName;
  263. // replace everything except alphanumeric with a single '-'
  264. $value = preg_replace('/[^A-Za-z0-9]+/', '-', $value);
  265. $value = strtolower($value);
  266. // trim '-'
  267. return trim($value, '-');
  268. }
  269. throw new \BadFunctionCallException($attributeName . ' is not a valid attribute');
  270. }
  271. }