Entity.class.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. <?php
  2. require_once __DIR__.'/../constant.php';
  3. require_once(__ROOT__.'class'.SLASH.'Database.class.php');
  4. /**
  5. @version 2
  6. **/
  7. class Entity
  8. {
  9. public $debug = false,$pdo = null;
  10. public $created,$updated,$creator,$updater,$joins;
  11. public static $lastError = '';
  12. public static $lastResult = '';
  13. public static $lastQuery = '';
  14. const ACTIVE = 'published';
  15. const INACTIVE = 'deleted';
  16. public function __construct()
  17. {
  18. if (!isset($this->TABLE_NAME)) {
  19. $this->TABLE_NAME = strtolower(get_called_class());
  20. }
  21. $this->connect();
  22. $this->fields['created'] = 'datetime';
  23. $this->fields['updated'] = 'datetime';
  24. $this->fields['updater'] = 'string';
  25. $this->fields['creator'] = 'string';
  26. $this->joins = array();
  27. $this->created = time();
  28. global $myUser;
  29. if(is_object($myUser) && $myUser->login!='') $this->creator = $myUser->login;
  30. }
  31. public function connect()
  32. {
  33. $this->pdo = Database::instance();
  34. }
  35. public function __toString()
  36. {
  37. foreach ($this->toArray() as $key => $value) {
  38. echo $key.' : '.$value.','.PHP_EOL;
  39. }
  40. }
  41. public static function debug()
  42. {
  43. return array(self::$lastQuery, self::$lastError, self::$lastResult);
  44. }
  45. public function __sleep()
  46. {
  47. return array_keys($this->toArray());
  48. }
  49. public function __wakeup()
  50. {
  51. $this->connect();
  52. }
  53. //Comparaison de deux instances d'une même entité, retourne les champs ayant changés uniquement
  54. public static function compare($obj1,$obj2){
  55. $class = get_called_class();
  56. $instance = new $class();
  57. $compare = array();
  58. foreach ($obj1->fields as $field => $type) {
  59. if($field == 'updated' || $field == 'updater') continue;
  60. if($obj1->$field != $obj2->$field){
  61. if($type=='int' && (($obj1->$field==0 && $obj2->$field =='') || ($obj2->$field=='' && $obj1->$field ==0)) ) continue;
  62. $compare[] = array('field'=>$field,'value1'=>$obj1->$field,'value2'=>$obj2->$field);
  63. }
  64. }
  65. return $compare;
  66. }
  67. public function toArray($decoded=false) {
  68. $fields = array();
  69. foreach ($this->fields as $field => $type) {
  70. $fields[$field] = $decoded ? html_entity_decode($this->$field) : $this->$field;
  71. }
  72. return $fields;
  73. }
  74. public function toText() {
  75. $text = array();
  76. foreach ($this->fields as $field => $type) {
  77. $value = is_object($this->$field) ? '[object]' : $this->$field;
  78. $text[]= $field.' = '.$value;
  79. }
  80. return implode(', ',$text);
  81. }
  82. public function fromArray($array) {
  83. foreach ($array as $field => $value) {
  84. $this->$field = $value;
  85. }
  86. }
  87. public function sgbdType($type) {
  88. $sgbd = BASE_SGBD;
  89. $types = $sgbd::types();
  90. return isset($types[$type]) ? $types[$type] : $types['default'];
  91. }
  92. public function closeDatabase() {
  93. // $this->close();
  94. }
  95. //Génère un slug unique pour l'element de liste utilisable dans le code
  96. // $label => string du label à slugifier
  97. // $column => la colonne en base où checker les slugs existants
  98. public static function generateSlug($label, $column){
  99. $slug = slugify($label);
  100. $class = get_called_class();
  101. $item = new $class();
  102. if(!array_key_exists($column, $item->fields)) return;
  103. $params = array_key_exists('state', $item->fields) ? array('state'=>$class::ACTIVE) : array();
  104. $i='';
  105. while($class::rowCount(array_merge(array($column=>$slug.$i), $params)) > 0 ) $i++;
  106. return $i==''?$slug:$slug.'-'.$i;
  107. }
  108. public static function tableName()
  109. {
  110. $class = get_called_class();
  111. $instance = new $class();
  112. return ENTITY_PREFIX.$instance->TABLE_NAME;
  113. }
  114. // GESTION SQL
  115. /**
  116. * Verifie l'existence de la table en base de donnée.
  117. *
  118. * @author Valentin CARRUESCO
  119. *
  120. * @category manipulation SQL
  121. *
  122. * @param <String> créé la table si elle n'existe pas
  123. *
  124. * @return true si la table existe, false dans le cas contraire
  125. */
  126. public static function checkTable($autocreate = false)
  127. {
  128. $class = get_called_class();
  129. $instance = new $class();
  130. $query = 'SELECT count(*) as numRows FROM sqlite_master WHERE type="table" AND name=?';
  131. $statement = $instance->customQuery($query, array($instance->tableName()));
  132. if ($statement != false) {
  133. $statement = $statement->fetchArray();
  134. if ($statement['numRows'] == 1) {
  135. $return = true;
  136. }
  137. }
  138. if ($autocreate && !$return) self::create();
  139. return $return;
  140. }
  141. public static function install($classDirectory)
  142. {
  143. foreach (glob($classDirectory.SLASH.'*.class.php') as $file) {
  144. $infos = explode('.', basename($file));
  145. $class = array_shift($infos);
  146. require_once($classDirectory.SLASH.$class.'.class.php');
  147. $reflection = new ReflectionClass($class);
  148. if (!class_exists($class) || !method_exists($class, 'create') || $class == get_class() || $reflection->isAbstract()) {
  149. continue;
  150. }
  151. $class::create();
  152. }
  153. }
  154. public static function uninstall($classDirectory)
  155. {
  156. foreach (glob($classDirectory.SLASH.'*.class.php') as $file) {
  157. $infos = explode('.', basename($file));
  158. $class = array_shift($infos);
  159. require_once($classDirectory.SLASH.$class.'.class.php');
  160. $reflection = new ReflectionClass($class);
  161. if (!class_exists($class) || !method_exists($class, 'drop') || $class == get_class() || $reflection->isAbstract()) continue;
  162. $class::drop();
  163. }
  164. }
  165. /**
  166. * Methode de vidage de l'entité.
  167. *
  168. * @author Valentin CARRUESCO
  169. * @category manipulation SQL
  170. * @return Aucun retour
  171. */
  172. public static function truncate()
  173. {
  174. $class = get_called_class();
  175. $instance = new $class();
  176. $sgbd = BASE_SGBD;
  177. $sql = $sgbd::truncate();
  178. $query = Entity::render($sql,array(
  179. 'table' => $instance->tableName()
  180. ));
  181. $instance->customExecute($query);
  182. }
  183. /**
  184. * Methode de creation de l'entité.
  185. *
  186. * @author Valentin CARRUESCO
  187. * @category manipulation SQL
  188. *
  189. * @return Aucun retour
  190. */
  191. public static function create()
  192. {
  193. $class = get_called_class();
  194. $instance = new $class();
  195. $fields = array();
  196. foreach ($instance->fields as $field => $type)
  197. $fields[$field] = $instance->sgbdType($type);
  198. $sgbd = BASE_SGBD;
  199. $sql = $sgbd::create();
  200. $query = Entity::render($sql,array(
  201. 'table' => $instance->tableName(),
  202. 'fields' => $fields
  203. ));
  204. $instance->customExecute($query);
  205. }
  206. public static function drop()
  207. {
  208. $class = get_called_class();
  209. $instance = new $class();
  210. $sgbd = BASE_SGBD;
  211. $sql = $sgbd::drop();
  212. $query = Entity::render($sql,array(
  213. 'table' => $instance->tableName()
  214. ));
  215. $instance->customExecute($query);
  216. }
  217. /**
  218. * Methode d'insertion ou de modifications d'elements de l'entité.
  219. *
  220. * @author Valentin CARRUESCO
  221. *
  222. * @category manipulation SQL
  223. *
  224. * @param Aucun
  225. *
  226. * @return Aucun retour
  227. */
  228. public function save()
  229. {
  230. $this->updated = time();
  231. global $myUser;
  232. if(is_object($myUser) && $myUser->login!='') $this->updater = $myUser->login;
  233. $data = array();
  234. $numericType = array('object', 'timestamp', 'datetime', 'date', 'int', 'float', 'decimal');
  235. $stringType = array('string', 'longstring', 'default');
  236. if (isset($this->id) && $this->id > 0) {
  237. $fields = array();
  238. $i = 0;
  239. foreach ($this->fields as $field => $type) {
  240. if ($type == 'key') continue;
  241. $data[':'.$i] = $this->{$field};
  242. if($type=='boolean') $data[':'.$i] = $data[':'.$i] ? 1:0;
  243. //if(in_array($type, $numericType) && !$data[':'.$i]) $data[':'.$i] = 0;
  244. //if(in_array($type, $stringType) && !$data[':'.$i]) $data[':'.$i] = '';
  245. $fields[$field] = ':'.$i;
  246. $i++;
  247. }
  248. $data[':id'] = $this->id;
  249. $sgbd = BASE_SGBD;
  250. $sql = $sgbd::update();
  251. $query = self::render($sql,array(
  252. 'table' => $this->tableName(),
  253. 'fields' => $fields,
  254. 'filters' => array('id'=>':id'),
  255. ));
  256. } else {
  257. $fields = array();
  258. $i = 0;
  259. foreach ($this->fields as $field => $type) {
  260. if ($type == 'key') continue;
  261. $data[':'.$i] = $this->{$field};
  262. if($type=='boolean') $data[':'.$i] = $data[':'.$i] ? 1:0;
  263. //if(in_array($type, $numericType) && !$data[':'.$i]) $data[':'.$i] = 0;
  264. //if(in_array($type, $stringType) && !$data[':'.$i]) $data[':'.$i] = '';
  265. $fields[$field] = ':'.$i;
  266. $i++;
  267. }
  268. $sgbd = BASE_SGBD;
  269. $sql = $sgbd::insert();
  270. $query = self::render($sql,array(
  271. 'table' => $this->tableName(),
  272. 'fields' => $fields
  273. ));
  274. }
  275. $this->customExecute($query, $data);
  276. $this->id = !isset($this->id) || !is_numeric($this->id) ? $this->pdo->lastInsertId() : $this->id;
  277. }
  278. /**
  279. * Méthode de modification d'éléments de l'entité.
  280. *
  281. * @author Valentin CARRUESCO
  282. *
  283. * @category manipulation SQL
  284. *
  285. * @param <Array> $colonnes=>$valeurs
  286. * @param <Array> $colonnes (WHERE) =>$valeurs (WHERE)
  287. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  288. *
  289. * @return Aucun retour
  290. */
  291. public static function change($columns, $columns2 = array(), $operation = '=')
  292. {
  293. $class = get_called_class();
  294. $instance = new $class();
  295. $fields = array();
  296. $i = 0;
  297. foreach ($columns as $field => $value) {
  298. $data[':'.$i] = $value;
  299. $fields[$field] = ':'.$i;
  300. $i++;
  301. }
  302. $filters = array();
  303. $i = 0;
  304. foreach ($columns2 as $field => $value) {
  305. $data[':_'.$i] = $value;
  306. $filters[$field] = ':_'.$i;
  307. $i++;
  308. }
  309. $sgbd = BASE_SGBD;
  310. $sql = $sgbd::update();
  311. $query = Entity::render($sql,array(
  312. 'table' => $instance->tableName(),
  313. 'fields' => $fields,
  314. 'filters' => $filters,
  315. ));
  316. $instance->customExecute($query, $data);
  317. }
  318. /**
  319. * Méthode de selection de tous les elements de l'entité.
  320. *
  321. * @author Valentin CARRUESCO
  322. *
  323. * @category manipulation SQL
  324. *
  325. * @param <String> $ordre=null
  326. * @param <String> $limite=null
  327. *
  328. * @return <Array<Entity>> $Entity
  329. */
  330. public static function populate($order = null, $limit = null,$selColumn = array('*'),$joins = 0)
  331. {
  332. $results = self::loadAll(array(), $order, $limit,$selColumn,$joins);
  333. return $results;
  334. }
  335. /**
  336. * Méthode de selection multiple d'elements de l'entité.
  337. *
  338. * @author Valentin CARRUESCO
  339. *
  340. * @category manipulation SQL
  341. *
  342. * @param <Array> $colonnes (WHERE)
  343. * @param <Array> $valeurs (WHERE)
  344. * @param <String> $ordre=null
  345. * @param <String> $limite=null
  346. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  347. *
  348. * @return <Array<Entity>> $Entity
  349. */
  350. public static function loadAll($columns = array(), $order = null, $limit = null, $selColumn = array('*'),$joins = 0)
  351. {
  352. $values = array();
  353. $i=0;
  354. foreach($columns as $key=>$value){
  355. //Gestion du IN
  356. if(strlen($key)>=3 && substr($key,-3) == ':IN'){
  357. $columns[$key] = array();
  358. foreach (explode(',',$value) as $v2) {
  359. $tag = ':'.$i;
  360. $columns[$key][]= $tag;
  361. $values[$tag] = $v2;
  362. $i++;
  363. }
  364. $columns[$key] = implode(',',$columns[$key]);
  365. //Gestion des opérateurs classiques
  366. } else {
  367. $tag = ':'.$i;
  368. $columns[$key] = $tag;
  369. $values[$tag] = $value;
  370. $i++;
  371. }
  372. }
  373. $class = get_called_class();
  374. $instance = new $class();
  375. $data = array(
  376. 'table' => $instance->tableName(),
  377. 'selected' => $selColumn,
  378. 'limit' => !isset($limit) || count($limit) == 0 ? null: $limit,
  379. 'orderby' => !isset($order) || count($order) == 0 ? null: $order,
  380. 'filter' => !isset($columns) || count($columns) == 0 ? null: $columns
  381. );
  382. $data['joins'] = array();
  383. if($joins!=0){
  384. foreach ($data['selected'] as $k=>$column) {
  385. $data['selected'][$k] = $instance->tableName().'.'.$column;
  386. }
  387. $data = self::recursiveJoining($instance,$data,$joins);
  388. }
  389. $sgbd = BASE_SGBD;
  390. $sql = $sgbd::select();
  391. $sql = Entity::render($sql,$data);
  392. return $instance->customQuery($sql, $values, true,$joins);
  393. }
  394. /**
  395. * Méthode privée de gestion du join récursif sur les objets liés
  396. *
  397. * @author Valentin CARRUESCO
  398. *
  399. * @category manipulation SQL
  400. *
  401. * @param <Object> $instance $instance de départ
  402. * @param <Array> $data Tableau de construction de la requete via render()
  403. * @param <Int> $iterations Nombre d'iteration réecurive maximum
  404. *
  405. * @return <Array> $data
  406. */
  407. private static function recursiveJoining($instance,$data,$iterations){
  408. if($iterations==0) return $data;
  409. $iterations--;
  410. if(isset($instance->links)){
  411. foreach ($instance->links as $field => $className) {
  412. $field2 = 'id';
  413. $classField = explode('.',$className);
  414. if(isset($classField[1]))
  415. list($className,$field2) = $classField;
  416. $joinInstance = new $className();
  417. foreach ($joinInstance->fields as $key=>$type) {
  418. $data['selected'][] = $className::tableName().'.'.$key.' as '.$className::tableName().'_join_'.$key;
  419. }
  420. $data['joins'][] = array(
  421. 'jointable1' => $instance::tableName(),
  422. 'jointable2' => $className::tableName(),
  423. 'field1' => $field,
  424. 'field2' => $field2
  425. );
  426. $data = self::recursiveJoining($joinInstance,$data,$iterations);
  427. }
  428. }
  429. return $data;
  430. }
  431. /**
  432. * Methode de comptage des éléments de l'entité.
  433. *
  434. * @author Valentin CARRUESCO
  435. *
  436. * @category manipulation SQL
  437. * @return<Integer> nombre de ligne dans l'entité'
  438. */
  439. public static function rowCount($columns = null) {
  440. $values = array();
  441. $i=0;
  442. foreach($columns as $key=>$value){
  443. $tag = ':'.$i;
  444. $columns[$key] = $tag;
  445. $values[$tag] = $value;
  446. $i++;
  447. }
  448. $class = get_called_class();
  449. $instance = new $class();
  450. $data = array(
  451. 'table' => $class::tableName(),
  452. 'selected' => 'id' ,
  453. 'filter' => count($columns) == 0 ? null: $columns
  454. );
  455. $sgbd = BASE_SGBD;
  456. $sql = $sgbd::count();
  457. $execQuery = $instance->customQuery(Entity::render($sql,$data), $values);
  458. $row = $execQuery->fetch();
  459. return $row['number'];
  460. }
  461. public static function loadAllOnlyColumn($selColumn, $columns, $order = null, $limit = null)
  462. {
  463. $objects = self::loadAll($columns, $order, $limit, $operation, $selColumn);
  464. if (count($objects) == 0) {
  465. $objects = array();
  466. }
  467. return $objects;
  468. }
  469. /**
  470. * Méthode de selection unique d'élements de l'entité.
  471. *
  472. * @author Valentin CARRUESCO
  473. *
  474. * @category manipulation SQL
  475. *
  476. * @param <Array> $colonnes (WHERE)
  477. * @param <Array> $valeurs (WHERE)
  478. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  479. *
  480. * @return <Entity> $Entity ou false si aucun objet n'est trouvé en base
  481. */
  482. public static function load($columns,$joins =0) {
  483. $objects = self::loadAll($columns, null, array('1'),array('*'),$joins);
  484. if (!isset($objects[0])) $objects[0] = false;
  485. return $objects[0];
  486. }
  487. /**
  488. * Méthode de selection unique d'élements de l'entité.
  489. *
  490. * @author Valentin CARRUESCO
  491. *
  492. * @category manipulation SQL
  493. *
  494. * @param <Array> $colonnes (WHERE)
  495. * @param <Array> $valeurs (WHERE)
  496. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  497. *
  498. * @return <Entity> $Entity ou false si aucun objet n'est trouvé en base
  499. */
  500. public static function getById($id,$joins =0 ) {
  501. return self::load(array('id' => $id),$joins);
  502. }
  503. public static function render($sql,$data=array()) {
  504. //loop
  505. $sql = preg_replace_callback('/{{\:([^\/\:\?}]*)}}(.*?){{\/\:[^\/\:\?}]*}}/',function($matches) use ($data) {
  506. $tag = $matches[1];
  507. $sqlTpl = $matches[2];
  508. $sql = '';
  509. if(isset($data[$tag])){
  510. $i = 0;
  511. $values = $data[$tag];
  512. if($tag =='joins'){
  513. //joins
  514. foreach($values as $join){
  515. $occurence = $sqlTpl;
  516. foreach($join as $key=>$value){
  517. $occurence = str_replace(array('{{'.$key.'}}'),array($value),$occurence);
  518. }
  519. $sql.= $occurence;
  520. }
  521. } else {
  522. //filters
  523. foreach($values as $key=>$value){
  524. $i++;
  525. $last = $i == count($values);
  526. $operator = isset($data['operator']) ? $data['operator'][0] : '=';
  527. $postoperator = isset($data['postoperator']) ? $data['postoperator'][0] : '';
  528. if(strpos($key,':')!==false){
  529. $infos = explode(':',$key);
  530. $key = $infos[0];
  531. $operator = $infos[1];
  532. if($operator=='IN'){
  533. $operator = 'IN(';
  534. $postoperator = ')';
  535. }
  536. }
  537. $occurence = str_replace(array('{{key}}','{{value}}','{{operator}}','{{postoperator}}'),array($key,$value,$operator,$postoperator),$sqlTpl);
  538. $occurence = preg_replace_callback('/{{\;}}(.*?){{\/\;}}/',function($matches) use ($last){
  539. return $last? '': $matches[1];
  540. },$occurence);
  541. $sql.= $occurence;
  542. }
  543. }
  544. return $sql;
  545. }
  546. return '';
  547. },$sql);
  548. //conditions
  549. $sql = preg_replace_callback('/{{\?([^\/\:\?}]*)}}(.*?){{\/\?[^\/\:\?}]*}}/',function($matches) use ($data) {
  550. $key = $matches[1];
  551. $sql = $matches[2];
  552. return !isset($data[$key]) || (is_array($data[$key]) && count($data[$key])==0) ?'':$sql;
  553. },$sql);
  554. //simple vars
  555. $sql = preg_replace_callback('/{{([^\/\:\;\?}]*)}}/',function($matches) use ($data) {
  556. $key = $matches[1];
  557. return isset($data[$key])?$data[$key]:'';
  558. },$sql);
  559. return $sql;
  560. }
  561. /**
  562. * Methode de définition de l'éxistence d'un moins un des éléments spécifiés en base.
  563. *
  564. * @author Valentin CARRUESCO
  565. *
  566. * @category manipulation SQL
  567. * @return<boolean> existe (true) ou non (false)
  568. */
  569. public static function exist($columns = null) {
  570. $result = self::rowCount($columns);
  571. return $result != 0;
  572. }
  573. public static function deleteById($id) {
  574. self::delete(array('id' => $id));
  575. }
  576. /**
  577. * Méthode de Suppression d'elements de l'entité.
  578. *
  579. * @author Valentin CARRUESCO
  580. *
  581. * @category manipulation SQL
  582. *
  583. * @param <Array> $colonnes (WHERE)
  584. * @param <Array> $valeurs (WHERE)
  585. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  586. *
  587. * @return Aucun retour
  588. */
  589. public static function delete($columns, $limit = array()) {
  590. $values = array();
  591. $i=0;
  592. foreach($columns as $key=>$value){
  593. $tag = ':'.$i;
  594. $columns[$key] = $tag;
  595. $values[$tag] = $value;
  596. $i++;
  597. }
  598. $class = get_called_class();
  599. $instance = new $class();
  600. $data = array(
  601. 'table' => $class::tableName(),
  602. 'limit' => count($limit) == 0 ? null: $limit,
  603. 'filter' => count($columns) == 0 ? null: $columns
  604. );
  605. $sgbd = BASE_SGBD;
  606. $sql = $sgbd::delete();
  607. return $instance->customExecute(Entity::render($sql,$data), $values);
  608. }
  609. public static function paginate($itemPerPage,$currentPage,&$query,$data){
  610. global $_;
  611. $class = get_called_class();
  612. $obj = new $class();
  613. $keys = array_keys($obj->fields, 'key');
  614. $key = count($keys) == 1 ? $keys[0] : 'id';
  615. $queryNumber = $query;
  616. $queryNumber = preg_replace("/(SELECT.+[\n|\t]*)FROM[\s\t\r\n]/iU", 'SELECT '.$obj->tableName().'.'.$key.' FROM ',$queryNumber);
  617. $queryNumber = $class::staticQuery('SELECT COUNT(*) FROM ('.$queryNumber.') number',$data)->fetch();
  618. $number = $queryNumber[0];
  619. $pageNumber = $number / $itemPerPage;
  620. if($currentPage > $pageNumber) $currentPage = 0;
  621. $limit = ' LIMIT '.($currentPage*$itemPerPage).','.$itemPerPage;
  622. $query .= $limit;
  623. return array(
  624. 'pages' => $pageNumber,
  625. 'current' => $currentPage
  626. );
  627. }
  628. public function customExecute($query, $data = array()) {
  629. self::$lastQuery = $query;
  630. try {
  631. if(BASE_DEBUG) self::logFile($query.' :: '.json_encode($data, JSON_UNESCAPED_UNICODE));
  632. $stm = $this->pdo->prepare($query);
  633. $stm->execute($data);
  634. } catch (Exception $e) {
  635. self::$lastError = $this->pdo->errorInfo();
  636. //Log l'erreur uniquement si elle ne proviens pas elle même de Log (evite les mysql gone away)
  637. if(get_class($this) !='Log')
  638. Log::put("[SQL ERROR] - ".$e->getMessage().' - '.$e->getLine().' - Requete : '.$query.' - Données : '.json_encode($data,JSON_UNESCAPED_UNICODE));
  639. if(BASE_DEBUG) self::logFile( "Erreur : ".$e->getMessage());
  640. throw new Exception($e->getMessage().' - '.$e->getLine().' : '.$query.' - '.json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
  641. }
  642. }
  643. public static function provide($parameter = 'id',$join=0){
  644. global $_;
  645. $class = get_called_class();
  646. return !empty($_[$parameter]) ? $class::getById($_[$parameter],$join) : new $class() ;
  647. }
  648. public static function staticQuery($query, $data = array(), $fill = false,$joins = 0) {
  649. $class = get_called_class();
  650. $instance = new $class();
  651. return $instance->customQuery($query, $data, $fill,$joins);
  652. }
  653. public function customQuery($query, $data = array(), $fill = false,$joins = 0) {
  654. $query = str_replace('{{table}}', '`'.$this->tableName().'`', $query);
  655. self::$lastQuery = $query;
  656. try{
  657. if(BASE_DEBUG) self::logFile($query.' :: '.json_encode($data, JSON_UNESCAPED_UNICODE));
  658. $results = $this->pdo->prepare($query);
  659. $results->execute($data);
  660. if (!$results) throw new Exception(json_encode($this->pdo->errorInfo()));
  661. }catch(Exception $e){
  662. self::$lastError = $e->getMessage();
  663. //echo "[SQL ERROR] - Erreur : ".$e->getMessage().' - Requete : '.$query.' - Données : '.json_encode($data);
  664. Log::put("[SQL ERROR] - Erreur : ".$e->getMessage().' - Requete : '.$query.' - Données : '.json_encode($data, JSON_UNESCAPED_UNICODE));
  665. if(BASE_DEBUG) self::logFile( "Erreur : ".$e->getMessage());
  666. throw $e;
  667. }
  668. if (!$fill) return $results;
  669. $class = get_class($this);
  670. $objects = array();
  671. $results = $results->fetchAll();
  672. self::$lastResult = $results;
  673. foreach ($results as $queryReturn) {
  674. $object = new $class();
  675. foreach ($this->fields as $field => $type) {
  676. if (isset($queryReturn[$field])) {
  677. $object->{$field} = $queryReturn[$field];
  678. }
  679. }
  680. if($joins>0) $object = self::recursiveJoiningFill($object,$queryReturn,$joins);
  681. $objects[] = $object;
  682. unset($object);
  683. }
  684. return $objects == null ? array() : $objects;
  685. }
  686. private static function recursiveJoiningFill($object,$queryReturn,$iterations){
  687. if($iterations == 0) return $object;
  688. $iterations--;
  689. if(isset($object->links)){
  690. foreach ($object->links as $link=>$classLink) {
  691. $classField = explode('.',$classLink);
  692. if(isset($classField[1]))
  693. $classLink = $classField[0];
  694. $instanceLink = new $classLink();
  695. foreach ($instanceLink->fields as $field => $type) {
  696. if (isset($queryReturn[$classLink::tableName().'_join_'.$field]))
  697. $instanceLink->{$field} = $queryReturn[$classLink::tableName().'_join_'.$field];
  698. }
  699. $instanceLink = self::recursiveJoiningFill($instanceLink,$queryReturn,$iterations);
  700. $object->joins[$link] = $instanceLink;
  701. }
  702. }
  703. return $object;
  704. }
  705. /**
  706. * Récupere l'objet join ex : $contact->join("adress")->street; --> récupere l'attribut street de la class Adress dont l'id est spécifié dans la colonne adress de la class Contact
  707. * Nb : cette méthode ne fonctionne que si vous avez placé le parametre joins > 0 dans la méthode LoadALl
  708. * Nb : cette méthode ne fonctionne que si vous avez précisé le lien entre Contact et Adress dans la classe Contact via :
  709. protected $links = array(
  710. 'address' => 'Address'
  711. );
  712. *
  713. * @author Valentin CARRUESCO
  714. * @category manipulation SQL
  715. *
  716. * @param <Array> $colonnes (WHERE)
  717. * @param <Array> $valeurs (WHERE)
  718. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  719. *
  720. * @return Aucun retour
  721. */
  722. public function join($field){
  723. return isset($this->joins[$field])?$this->joins[$field]:'';
  724. }
  725. public static function logFile($msg){
  726. file_put_contents(__DIR__.SLASH.'..'.SLASH.'sql.debug.sql', date('H:i:s').' | '.$msg.PHP_EOL,FILE_APPEND);
  727. }
  728. /*
  729. public function __get($name) {
  730. $pos = strpos($name, '_object');
  731. if ($pos !== false) {
  732. $field = strtolower(substr($name, 0, $pos));
  733. if (array_key_exists($field, $this->fields)) {
  734. $class = ucfirst($field);
  735. return $class::getById($this->{$field});
  736. }
  737. }
  738. throw new Exception('Attribut '.get_class($this)."->$name non existant");
  739. }
  740. */
  741. public static function log_executed_query($string, $data) {
  742. $indexed=$data==array_values($data);
  743. foreach($data as $k=>$v) {
  744. if(is_string($v)) $v="'$v'";
  745. if($indexed) $string=preg_replace('/\?/',$v,$string,1);
  746. else $string=str_replace(":$k",$v,$string);
  747. }
  748. self::logFile($string);
  749. }
  750. }