Entity.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. <?php
  2. namespace ORM;
  3. abstract class Entity {
  4. const _tableName = '';
  5. const _connectionName = 'default';
  6. const _softdelete = false;
  7. const _ignore = Array(
  8. 'classname',
  9. '_properties',
  10. '_ignore',
  11. '_connectionName',
  12. '_timestamps',
  13. '_softdelete',
  14. '_tableName',
  15. '_idPolice'
  16. );
  17. const _properties = Array();
  18. /*
  19. * [type] = nextval| manual | empty is the default
  20. * [max] = maximum value allowed
  21. * [min] = minumul value allowed
  22. * [step] = increment by n each id
  23. */
  24. const _idPolice = Array();
  25. function __construct() {
  26. if (isset($this->_timestamps) && $this->_timestamps) {
  27. $this->created_at = date('Y-m-d h:m:s');
  28. $this->updated_at = date('Y-m-d h:m:s');
  29. }
  30. }
  31. public function __set($property, $value) {
  32. if (in_array($property, static::_ignore)) {
  33. return;
  34. }
  35. $this->$property = $value;
  36. }
  37. public function __get($key) {
  38. if (!isset($this->$key)) {
  39. return 0;
  40. }
  41. return $this->toArray()[$key];
  42. }
  43. public function __toString() {
  44. if (isset($this->name)) {
  45. return $this->name;
  46. }
  47. if (isset($this->nome)) {
  48. return $this->nome;
  49. }
  50. return static::class;
  51. }
  52. public function charge($payload) {
  53. foreach (static::_properties as $key => $property) {
  54. $this->$property = $payload[$property];
  55. }
  56. return [];
  57. }
  58. public static function get_properties() {
  59. $properties = Array();
  60. foreach (static::_properties as $propertie) {
  61. $obj = new \stdClass();
  62. $obj->data = $propertie;
  63. $properties[] = $obj;
  64. }
  65. return json_encode($properties);
  66. }
  67. public function save() {
  68. if (isset($this->id)) {
  69. $this->update();
  70. } else {
  71. $this->create();
  72. }
  73. }
  74. private function update() {
  75. //First check if the record exist. If not, we might have a idPolice
  76. if (!DBInstance::queryOne("SELECT id FROM {" . static::_tableName . "} WHERE id = ?", Array($this->id))) {
  77. $this->create();
  78. return;
  79. }
  80. $updatekeys = static::_ignore;
  81. $updatekeys[] = 'id';
  82. $columns = array_diff(array_keys(get_object_vars($this)), $updatekeys);
  83. $obj = (array) $this;
  84. $update_string = '';
  85. $update_data = Array();
  86. $update_data['_update_id'] = $this->id;
  87. foreach ($columns as $column) {
  88. $update_string .= $column . " = :$column, ";
  89. $update_data[$column] = $obj[$column];
  90. }
  91. $update_string = rtrim($update_string, ', ');
  92. $sql = "UPDATE {" . static::_tableName . "} SET $update_string WHERE id = :_update_id";
  93. DBInstance::execute($sql, $update_data, static::_connectionName);
  94. }
  95. private function create() {
  96. //First, let's verify id polices
  97. //Manual and empty don't need special treatments
  98. if (!empty(static::_idPolice) && static::_idPolice['type'] != 'manual') {
  99. //Get the actual max value of the key
  100. $maxVal = DBInstance::queryOne("SELECT max(id) as id FROM {" . static::_tableName . "}");
  101. $maxVal = ($maxVal) ? $maxVal : 0;
  102. // If the next val is smaller than the minumum value
  103. if (isset(static::_idPolice['min']) && static::_idPolice['min'] > $maxVal->id+1) {
  104. // The id value shpuld assume the min value
  105. $this->id = static::_idPolice['min'];
  106. } else {
  107. // The id is bigger than the min or min is not set
  108. if (isset(static::_idPolice['step'])) {
  109. //If sted is defined, increment by step multiples
  110. $this->id = $maxVal->id + static::_idPolice['step'];
  111. } else {
  112. $this->id = $maxVal->id + 1;
  113. }
  114. }
  115. //If the id is bigger than the max value. There is problems
  116. if (isset(static::_idPolice['max']) && $maxVal->id > static::_idPolice['max']) {
  117. //Do not store the register
  118. return false;
  119. }
  120. }
  121. $columns = array_diff(array_keys(get_object_vars($this)), static::_ignore);
  122. $obj = (array) $this;
  123. $first_argument = '';
  124. $second_argument = '';
  125. $insert_data = Array();
  126. foreach ($columns as $column) {
  127. $first_argument .= $column . ', ';
  128. $insert_data[$column] = $obj[$column];
  129. $second_argument .= ":$column, ";
  130. }
  131. $first_argument = rtrim($first_argument, ', ');
  132. $second_argument = rtrim($second_argument, ', ');
  133. $sql = "INSERT INTO {" . static::_tableName . "} ($first_argument) VALUES ($second_argument)";
  134. DBInstance::execute($sql, $insert_data, static::_connectionName);
  135. // If there is a id pollice applied, do not get the inserted id
  136. if (empty(static::_idPolice)) {
  137. $this->id = DBInstance::lastInsert();
  138. }
  139. }
  140. public function delete() {
  141. if (isset($this->_softdelete) && $this->_softdelete) {
  142. $this->deleted_at = date('Y-m-d h:m:s');
  143. $this->update();
  144. return;
  145. }
  146. $this->purge();
  147. }
  148. public function load($id = false) {
  149. if (!$id) {
  150. return;
  151. }
  152. $sql = "SELECT * FROM {" . static::_tableName . "} WHERE id = ?";
  153. $this->fill(DBInstance::queryPrepare($sql, Array($id), static::_connectionName)[0]);
  154. }
  155. public function purge() {
  156. $sql = "DELETE FROM {" . static::_tableName . "} WHERE id = :id";
  157. DBInstance::execute($sql, Array('id' => $this->id), static::_connectionName);
  158. }
  159. private function fill($data) {
  160. $data = (array) $data;
  161. foreach ($data as $key => $value) {
  162. $this->$key = $value;
  163. }
  164. }
  165. /**
  166. * Find All
  167. *
  168. * This method will load all instances from the class.
  169. * Limits are avaliable for paginations.
  170. *
  171. * @param Array $select Columns to select. Array('id', 'name')
  172. * @param Array $limits Array( 'offset'=> 10, 'limit' => 10 )
  173. * @param boolean $trashed Bring trashed elements?
  174. */
  175. public static function findAll($select = Array('*'), $limits = Array(), $trashed = false) {
  176. $criteria = '';
  177. $limits_sql = '';
  178. foreach ($select as $value) {
  179. $criteria .= $value . ', ';
  180. }
  181. $criteria = rtrim($criteria, ', ');
  182. foreach ($limits as $key => $value) {
  183. $limits_sql .= "$key $value ";
  184. }
  185. if (static::_softdelete && !$trashed) {
  186. $sql = "SELECT $criteria FROM {" . static::_tableName . "} WHERE deleted_at is null $limits_sql";
  187. } else {
  188. $sql = "SELECT $criteria FROM {" . static::_tableName . "} $limits_sql";
  189. }
  190. $results = DBInstance::query($sql, Array(), static::_connectionName);
  191. $objects = Array();
  192. foreach ($results as $value) {
  193. $static = static::class;
  194. $object = new $static;
  195. $object->fill($value);
  196. $objects[] = $object;
  197. }
  198. return $objects;
  199. }
  200. /**
  201. * Count
  202. *
  203. * Count how many records there is on the database
  204. * in relation with this class with the parameters filter
  205. *
  206. * @param Array $criterias Criteras for WHERE Array('id' => Array('=', 10) )
  207. * @param boolean $trashed Bring trashed registers?
  208. *
  209. */
  210. public static function count($criterias = Array(), $trashed = false) {
  211. $criteria_sql = "";
  212. $criteria_data = Array();
  213. foreach ($criterias as $key => $criteria) {
  214. if ($criteria_sql != "") {
  215. $criteria_sql .= " AND ";
  216. } else {
  217. $criteria_sql .= " WHERE ";
  218. }
  219. if (is_array($criteria[1])) {
  220. $crit_temp = '';
  221. foreach ($criteria[1] as $crit) {
  222. $crit_temp .= '?, ';
  223. $criteria_data[] = $crit;
  224. }
  225. $crit_temp = rtrim($crit_temp, ', ');
  226. $criteria_sql .= "$key $criteria[0] ($crit_temp)";
  227. } else {
  228. $criteria_sql .= "$key $criteria[0] (?) ";
  229. $criteria_data[] = $criteria[1];
  230. }
  231. }
  232. if (static::_softdelete && !$trashed) {
  233. $sql = "SELECT COUNT(*) FROM {" . static::_tableName . "} $criteria_sql AND deleted_at is null";
  234. } else {
  235. $sql = "SELECT COUNT(*) FROM {" . static::_tableName . "} $criteria_sql";
  236. }
  237. $results = DBInstance::queryOne($sql, $criteria_data, static::_connectionName);
  238. return $results->count;
  239. }
  240. /**
  241. * Find One
  242. *
  243. * @param Array/Int $criterias Array('id' => Array('in', Array(10, 20, 30)))
  244. * @param Array $select Array(id, fullname)
  245. * @param Boolan $trashed true, false
  246. */
  247. public static function findOne($criterias = Array(), $select = Array('*'), $trashed = false) {
  248. $select_sql = "";
  249. $criteria_sql = "";
  250. $limits_sql = "";
  251. $criteria_data = Array();
  252. $limits = Array("LIMIT" => 1);
  253. if (is_numeric($criterias)) {
  254. $criteria_sql = "WHERE id = ? ";
  255. $criteria_data[] = $criterias;
  256. } else {
  257. foreach ($criterias as $key => $criteria) {
  258. if ($criteria_sql != "") {
  259. $criteria_sql .= " AND ";
  260. } else {
  261. $criteria_sql .= " WHERE ";
  262. }
  263. if (is_array($criteria[1])) {
  264. $crit_temp = '';
  265. foreach ($criteria[1] as $crit) {
  266. $crit_temp .= '?, ';
  267. $criteria_data[] = $crit;
  268. }
  269. $crit_temp = rtrim($crit_temp, ', ');
  270. $criteria_sql .= "$key $criteria[0] ($crit_temp)";
  271. } else {
  272. $criteria_sql .= "$key $criteria[0] (?) ";
  273. $criteria_data[] = $criteria[1];
  274. }
  275. }
  276. }
  277. foreach ($select as $value) {
  278. $select_sql .= $value . ', ';
  279. }
  280. $select_sql = rtrim($select_sql, ', ');
  281. foreach ($limits as $key => $value) {
  282. $limits_sql .= "$key $value ";
  283. }
  284. if (static::_softdelete && !$trashed) {
  285. $sql = "SELECT $select_sql FROM {" . static::_tableName . "} $criteria_sql AND deleted_at is null $limits_sql";
  286. } else {
  287. $sql = "SELECT $select_sql FROM {" . static::_tableName . "} $criteria_sql $limits_sql";
  288. }
  289. $results = DBInstance::query($sql, $criteria_data, static::_connectionName);
  290. $objects = Array();
  291. foreach ($results as $value) {
  292. $class = static::class;
  293. $object = new $class;
  294. $object->fill($value);
  295. $objects[] = $object;
  296. }
  297. if (empty($objects)) {
  298. //return false; //new $this->classname;
  299. $className = static::class;
  300. return new $className;
  301. }
  302. return $objects[0];
  303. }
  304. /**
  305. * Find Many
  306. *
  307. * @param Array $criterias Description
  308. * @param Array $select Description
  309. * @param Array $limits Description
  310. * @param boolean $trashed Description
  311. *
  312. */
  313. public static function findMany($criterias = Array(), $select = Array('*'), $limits = Array(), $trashed = false) {
  314. $select_sql = "";
  315. $criteria_sql = "";
  316. $limits_sql = "";
  317. foreach ($limits as $key => $value) {
  318. $limits_sql .= "$key $value ";
  319. }
  320. foreach ($criterias as $key => $criteria) {
  321. if ($criteria_sql != "") {
  322. $criteria_sql .= " AND ";
  323. } else {
  324. $criteria_sql .= " WHERE ";
  325. }
  326. if (is_string($criteria[1])) {
  327. $criteria_sql .= "$key $criteria[0] '$criteria[1]'";
  328. } else if (is_array($criteria[1])) {
  329. $criteria_sql .= "$key $criteria[0] (" . implode(', ', $criteria[1]) . ")";
  330. } else {
  331. $criteria_sql .= "$key $criteria[0] $criteria[1]";
  332. }
  333. }
  334. foreach ($select as $value) {
  335. $select_sql .= $value . ', ';
  336. }
  337. $select_sql = rtrim($select_sql, ', ');
  338. if (static::_softdelete && !$trashed) {
  339. $sql = "SELECT $select_sql FROM {" . static::_tableName . "} $criteria_sql AND deleted_at is null $limits_sql";
  340. } else {
  341. $sql = "SELECT $select_sql FROM {" . static::_tableName . "} $criteria_sql $limits_sql";
  342. }
  343. $results = DBInstance::query($sql, Array(), static::_connectionName);
  344. $objects = Array();
  345. foreach ($results as $value) {
  346. $class = static::class;
  347. $object = new $class;
  348. $object->fill($value);
  349. $objects[] = $object;
  350. }
  351. if (empty($objects)) {
  352. return Array();
  353. }
  354. return $objects;
  355. }
  356. /**
  357. * Has One Local
  358. *
  359. * Defines that, this object has a child an only one,
  360. * object in other class.
  361. *
  362. * Table user = (id, name)
  363. * Table phone = (id, number, userid)
  364. *
  365. * This relation will be created on the User class
  366. * making reference to the Phone class
  367. *
  368. * @ctag $this->hasOne('foreign_object', 'field_in_remote');
  369. *
  370. * @param Object $foreign_object Class instance from the remote object
  371. * @param (int, string) $field_in_remote Field in local object matchin the remote id
  372. *
  373. * @return Object Instance of the remote class
  374. *
  375. */
  376. protected function hasOne($foreign_object, $field_in_remote) {
  377. $obj = new $foreign_object;
  378. return $obj->findOne(Array($field_in_remote => Array('=', $this->id)));
  379. }
  380. /**
  381. * Has Many
  382. *
  383. * Defines that, this object has many instances of other Object
  384. *
  385. * Table Post = (id, name, content)
  386. * Table Comment = (id, name, content, postid)
  387. *
  388. * This relation will be created on the Post class
  389. * Making reference to the Comment class
  390. *
  391. * @ctag $this->hasMany('foreign_object', 'field_in_foreign');
  392. *
  393. * @param type $foreign_object Instance of a remote class
  394. * @param (int, string) $field_in_foreign The field to match the local id
  395. *
  396. */
  397. protected function hasMany($foreign_object, $field_in_foreign) {
  398. $obj = new $foreign_object;
  399. return $obj->findMany(Array($field_in_foreign => Array('=', $this->id)));
  400. }
  401. /**
  402. * Belongs To
  403. *
  404. * Defines that, this object is part of an other class.
  405. * The local field must match the id of an other class.
  406. *
  407. * Table Post = (id, name, content)
  408. * Table Comment = (id, name, content, postid)
  409. *
  410. * This relation will be created on the comment class
  411. * Making reference to the post class
  412. *
  413. * @ctag $this->belongsTo('foreign_object', 'local_field');
  414. * @ctag $this->belongsTo('foreign_object', 'local_field', 'id');
  415. *
  416. * @param Object $foreign_object Instance of a remote class
  417. * @param (int, String) $local_field Remote field relate to local Object
  418. * @param string $remote_field
  419. */
  420. protected function belongsTo($foreign_object, $local_field, $remote_field = 'id') {
  421. $obj = new $foreign_object;
  422. return $obj->findOne(Array($remote_field => Array('=', $this->$local_field)));
  423. }
  424. /**
  425. * Belongs to Many
  426. *
  427. * Defines that this object is related to many other instances
  428. * of other classes throw a pivot table.
  429. *
  430. * Table Post = (id, name, content)
  431. * Table Tag = (id, name)
  432. * Table Post_Tag = (id, postid, tagid)
  433. *
  434. * This relation will be created in both classes
  435. *
  436. * @ctag $this->belongsToMany('foreign_object', 'pivot_table', 'local_in_pivot', 'remote_in_pivot');
  437. * @ctag $this->belongsToMany('foreign_object', 'pivot_table', 'local_in_pivot', 'remote_in_pivot', $remote_filter = Array());
  438. * @ctag $this->belongsToMany('foreign_object', 'pivot_table', 'local_in_pivot', 'remote_in_pivot', $remote_filter = Array(), $remote_limit = Array());
  439. *
  440. * @param Object $foreign_object Instance of the remote class
  441. * @param string $pivot_table Name of the pivot table
  442. * @param int $local_in_pivot Name of field on the pivot in relation of the local class
  443. * @param int $remote_in_pivot Name of field on the pivot in relation of the remote class
  444. * @param Array $remote_filter Filters to the remote Array('id', Array('>', 50) )
  445. * @param Array $remote_limit Array( 'offset'=> 10, 'limit' => 10 )
  446. */
  447. protected function belongsToMany($foreign_object, $pivot_table, $local_in_pivot, $remote_in_pivot, $remote_filter = Array(), $remote_limit = Array()) {
  448. $obj = new $foreign_object;
  449. $limits_sql = '';
  450. foreach ($remote_limit as $key => $value) {
  451. $limits_sql .= "$key $value ";
  452. }
  453. $sql = "SELECT $remote_in_pivot FROM {$pivot_table} WHERE $local_in_pivot = $this->id $limits_sql";
  454. $relations = DBInstance::query($sql, Array(), static::_connectionName);
  455. $ids = Array();
  456. foreach ($relations as $relation) {
  457. $ids[] = $relation->$remote_in_pivot;
  458. }
  459. if (empty($ids)) {
  460. return Array();
  461. }
  462. return $obj->findMany(array_merge(Array('id' => Array('IN', $ids)), $remote_filter), Array('*'), $remote_limit);
  463. }
  464. /**
  465. * Belongs to Many Extended
  466. *
  467. * Defines that this object is related to many other instances
  468. * of other classes throw a pivot table.
  469. * This relation will bring the pivot table with the elements inside
  470. *
  471. * Table Post = (id, name, content)
  472. * Table Tag = (id, name)
  473. * Table Post_Tag = (id, postid, tagid)
  474. *
  475. * @ctag $this->belongsToManyExtended('foreign_object', 'pivot_table', 'local_in_pivot', 'remote_in_pivot');
  476. * @ctag $this->belongsToManyExtended('foreign_object', 'pivot_table', 'local_in_pivot', 'remote_in_pivot', $remote_filter = Array());
  477. * @ctag $this->belongsToManyExtended('foreign_object', 'pivot_table', 'local_in_pivot', 'remote_in_pivot', $remote_filter = Array(), $pivot_limits = Array());
  478. *
  479. * This relation will be created in both classes
  480. *
  481. * @param Object $foreign_object Instance of the remote class
  482. * @param string $pivot_table Name of the pivot table
  483. * @param int $local_in_pivot Name of field on the pivot in relation of the local class
  484. * @param int $remote_in_pivot Name of field on the pivot in relation of the remote class
  485. * @param Array $remote_filter Filters to the remote Array('id', Array('>', 50) )
  486. * @param Array $pivot_limits Array( 'offset'=> 10, 'limit' => 10 )
  487. */
  488. protected function belongsToManyExtended($foreign_object, $pivot_table, $local_in_pivot, $remote_in_pivot, $remote_filter = Array(), $pivot_limits = Array()) {
  489. $obj = new $foreign_object;
  490. $limits_sql = '';
  491. foreach ($pivot_limits as $key => $value) {
  492. $limits_sql .= "$key $value ";
  493. }
  494. $sql = "SELECT * FROM $pivot_table WHERE $local_in_pivot = $this->id $limits_sql";
  495. $relations = DBInstance::query($sql, Array(), static::_connectionName);
  496. $objects = Array();
  497. if (empty($relations)) {
  498. return Array();
  499. }
  500. foreach ($relations as $relation) {
  501. $relation->child_element = $obj->findOne(array_merge(Array("id" => Array("=", $relation->$remote_in_pivot)), $remote_filter));
  502. $objects[] = $relation;
  503. }
  504. if (empty($objects)) {
  505. return Array();
  506. }
  507. return $objects;
  508. }
  509. }