Entity.class.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. <?php
  2. require_once __DIR__.'/../constant.php';
  3. require_once(__ROOT__.'class'.SLASH.'Database.class.php');
  4. require_once(__ROOT__.'connector'.SLASH.'Oracle.class.php');
  5. require_once(__ROOT__.'connector'.SLASH.'Mysql.class.php');
  6. require_once(__ROOT__.'connector'.SLASH.'Sqlite.class.php');
  7. require_once(__ROOT__.'connector'.SLASH.'SqlServer.class.php');
  8. /**
  9. * Classe de gestion ORM
  10. * @version 2
  11. * @category sql
  12. * @author Valentin CARRUESCO
  13. **/
  14. class Entity {
  15. public $pdo = null,$baseUid= 'local';
  16. public $created,$updated,$creator,$updater,$joins,$entityLabel = '';
  17. public $links = array();
  18. public $foreignColumns = array();
  19. public $fieldMapping = array();
  20. const ACTIVE = 'published';
  21. const INACTIVE = 'deleted';
  22. public function __construct() {
  23. if (!isset($this->TABLE_NAME)) $this->TABLE_NAME = strtolower(get_called_class());
  24. $this->connect();
  25. $this->fields['created'] = array('type'=>'date', 'label' => 'Date de création');
  26. $this->fields['updated'] = array('type'=>'date', 'label' => 'Date de modification');
  27. $this->fields['updater'] = array('type'=>'text', 'label' => 'Modificateur');
  28. $this->fields['creator'] = array('type'=>'text', 'label' => 'Créateur');
  29. $this->joins = array();
  30. $this->created = time();
  31. $this->fieldMapping = $this->field_mapping($this->fields);
  32. global $myUser;
  33. if(is_object($myUser) && $myUser->login!='') $this->creator = $myUser->login;
  34. }
  35. public function field_mapping($fields = array()){
  36. $fieldMapping = array();
  37. $fieldTypes = FieldType::available();
  38. foreach($fields as $field => $type) {
  39. if(!is_array($type)) $type = array('type'=>$type,'column'=>$field);
  40. if(!isset($type['column'])) $type['column'] = $field;
  41. if(isset($type['link'])) $this->links[$type['column']] = $type['link'];
  42. $type['fieldtype'] = $type['type'];
  43. //conversion des field type en sql type
  44. if(isset($fieldTypes[$type['type']]))
  45. $type['type'] = $fieldTypes[$type['type']]->sqlType;
  46. $fieldMapping[$field] = $type;
  47. }
  48. return $fieldMapping;
  49. }
  50. //Connexion à la base
  51. public function connect() {
  52. $this->pdo = Database::instance($this->baseUid);
  53. global $databases_credentials;
  54. $this->connector = $databases_credentials[$this->baseUid]['connector'];
  55. }
  56. public function __toString() {
  57. foreach ($this->toArray() as $key => $value) {
  58. echo $key.' : '.$value.','.PHP_EOL;
  59. }
  60. }
  61. public function __sleep() {
  62. return array_keys($this->toArray());
  63. }
  64. public function __wakeup() {
  65. $this->connect();
  66. }
  67. //Comparaison de deux instances d'une même entité, retourne les champs ayant changés uniquement
  68. public static function compare($obj1,$obj2,$ignore=array()){
  69. $class = get_called_class();
  70. $compare = array();
  71. foreach ($obj1->fields as $field => $type) {
  72. if($field == 'updated' || $field == 'updater' || in_array($field, $ignore)) continue;
  73. if($obj1->$field != $obj2->$field){
  74. if($type=='int' && (($obj1->$field==0 && $obj2->$field =='') || ($obj2->$field=='' && $obj1->$field ==0)) ) continue;
  75. $compare[] = array('field'=>$field,'value1'=>$obj1->$field,'value2'=>$obj2->$field);
  76. }
  77. }
  78. return $compare;
  79. }
  80. public static function fields($onlyKeys = true){
  81. $class = get_called_class();
  82. $instance = new $class();
  83. if($onlyKeys) return array_keys($instance->fields);
  84. return $instance->fieldMapping;
  85. }
  86. public function toArray($decoded=false) {
  87. $fields = array();
  88. foreach ($this->fields as $field => $type) {
  89. $fields[$field] = $decoded ? html_entity_decode($this->$field) : $this->$field;
  90. }
  91. return $fields;
  92. }
  93. public function toText() {
  94. $text = array();
  95. foreach ($this->fields as $field => $type) {
  96. $value = is_object($this->$field) ? '[object]' : $this->$field;
  97. $text[]= $field.' = '.$value;
  98. }
  99. return implode(', ',$text);
  100. }
  101. public function fromArray($array) {
  102. foreach ($array as $field => $value) {
  103. $this->$field = $value;
  104. }
  105. }
  106. public function closeDatabase() {
  107. // $this->close();
  108. }
  109. //Libellé human readable de l'entité
  110. public static function entityLabel() {
  111. $class = get_called_class();
  112. $instance = new $class();
  113. return !empty($instance->entityLabel) ? $instance->entityLabel : $class;
  114. }
  115. public static function tableName($escapeName = false,$instance = null) {
  116. global $databases_credentials;
  117. $class = get_called_class();
  118. if(!isset($instance)) $instance = new $class();
  119. $prefix = isset($databases_credentials[$instance->baseUid]['prefix']) ? $databases_credentials[$instance->baseUid]['prefix'] : '';
  120. $connector = $instance->connector;
  121. return $escapeName ? $connector::table_escape.$prefix.$instance->TABLE_NAME.$connector::table_escape : $prefix.$instance->TABLE_NAME;
  122. }
  123. // GESTION SQL
  124. /**
  125. * Verifie l'existence de la table en base de donnée.
  126. * @category manipulation SQL
  127. * @param <String> créé la table si elle n'existe pas
  128. * @return true si la table existe, false dans le cas contraire
  129. */
  130. public static function checkTable($autocreate = false) {
  131. $class = get_called_class();
  132. $instance = new $class();
  133. $query = 'SELECT count(*) as numRows FROM sqlite_master WHERE type="table" AND name=?';
  134. $statement = $instance->customQuery($query, array($class::tableName(false,$instance)));
  135. if ($statement != false) {
  136. $statement = $statement->fetchArray();
  137. if ($statement['numRows'] == 1) {
  138. $return = true;
  139. }
  140. }
  141. if ($autocreate && !$return) self::create();
  142. return $return;
  143. }
  144. public static function install($classDirectory) {
  145. foreach (glob($classDirectory.SLASH.'*.class.php') as $file) {
  146. $infos = explode('.', basename($file));
  147. $class = array_shift($infos);
  148. require_once($classDirectory.SLASH.$class.'.class.php');
  149. $reflection = new ReflectionClass($class);
  150. if (!class_exists($class) || !method_exists($class, 'create') || $class == get_class() || $reflection->isAbstract()) {
  151. continue;
  152. }
  153. $class::create();
  154. }
  155. }
  156. public static function uninstall($classDirectory) {
  157. foreach (glob($classDirectory.SLASH.'*.class.php') as $file) {
  158. $infos = explode('.', basename($file));
  159. $class = array_shift($infos);
  160. require_once($classDirectory.SLASH.$class.'.class.php');
  161. $reflection = new ReflectionClass($class);
  162. if (!class_exists($class) || !method_exists($class, 'drop') || $class == get_class() || $reflection->isAbstract()) continue;
  163. $class::drop();
  164. }
  165. }
  166. /**
  167. * Methode de vidage de l'entité.
  168. * @category manipulation SQL
  169. * @return Aucun retour
  170. */
  171. public static function truncate() {
  172. $class = get_called_class();
  173. $instance = new $class();
  174. $connector = $instance->connector;
  175. $sql = $connector::truncate();
  176. $query = Entity::render($sql,array(
  177. 'table' => $class::tableName(false,$instance),
  178. 'fieldMapping' => $instance->fieldMapping
  179. ));
  180. $instance->customQuery($query);
  181. }
  182. /**
  183. * Methode de creation de l'entité.
  184. * @category manipulation SQL
  185. * @return Aucun retour
  186. */
  187. public static function create() {
  188. $class = get_called_class();
  189. $instance = new $class();
  190. $fields = array();
  191. $connector = $instance->connector;
  192. $types = $connector::types();
  193. $fieldMapping = $instance->field_mapping($instance->fields);
  194. foreach ($instance->fields(false) as $slug => $field) {
  195. $fields[$slug] = isset($types[$field['type']]) ? $types[$field['type']] : $types['default'];
  196. }
  197. $sql = $connector::create();
  198. $query = Entity::render($sql,array(
  199. 'table' => $class::tableName(false,$instance),
  200. 'fields' => $fields,
  201. 'fieldMapping' => $instance->fieldMapping
  202. ));
  203. $instance->customQuery($query);
  204. if(isset($instance->indexes)) $instance->index($instance->indexes);
  205. }
  206. public static function drop() {
  207. $class = get_called_class();
  208. $instance = new $class();
  209. $connector = $instance->connector;
  210. $sql = $connector::drop();
  211. $query = Entity::render($sql,array(
  212. 'table' => $class::tableName(false,$instance),
  213. 'fieldMapping' => $instance->fieldMapping
  214. ));
  215. $instance->customQuery($query);
  216. if(isset($instance->indexes)) $instance->index($instance->indexes,false);
  217. }
  218. /**
  219. * Methode d'insertion ou de modifications d'elements de l'entité.
  220. * @category manipulation SQL
  221. * @param Aucun
  222. * @return Aucun retour
  223. */
  224. public function save() {
  225. global $myUser;
  226. $this->updated = time();
  227. if(is_object($myUser) && $myUser->login!='') $this->updater = $myUser->login;
  228. //update
  229. if (isset($this->id) && $this->id > 0) {
  230. $fields = array();
  231. foreach ($this->fields as $field => $type)
  232. $fields[$field] = $this->{$field};
  233. self::change($fields,array('id'=>$this->id));
  234. //insert
  235. } else {
  236. $connector = $this->connector;
  237. $data = array();
  238. $fields = array();
  239. $i = 0;
  240. foreach ($this->fields as $field => $type) {
  241. if((is_array($type) && $type['type'] == 'key') || $type == 'key') continue;
  242. $data[':'.$i] = $this->{$field};
  243. if((is_array($type) && $type['type'] == 'boolean') || $type == 'boolean') $data[':'.$i] = $data[':'.$i] ? 1 : 0;
  244. $fields[$field] = ':'.$i;
  245. $i++;
  246. }
  247. $sql = $connector::insert();
  248. $query = self::render($sql,array(
  249. 'table' => $this->tableName(false,$this),
  250. 'fields' => $fields,
  251. 'fieldMapping' => $this->fieldMapping
  252. ));
  253. $this->customQuery($query, $data);
  254. }
  255. $this->id = !isset($this->id) || !is_numeric($this->id) ? $this->pdo->lastInsertId() : $this->id;
  256. }
  257. /**
  258. * Methode d'insertion massive de l'entité.
  259. * @category manipulation SQL
  260. * @param $entities tableau des entité a inserer (update non géré)
  261. * @param $maxLines grouper par requete de $maxLines maximum
  262. * @return Aucun retour
  263. */
  264. public static function saveAll($entities,$maxLines = 300) {
  265. global $myUser;
  266. if(empty($entities)) return;
  267. $reference = $entities[0];
  268. $connector = $reference->connector;
  269. $sql_head = $connector::insert_head();
  270. $sql_body = $connector::insert_body();
  271. $time = time();
  272. $login = is_object($myUser) && $myUser->login!='' ? $myUser->login : '';
  273. //sépare en requetes groupées de $maxLines lignes max
  274. $entities_groups = array_chunk($entities, $maxLines);
  275. $tableName = $reference->tableName(false,$reference);
  276. foreach ($entities_groups as $entities_group) {
  277. $end = count($entities_group)-1;
  278. $data = array();
  279. foreach($entities_group as $u=>$entity){
  280. $entity->updated = $time;
  281. $entity->updater = $login;
  282. $fields = array();
  283. $i = 0;
  284. foreach ($entity->fields as $field => $type) {
  285. if ($type == 'key') continue;
  286. $data[':'.$u.'a'.$i] = $type!='boolean' ? $entity->{$field} : ($entity->{$field} ? 1:0);
  287. $fields[$field] = ':'.$u.'a'.$i;
  288. $i++;
  289. }
  290. if($u==0){
  291. $query = self::render($sql_head,array(
  292. 'table' => $tableName,
  293. 'fields' => $fields,
  294. 'fieldMapping' => $reference->fieldMapping
  295. ));
  296. }
  297. $query .= self::render($sql_body,array(
  298. 'table' => $entity->tableName(false,$entity),
  299. 'fields' => $fields,
  300. 'fieldMapping' => $entity->fieldMapping
  301. ));
  302. if($u!=$end) $query .= ',';
  303. }
  304. $reference->customQuery($query, $data);
  305. }
  306. }
  307. /**
  308. * Méthode de modification d'éléments de l'entité.
  309. * @category manipulation SQL
  310. * @param <Array> $colonnes=>$valeurs
  311. * @param <Array> $colonnes (WHERE) =>$valeurs (WHERE)
  312. * @return Aucun retour
  313. */
  314. public static function change($columns, $columns2 = array()) {
  315. $class = get_called_class();
  316. $instance = new $class();
  317. $connector = $instance->connector;
  318. $fields = array();
  319. $i = 0;
  320. $values = array();
  321. foreach ($columns as $field => $value) {
  322. $values[':'.$i] = $value;
  323. $fields[$field] = ':'.$i;
  324. $i++;
  325. }
  326. $filters = array();
  327. foreach($columns2 as $key=>$value){
  328. $filter = array(
  329. 'operator' => '=',
  330. 'field' => $key,
  331. 'postoperator' => ''
  332. );
  333. if(strpos($key,':')!==false){
  334. $infos = explode(':',$key);
  335. $filter['operator'] = $infos[1];
  336. $filter['field'] = $infos[0];
  337. }
  338. $fieldInfos = $instance->fieldMapping[$filter['field']];
  339. $filter['type'] = $fieldInfos['type'];
  340. $filter['column'] = $fieldInfos['column'];
  341. $connector::processField($filter,$value,$values,$i);
  342. $filters[] = $filter;
  343. }
  344. $data = array(
  345. 'table' => $class::tableName(false,$instance),
  346. 'fields' => $fields,
  347. 'filter' => !isset($filters) || count($filters) == 0 ? null: $filters,
  348. 'fieldMapping' => $instance->fieldMapping
  349. );
  350. $sql = $connector::update();
  351. $sql = Entity::render($sql,$data);
  352. $instance->customQuery($sql, $values);
  353. }
  354. /**
  355. * Méthode de selection de tous les elements de l'entité.
  356. * @category manipulation SQL
  357. * @param <String> $ordre=null
  358. * @param <String> $limite=null
  359. * @return <Array<Entity>> $Entity
  360. */
  361. public static function populate($order = null, $limit = null,$selColumn = array('*'),$joins = 0) {
  362. $results = self::loadAll(array(), $order, $limit,$selColumn,$joins);
  363. return $results;
  364. }
  365. /**
  366. * Méthode de selection multiple d'elements de l'entité.
  367. * @category manipulation SQL
  368. * @param <Array> $colonnes (WHERE)
  369. * @param <Array> $valeurs (WHERE)
  370. * @param <String> $ordre=null
  371. * @param <String> $limite=null
  372. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  373. * @return <Array<Entity>> $Entity
  374. */
  375. public static function loadAll($columns = array(), $order = null, $limit = null, $selColumn = array('*'), $joins = 0) {
  376. $class = get_called_class();
  377. $instance = new $class();
  378. $connector = $instance->connector;
  379. $values = array();
  380. $i=0;
  381. $filters = array();
  382. foreach($columns as $key=>$value){
  383. $filter = array(
  384. 'operator' => '=',
  385. 'field' => $key,
  386. 'postoperator' => ''
  387. );
  388. if(strpos($key,':')!==false){
  389. $infos = explode(':',$key);
  390. $filter['operator'] = $infos[1];
  391. $filter['field'] = $infos[0];
  392. }
  393. $fieldInfos = $instance->fieldMapping[$filter['field']];
  394. $filter['type'] = $fieldInfos['type'];
  395. $filter['column'] = $fieldInfos['column'];
  396. $connector::processField($filter,$value,$values,$i);
  397. $filters[] = $filter;
  398. }
  399. if(!empty($order)){
  400. foreach ($order as $key=>$clause) {
  401. foreach ($instance->fieldMapping as $attribute => $infos) {
  402. $order[$key] = str_replace( $attribute,$infos['column'],$order[$key]);
  403. }
  404. }
  405. }
  406. $tableName = $class::tableName(false,$instance);
  407. $data = array(
  408. 'table' => $tableName,
  409. 'selected' => $selColumn,
  410. 'limit' => !isset($limit) || count($limit) == 0 ? null: $limit,
  411. 'orderby' => !isset($order) || count($order) == 0 ? null: $order,
  412. 'filter' => !isset($filters) || count($filters) == 0 ? null: $filters,
  413. 'fieldMapping' => $instance->fieldMapping
  414. );
  415. $data['joins'] = array();
  416. if($joins!=0){
  417. foreach ($data['selected'] as $k=>$column) {
  418. $data['selected'][$k] = $tableName.'.'.$column;
  419. }
  420. $data = self::recursiveJoining($instance,$data,$joins);
  421. }
  422. $sql = $connector::select();
  423. $sql = Entity::render($sql,$data);
  424. return $instance->customQuery($sql, $values, true, $joins);
  425. }
  426. /**
  427. * Méthode privée de gestion du join récursif sur les objets liés
  428. * @category manipulation SQL
  429. * @param <Object> $instance $instance de départ
  430. * @param <Array> $data Tableau de construction de la requete via render()
  431. * @param <Int> $iterations Nombre d'iteration réecurive maximum
  432. * @return <Array> $data
  433. */
  434. private static function recursiveJoining($instance,$data,$iterations,$joinInstanceAlias=''){
  435. if($iterations==0) return $data;
  436. $iterations--;
  437. if(isset($instance->links)){
  438. $instanceTable = $instance::tableName();
  439. foreach ($instance->links as $field => $className) {
  440. $className = str_replace('.class.php','',basename($className));
  441. $linkTable = $className::tableName();
  442. $field2 = 'id';
  443. $classField = explode('.',$className);
  444. if(isset($classField[1]))
  445. list($className,$field2) = $classField;
  446. $alias = substr($linkTable,0,3).'_'.$field;
  447. $joinInstance = new $className();
  448. foreach ($joinInstance->fields as $key=>$type) {
  449. $data['selected'][] = $alias.'.'.$key.' as '.$linkTable.'_join_'.$key;
  450. }
  451. $joinTable1 = $instanceTable;
  452. if(!empty($joinInstanceAlias)) $joinTable1 = $joinInstanceAlias;
  453. $data['joins'][] = array(
  454. 'jointable1' => $joinTable1,
  455. 'jointable2' => $linkTable,
  456. 'jointableAlias' => $alias,
  457. 'field1' => $field,
  458. 'field2' => $field2
  459. );
  460. $data = self::recursiveJoining($joinInstance,$data,$iterations,$alias);
  461. }
  462. }
  463. return $data;
  464. }
  465. /**
  466. * Methode de comptage des éléments de l'entité.
  467. * @category manipulation SQL
  468. * @return<Integer> nombre de ligne dans l'entité'
  469. */
  470. public static function rowCount($columns = array()) {
  471. $values = array();
  472. $class = get_called_class();
  473. $instance = new $class();
  474. $connector = $instance->connector;
  475. $i=0;
  476. $values = array();
  477. $filters = array();
  478. foreach($columns as $key=>$value){
  479. $filter = array(
  480. 'operator' => '=',
  481. 'field' => $key,
  482. 'postoperator' => ''
  483. );
  484. if(strpos($key,':')!==false){
  485. $infos = explode(':',$key);
  486. $filter['operator'] = $infos[1];
  487. $filter['field'] = $infos[0];
  488. }
  489. $fieldInfos = $instance->fieldMapping[$filter['field']];
  490. $filter['type'] = $fieldInfos['type'];
  491. $filter['column'] = $fieldInfos['column'];
  492. $connector::processField($filter,$value,$values,$i);
  493. $filters[] = $filter;
  494. }
  495. $data = array(
  496. 'table' => $class::tableName(false,$instance),
  497. 'selected' => 'id' ,
  498. 'filter' => count($filters) == 0 ? null: $filters,
  499. 'fieldMapping' => $instance->fieldMapping
  500. );
  501. $sql = $connector::count();
  502. $execQuery = $instance->customQuery(Entity::render($sql,$data), $values);
  503. $row = $execQuery->fetch();
  504. return $row['number'];
  505. }
  506. public static function loadAllOnlyColumn($selColumn, $columns, $order = null, $limit = null) {
  507. $objects = self::loadAll($columns, $order, $limit, $selColumn);
  508. if (count($objects) == 0) $objects = array();
  509. return $objects;
  510. }
  511. /**
  512. * Méthode de selection unique d'élements de l'entité.
  513. *
  514. *
  515. * @category manipulation SQL
  516. *
  517. * @param <Array> $colonnes (WHERE)
  518. * @param <Array> $valeurs (WHERE)
  519. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  520. *
  521. * @return <Entity> $Entity ou false si aucun objet n'est trouvé en base
  522. */
  523. public static function load($columns = array(),$joins =0) {
  524. $objects = self::loadAll($columns, null, array('1'),array('*'),$joins);
  525. if (!isset($objects[0])) $objects[0] = false;
  526. return $objects[0];
  527. }
  528. /**
  529. * Méthode de selection unique d'élements de l'entité.
  530. * @param <Array> $colonnes (WHERE)
  531. * @param <Array> $valeurs (WHERE)
  532. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  533. * @deprecated use byId
  534. * @return <Entity> $Entity ou false si aucun objet n'est trouvé en base
  535. */
  536. public static function getById($id,$joins =0 ) {
  537. return self::byId($id,$joins =0);
  538. }
  539. /**
  540. * Méthode de selection unique d'élements de l'entité.
  541. * @param <Array> $colonnes (WHERE)
  542. * @param <Array> $valeurs (WHERE)
  543. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  544. * @return <Entity> $Entity ou false si aucun objet n'est trouvé en base
  545. */
  546. public static function byId($id,$joins =0 ) {
  547. return self::load(array('id' => $id),$joins);
  548. }
  549. //parsing des templates sql de cnnecteurs avec les filtres/columns/data...
  550. public static function render($sql,$data=array()) {
  551. //loop
  552. $sql = preg_replace_callback('/{{\:([^\/\:\?}]*)}}(.*?){{\/\:[^\/\:\?}]*}}/',function($matches) use ($data) {
  553. $tag = $matches[1];
  554. $sqlTpl = $matches[2];
  555. $sql = '';
  556. if(isset($data[$tag])){
  557. $i = 0;
  558. $values = $data[$tag];
  559. if($tag =='joins'){
  560. //joins
  561. foreach($values as $join){
  562. $occurence = $sqlTpl;
  563. foreach($join as $key=>$value){
  564. $occurence = str_replace(array('{{'.$key.'}}'),array($value),$occurence);
  565. }
  566. $sql.= $occurence;
  567. }
  568. }else if($tag =='filter'){
  569. //filters
  570. foreach($values as $key=>$value){
  571. $i++;
  572. $last = $i == count($values);
  573. $operator = $value['operator'];
  574. $postoperator = $value['postoperator'];
  575. $key = $value['column'];
  576. $occurence = str_replace(array('{{key}}','{{value}}','{{operator}}','{{postoperator}}'),array($key,
  577. $value['tag'],
  578. $operator,
  579. $postoperator),
  580. $sqlTpl);
  581. $occurence = preg_replace_callback('/{{\;}}(.*?){{\/\;}}/',function($matches) use ($last){
  582. return $last? '': $matches[1];
  583. },$occurence);
  584. $sql.= $occurence;
  585. }
  586. } else {
  587. //Autre boucles
  588. foreach($values as $key=>$value){
  589. $i++;
  590. $last = $i == count($values);
  591. $operator = isset($data['operator']) ? $data['operator'][0] : '=';
  592. $postoperator = isset($data['postoperator']) ? $data['postoperator'][0] : '';
  593. if(strpos($key,':')!==false){
  594. $infos = explode(':',$key);
  595. $key = $infos[0];
  596. $operator = $infos[1];
  597. if($operator=='IN' || $operator=='NOT IN'){
  598. $operator = $operator.'(';
  599. $postoperator = ')';
  600. }
  601. }
  602. $occurence = str_replace(array('{{key}}','{{value}}','{{operator}}','{{postoperator}}'),array($key,$value,$operator,$postoperator),$sqlTpl);
  603. $occurence = preg_replace_callback('/{{\;}}(.*?){{\/\;}}/',function($matches) use ($last){
  604. return $last? '': $matches[1];
  605. },$occurence);
  606. $sql.= $occurence;
  607. }
  608. }
  609. return $sql;
  610. }
  611. return '';
  612. },$sql);
  613. //conditions
  614. $sql = preg_replace_callback('/{{\?([^\/\:\?}]*)}}(.*?){{\/\?[^\/\:\?}]*}}/',function($matches) use ($data) {
  615. $key = $matches[1];
  616. $sql = $matches[2];
  617. return !isset($data[$key]) || (is_array($data[$key]) && count($data[$key])==0) ?'':$sql;
  618. },$sql);
  619. //simple vars
  620. $sql = preg_replace_callback('/{{([^\/\:\;\?}]*)}}/',function($matches) use ($data) {
  621. $key = $matches[1];
  622. return isset($data[$key])?$data[$key]:'';
  623. },$sql);
  624. return $sql;
  625. }
  626. /**
  627. * Methode de définition de l'éxistence d'un moins un des éléments spécifiés en base.
  628. *
  629. * @category manipulation SQL
  630. * @return<boolean> existe (true) ou non (false)
  631. */
  632. public static function exist($columns = array()) {
  633. $result = self::rowCount($columns);
  634. return $result != 0;
  635. }
  636. public static function deleteById($id) {
  637. self::delete(array('id' => $id));
  638. }
  639. /**
  640. * Méthode de Suppression d'elements de l'entité.
  641. * @category manipulation SQL
  642. * @param <Array> $colonnes (WHERE)
  643. * @param <Array> $valeurs (WHERE)
  644. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  645. * @return Aucun retour
  646. */
  647. public static function delete($columns, $limit = array()) {
  648. $values = array();
  649. $class = get_called_class();
  650. $instance = new $class();
  651. $connector = $instance->connector;
  652. $i=0;
  653. $values = array();
  654. $filters = array();
  655. foreach($columns as $key=>$value){
  656. $filter = array(
  657. 'operator' => '=',
  658. 'field' => $key,
  659. 'postoperator' => ''
  660. );
  661. if(strpos($key,':')!==false){
  662. $infos = explode(':',$key);
  663. $filter['operator'] = $infos[1];
  664. $filter['field'] = $infos[0];
  665. }
  666. $fieldInfos = $instance->fieldMapping[$filter['field']];
  667. $filter['type'] = $fieldInfos['type'];
  668. $filter['column'] = $fieldInfos['column'];
  669. $connector::processField($filter,$value,$values,$i);
  670. $filters[] = $filter;
  671. }
  672. $data = array(
  673. 'table' => $class::tableName(false,$instance),
  674. 'limit' => count($limit) == 0 ? null: $limit,
  675. 'filter' => count($filters) == 0 ? null: $filters,
  676. 'fieldMapping' => $instance->fieldMapping
  677. );
  678. $sql = $connector::delete();
  679. return $instance->customQuery(Entity::render($sql,$data), $values);
  680. }
  681. /**
  682. * Méthode d'indexation de la ou les colonnes ciblées
  683. * nb : il est possible d'appeller automatiquement cette méthode sur les classes entity lors du create
  684. * si la classe contient l'attribut $this->indexes = array(...);
  685. * @category manipulation SQL
  686. * @param <Array> | <String> $colonne(s)
  687. * @param <Boolean> Mode (true : ajout, false : suppression)
  688. * @return Aucun retour
  689. */
  690. public static function index($columns,$mode = true){
  691. if(!is_array($columns)) $columns = array($columns);
  692. $columns = array_filter($columns);
  693. $class = get_called_class();
  694. $instance = new $class();
  695. $connector = $instance->connector;
  696. $tableName = $class::tableName(false,$instance);
  697. foreach($columns as $column){
  698. if(!is_array($column)) $column = array($column);
  699. $data = array(
  700. 'table' => $tableName,
  701. 'column' => '`'.implode('`,`',$column).'`',
  702. 'index_name' => $tableName.'_'.implode('_',$column),
  703. 'fieldMapping' => $instance->fieldMapping
  704. );
  705. $results = $class::staticQuery(Entity::render($connector::count_index(),$data));
  706. $exists = $results->fetch();
  707. if($mode){
  708. if($exists['exists'] != 1) $class::staticQuery(Entity::render($connector::create_index(),$data));
  709. }else{
  710. if($exists['exists'] > 0) $class::staticQuery(Entity::render($connector::drop_index(),$data));
  711. }
  712. }
  713. }
  714. //Génération d'une pagination
  715. public static function paginate($itemPerPage,$currentPage,&$query,$data,$alias=''){
  716. $class = get_called_class();
  717. $instance = new $class();
  718. $keys = array_keys($instance->fields, 'key');
  719. $key = count($keys) == 1 ? $keys[0] : 'id';
  720. $tableName = $class::tableName(false,$instance);
  721. $queryNumber = $query;
  722. $queryNumber = preg_replace("/(?<!\([^(\)])(SELECT.+[\n|\t]*FROM[\s\t\r\n])({{table}}|`?".$tableName."`?)(?![^(\)]*\))/iU", 'SELECT DISTINCT '.(!empty($alias) ? $alias : $tableName).'.'.$key.' FROM $2',$queryNumber);
  723. $queryNumber = $class::staticQuery('SELECT COUNT(*) FROM ('.$queryNumber.') number',$data)->fetch();
  724. $number = $queryNumber[0];
  725. $pageNumber = $number / $itemPerPage;
  726. if($currentPage >= $pageNumber) $currentPage = 0;
  727. $limit = ' LIMIT '.($currentPage*$itemPerPage).','.$itemPerPage;
  728. $query .= $limit;
  729. return array(
  730. 'pages' => $pageNumber,
  731. 'current' => $currentPage,
  732. 'total' => $number
  733. );
  734. }
  735. public static function provide($parameter = 'id',$join=0){
  736. global $_;
  737. $class = get_called_class();
  738. return !empty($_[$parameter]) ? $class::getById($_[$parameter],$join) : new $class();
  739. }
  740. // L'alias utilisé pour la colonne du join doit avoir la syntaxe [table]_join_[field]
  741. // Ex : address_join_street
  742. public static function staticQuery($query, $data = array(), $fill = false,$joins = 0) {
  743. $class = get_called_class();
  744. $instance = new $class();
  745. return $instance->customQuery($query, $data, $fill,$joins);
  746. }
  747. public function customQuery($query, $data = array(), $fill = false,$joins = 0) {
  748. $query = str_replace('{{table}}', $this->tableName(true,$this), $query);
  749. $mapping = $this->fieldMapping;
  750. $query = preg_replace_callback('/{{([^}]*)}}/si', function($match) use ($mapping){
  751. return isset($mapping[$match[1]]) && isset($mapping[$match[1]]['column']) ? $mapping[$match[1]]['column'] : $match[0];
  752. }, $query);
  753. try{
  754. if(BASE_DEBUG) self::logFile($query.' :: '.json_encode($data, JSON_UNESCAPED_UNICODE),debug_backtrace());
  755. $results = $this->pdo->prepare($query);
  756. $results->execute($data);
  757. if (!$results) throw new Exception(json_encode($this->pdo->errorInfo()));
  758. }catch(Exception $e){
  759. Log::put("[SQL ERROR] - Erreur : ".$e->getMessage().' - Requete : '.$query.' - Données : '.json_encode($data, JSON_UNESCAPED_UNICODE));
  760. if(BASE_DEBUG) self::logFile( "Erreur : ".$e->getMessage());
  761. throw $e;
  762. }
  763. if (!$fill) return $results;
  764. $class = get_class($this);
  765. $objects = array();
  766. $results = $results->fetchAll(PDO::FETCH_ASSOC);
  767. foreach ($results as $queryReturn) {
  768. $object = new $class();
  769. foreach ($this->fields as $field => $type) {
  770. $dbField = $field;
  771. if(is_array($type)){
  772. if(isset($type['column'])) $dbField = $type['column'];
  773. $type = $type['type'];
  774. }
  775. if (isset($queryReturn[$dbField])) {
  776. $object->{$field} = $queryReturn[$dbField];
  777. unset($queryReturn[$dbField]);
  778. }
  779. }
  780. if($joins>0) $object = self::recursiveJoiningFill($object,$queryReturn,$joins);
  781. foreach ($queryReturn as $key => $value) {
  782. if(!is_numeric($key)) $object->foreignColumns[$key] = $value;
  783. }
  784. $objects[] = $object;
  785. unset($object);
  786. }
  787. return $objects == null ? array() : $objects;
  788. }
  789. //Récuperation d'une/plusieurs colonne non référencée dans l'objet mais récuperée dans une requete static query
  790. public function foreign($key=null){
  791. if(!isset($key)) return $this->foreignColumns;
  792. return isset($this->foreignColumns[$key]) ? $this->foreignColumns[$key] : '';
  793. }
  794. //Renvois une chaine de selecteur sql devant être join
  795. //ex : Client::joinString('cli') --> cli.id client_join_id,cli.label client_join_label ...
  796. public static function joinString($prefix = ''){
  797. $class = get_called_class();
  798. $instance = new $class();
  799. $tableName = $class::tableName(false,$instance);
  800. $columns = array();
  801. foreach($instance->fields() as $field)
  802. $columns[] = $prefix.'.'.$field.' '.$tableName.'_join_'.$field.' ';
  803. return implode(', ',$columns);
  804. }
  805. private static function recursiveJoiningFill($object,$queryReturn,$iterations){
  806. if($iterations == 0) return $object;
  807. $iterations--;
  808. if(isset($object->links)){
  809. foreach ($object->links as $link=>$classLink) {
  810. $classLink = str_replace('.class.php','',basename($classLink));
  811. $classField = explode('.',$classLink);
  812. if(isset($classField[1]))
  813. $classLink = $classField[0];
  814. $instanceLink = new $classLink();
  815. $tableName = $classLink::tableName(false,$instanceLink);
  816. foreach ($instanceLink->fields as $field => $type) {
  817. if (isset($queryReturn[$tableName.'_join_'.$field]))
  818. $instanceLink->{$field} = $queryReturn[$tableName.'_join_'.$field];
  819. }
  820. $instanceLink = self::recursiveJoiningFill($instanceLink,$queryReturn,$iterations);
  821. $object->joins[$link] = $instanceLink;
  822. }
  823. }
  824. return $object;
  825. }
  826. /**
  827. * 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
  828. * Nb : cette méthode ne fonctionne que si vous avez placé le parametre joins > 0 dans la méthode LoadALl
  829. * Nb : cette méthode ne fonctionne que si vous avez précisé le lien entre Contact et Adress dans la classe Contact via :
  830. protected $links = array(
  831. 'address' => 'Address'
  832. );
  833. *
  834. * @category manipulation SQL
  835. *
  836. * @param <Array> $colonnes (WHERE)
  837. * @param <Array> $valeurs (WHERE)
  838. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  839. *
  840. * @return Aucun retour
  841. */
  842. public function join($field){
  843. return isset($this->joins[$field])?$this->joins[$field]:'';
  844. }
  845. public static function logFile($msg,$backtrace=null){
  846. if(strpos(ROOT_URL, '127.0.0.1') === false && strpos(ROOT_URL, 'dev.local') === false && strpos(ROOT_URL, 'localhost') === false ) return;
  847. file_put_contents(__DIR__.SLASH.'..'.SLASH.'sql.debug.sql', date('H:i:s').' | '.$msg.PHP_EOL,FILE_APPEND);
  848. //A décommenter pour obtenir la stacktrace d'un appel sql dans le fichier sql.debug.sql
  849. //if(isset($backtrace)) file_put_contents(__DIR__.SLASH.'..'.SLASH.'sql.debug.sql', json_encode($backtrace,JSON_PRETTY_PRINT).PHP_EOL,FILE_APPEND);
  850. }
  851. public static function log_executed_query($string, $data) {
  852. $indexed=$data==array_values($data);
  853. foreach($data as $k=>$v) {
  854. if(is_string($v)) $v="'$v'";
  855. if($indexed) $string=preg_replace('/\?/',$v,$string,1);
  856. else $string=str_replace(":$k",$v,$string);
  857. }
  858. self::logFile($string);
  859. }
  860. }