Entity.php 18 KB

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