Entity.class.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  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. * @return <Entity> $Entity ou false si aucun objet n'est trouvé en base
  534. */
  535. public static function getById($id,$joins =0 ) {
  536. return self::load(array('id' => $id),$joins);
  537. }
  538. //parsing des templates sql de cnnecteurs avec les filtres/columns/data...
  539. public static function render($sql,$data=array()) {
  540. //loop
  541. $sql = preg_replace_callback('/{{\:([^\/\:\?}]*)}}(.*?){{\/\:[^\/\:\?}]*}}/',function($matches) use ($data) {
  542. $tag = $matches[1];
  543. $sqlTpl = $matches[2];
  544. $sql = '';
  545. if(isset($data[$tag])){
  546. $i = 0;
  547. $values = $data[$tag];
  548. if($tag =='joins'){
  549. //joins
  550. foreach($values as $join){
  551. $occurence = $sqlTpl;
  552. foreach($join as $key=>$value){
  553. $occurence = str_replace(array('{{'.$key.'}}'),array($value),$occurence);
  554. }
  555. $sql.= $occurence;
  556. }
  557. }else if($tag =='filter'){
  558. //filters
  559. foreach($values as $key=>$value){
  560. $i++;
  561. $last = $i == count($values);
  562. $operator = $value['operator'];
  563. $postoperator = $value['postoperator'];
  564. $key = $value['column'];
  565. $occurence = str_replace(array('{{key}}','{{value}}','{{operator}}','{{postoperator}}'),array($key,
  566. $value['tag'],
  567. $operator,
  568. $postoperator),
  569. $sqlTpl);
  570. $occurence = preg_replace_callback('/{{\;}}(.*?){{\/\;}}/',function($matches) use ($last){
  571. return $last? '': $matches[1];
  572. },$occurence);
  573. $sql.= $occurence;
  574. }
  575. } else {
  576. //Autre boucles
  577. foreach($values as $key=>$value){
  578. $i++;
  579. $last = $i == count($values);
  580. $operator = isset($data['operator']) ? $data['operator'][0] : '=';
  581. $postoperator = isset($data['postoperator']) ? $data['postoperator'][0] : '';
  582. if(strpos($key,':')!==false){
  583. $infos = explode(':',$key);
  584. $key = $infos[0];
  585. $operator = $infos[1];
  586. if($operator=='IN' || $operator=='NOT IN'){
  587. $operator = $operator.'(';
  588. $postoperator = ')';
  589. }
  590. }
  591. $occurence = str_replace(array('{{key}}','{{value}}','{{operator}}','{{postoperator}}'),array($key,$value,$operator,$postoperator),$sqlTpl);
  592. $occurence = preg_replace_callback('/{{\;}}(.*?){{\/\;}}/',function($matches) use ($last){
  593. return $last? '': $matches[1];
  594. },$occurence);
  595. $sql.= $occurence;
  596. }
  597. }
  598. return $sql;
  599. }
  600. return '';
  601. },$sql);
  602. //conditions
  603. $sql = preg_replace_callback('/{{\?([^\/\:\?}]*)}}(.*?){{\/\?[^\/\:\?}]*}}/',function($matches) use ($data) {
  604. $key = $matches[1];
  605. $sql = $matches[2];
  606. return !isset($data[$key]) || (is_array($data[$key]) && count($data[$key])==0) ?'':$sql;
  607. },$sql);
  608. //simple vars
  609. $sql = preg_replace_callback('/{{([^\/\:\;\?}]*)}}/',function($matches) use ($data) {
  610. $key = $matches[1];
  611. return isset($data[$key])?$data[$key]:'';
  612. },$sql);
  613. return $sql;
  614. }
  615. /**
  616. * Methode de définition de l'éxistence d'un moins un des éléments spécifiés en base.
  617. *
  618. * @category manipulation SQL
  619. * @return<boolean> existe (true) ou non (false)
  620. */
  621. public static function exist($columns = array()) {
  622. $result = self::rowCount($columns);
  623. return $result != 0;
  624. }
  625. public static function deleteById($id) {
  626. self::delete(array('id' => $id));
  627. }
  628. /**
  629. * Méthode de Suppression d'elements de l'entité.
  630. * @category manipulation SQL
  631. * @param <Array> $colonnes (WHERE)
  632. * @param <Array> $valeurs (WHERE)
  633. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  634. * @return Aucun retour
  635. */
  636. public static function delete($columns, $limit = array()) {
  637. $values = array();
  638. $class = get_called_class();
  639. $instance = new $class();
  640. $connector = $instance->connector;
  641. $i=0;
  642. $values = array();
  643. $filters = array();
  644. foreach($columns as $key=>$value){
  645. $filter = array(
  646. 'operator' => '=',
  647. 'field' => $key,
  648. 'postoperator' => ''
  649. );
  650. if(strpos($key,':')!==false){
  651. $infos = explode(':',$key);
  652. $filter['operator'] = $infos[1];
  653. $filter['field'] = $infos[0];
  654. }
  655. $fieldInfos = $instance->fieldMapping[$filter['field']];
  656. $filter['type'] = $fieldInfos['type'];
  657. $filter['column'] = $fieldInfos['column'];
  658. $connector::processField($filter,$value,$values,$i);
  659. $filters[] = $filter;
  660. }
  661. $data = array(
  662. 'table' => $class::tableName(false,$instance),
  663. 'limit' => count($limit) == 0 ? null: $limit,
  664. 'filter' => count($filters) == 0 ? null: $filters,
  665. 'fieldMapping' => $instance->fieldMapping
  666. );
  667. $sql = $connector::delete();
  668. return $instance->customQuery(Entity::render($sql,$data), $values);
  669. }
  670. /**
  671. * Méthode d'indexation de la ou les colonnes ciblées
  672. * nb : il est possible d'appeller automatiquement cette méthode sur les classes entity lors du create
  673. * si la classe contient l'attribut $this->indexes = array(...);
  674. * @category manipulation SQL
  675. * @param <Array> | <String> $colonne(s)
  676. * @param <Boolean> Mode (true : ajout, false : suppression)
  677. * @return Aucun retour
  678. */
  679. public static function index($columns,$mode = true){
  680. if(!is_array($columns)) $columns = array($columns);
  681. $columns = array_filter($columns);
  682. $class = get_called_class();
  683. $instance = new $class();
  684. $connector = $instance->connector;
  685. $tableName = $class::tableName(false,$instance);
  686. foreach($columns as $column){
  687. if(!is_array($column)) $column = array($column);
  688. $data = array(
  689. 'table' => $tableName,
  690. 'column' => '`'.implode('`,`',$column).'`',
  691. 'index_name' => $tableName.'_'.implode('_',$column),
  692. 'fieldMapping' => $instance->fieldMapping
  693. );
  694. $results = $class::staticQuery(Entity::render($connector::count_index(),$data));
  695. $exists = $results->fetch();
  696. if($mode){
  697. if($exists['exists'] != 1) $class::staticQuery(Entity::render($connector::create_index(),$data));
  698. }else{
  699. if($exists['exists'] > 0) $class::staticQuery(Entity::render($connector::drop_index(),$data));
  700. }
  701. }
  702. }
  703. //Génération d'une pagination
  704. public static function paginate($itemPerPage,$currentPage,&$query,$data,$alias=''){
  705. $class = get_called_class();
  706. $instance = new $class();
  707. $keys = array_keys($instance->fields, 'key');
  708. $key = count($keys) == 1 ? $keys[0] : 'id';
  709. $tableName = $class::tableName(false,$instance);
  710. $queryNumber = $query;
  711. $queryNumber = preg_replace("/(?<!\([^(\)])(SELECT.+[\n|\t]*FROM[\s\t\r\n])({{table}}|`?".$tableName."`?)(?![^(\)]*\))/iU", 'SELECT DISTINCT '.(!empty($alias) ? $alias : $tableName).'.'.$key.' FROM $2',$queryNumber);
  712. $queryNumber = $class::staticQuery('SELECT COUNT(*) FROM ('.$queryNumber.') number',$data)->fetch();
  713. $number = $queryNumber[0];
  714. $pageNumber = $number / $itemPerPage;
  715. if($currentPage >= $pageNumber) $currentPage = 0;
  716. $limit = ' LIMIT '.($currentPage*$itemPerPage).','.$itemPerPage;
  717. $query .= $limit;
  718. return array(
  719. 'pages' => $pageNumber,
  720. 'current' => $currentPage,
  721. 'total' => $number
  722. );
  723. }
  724. public static function provide($parameter = 'id',$join=0){
  725. global $_;
  726. $class = get_called_class();
  727. return !empty($_[$parameter]) ? $class::getById($_[$parameter],$join) : new $class();
  728. }
  729. // L'alias utilisé pour la colonne du join doit avoir la syntaxe [table]_join_[field]
  730. // Ex : address_join_street
  731. public static function staticQuery($query, $data = array(), $fill = false,$joins = 0) {
  732. $class = get_called_class();
  733. $instance = new $class();
  734. return $instance->customQuery($query, $data, $fill,$joins);
  735. }
  736. public function customQuery($query, $data = array(), $fill = false,$joins = 0) {
  737. $query = str_replace('{{table}}', $this->tableName(true,$this), $query);
  738. $mapping = $this->fieldMapping;
  739. $query = preg_replace_callback('/{{([^}]*)}}/si', function($match) use ($mapping){
  740. return isset($mapping[$match[1]]) && isset($mapping[$match[1]]['column']) ? $mapping[$match[1]]['column'] : $match[0];
  741. }, $query);
  742. try{
  743. if(BASE_DEBUG) self::logFile($query.' :: '.json_encode($data, JSON_UNESCAPED_UNICODE),debug_backtrace());
  744. $results = $this->pdo->prepare($query);
  745. $results->execute($data);
  746. if (!$results) throw new Exception(json_encode($this->pdo->errorInfo()));
  747. }catch(Exception $e){
  748. Log::put("[SQL ERROR] - Erreur : ".$e->getMessage().' - Requete : '.$query.' - Données : '.json_encode($data, JSON_UNESCAPED_UNICODE));
  749. if(BASE_DEBUG) self::logFile( "Erreur : ".$e->getMessage());
  750. throw $e;
  751. }
  752. if (!$fill) return $results;
  753. $class = get_class($this);
  754. $objects = array();
  755. $results = $results->fetchAll(PDO::FETCH_ASSOC);
  756. foreach ($results as $queryReturn) {
  757. $object = new $class();
  758. foreach ($this->fields as $field => $type) {
  759. $dbField = $field;
  760. if(is_array($type)){
  761. if(isset($type['column'])) $dbField = $type['column'];
  762. $type = $type['type'];
  763. }
  764. if (isset($queryReturn[$dbField])) {
  765. $object->{$field} = $queryReturn[$dbField];
  766. unset($queryReturn[$dbField]);
  767. }
  768. }
  769. if($joins>0) $object = self::recursiveJoiningFill($object,$queryReturn,$joins);
  770. foreach ($queryReturn as $key => $value) {
  771. if(!is_numeric($key)) $object->foreignColumns[$key] = $value;
  772. }
  773. $objects[] = $object;
  774. unset($object);
  775. }
  776. return $objects == null ? array() : $objects;
  777. }
  778. //Récuperation d'une/plusieurs colonne non référencée dans l'objet mais récuperée dans une requete static query
  779. public function foreign($key=null){
  780. if(!isset($key)) return $this->foreignColumns;
  781. return isset($this->foreignColumns[$key]) ? $this->foreignColumns[$key] : '';
  782. }
  783. //Renvois une chaine de selecteur sql devant être join
  784. //ex : Client::joinString('cli') --> cli.id client_join_id,cli.label client_join_label ...
  785. public static function joinString($prefix = ''){
  786. $class = get_called_class();
  787. $instance = new $class();
  788. $tableName = $class::tableName(false,$instance);
  789. $columns = array();
  790. foreach($instance->fields() as $field)
  791. $columns[] = $prefix.'.'.$field.' '.$tableName.'_join_'.$field.' ';
  792. return implode(', ',$columns);
  793. }
  794. private static function recursiveJoiningFill($object,$queryReturn,$iterations){
  795. if($iterations == 0) return $object;
  796. $iterations--;
  797. if(isset($object->links)){
  798. foreach ($object->links as $link=>$classLink) {
  799. $classLink = str_replace('.class.php','',basename($classLink));
  800. $classField = explode('.',$classLink);
  801. if(isset($classField[1]))
  802. $classLink = $classField[0];
  803. $instanceLink = new $classLink();
  804. $tableName = $classLink::tableName(false,$instanceLink);
  805. foreach ($instanceLink->fields as $field => $type) {
  806. if (isset($queryReturn[$tableName.'_join_'.$field]))
  807. $instanceLink->{$field} = $queryReturn[$tableName.'_join_'.$field];
  808. }
  809. $instanceLink = self::recursiveJoiningFill($instanceLink,$queryReturn,$iterations);
  810. $object->joins[$link] = $instanceLink;
  811. }
  812. }
  813. return $object;
  814. }
  815. /**
  816. * 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
  817. * Nb : cette méthode ne fonctionne que si vous avez placé le parametre joins > 0 dans la méthode LoadALl
  818. * Nb : cette méthode ne fonctionne que si vous avez précisé le lien entre Contact et Adress dans la classe Contact via :
  819. protected $links = array(
  820. 'address' => 'Address'
  821. );
  822. *
  823. * @category manipulation SQL
  824. *
  825. * @param <Array> $colonnes (WHERE)
  826. * @param <Array> $valeurs (WHERE)
  827. * @param <String> $operation="=" definis le type d'operateur pour la requete select
  828. *
  829. * @return Aucun retour
  830. */
  831. public function join($field){
  832. return isset($this->joins[$field])?$this->joins[$field]:'';
  833. }
  834. public static function logFile($msg,$backtrace=null){
  835. if(strpos(ROOT_URL, '127.0.0.1') === false && strpos(ROOT_URL, 'dev.local') === false && strpos(ROOT_URL, 'localhost') === false ) return;
  836. file_put_contents(__DIR__.SLASH.'..'.SLASH.'sql.debug.sql', date('H:i:s').' | '.$msg.PHP_EOL,FILE_APPEND);
  837. //A décommenter pour obtenir la stacktrace d'un appel sql dans le fichier sql.debug.sql
  838. //if(isset($backtrace)) file_put_contents(__DIR__.SLASH.'..'.SLASH.'sql.debug.sql', json_encode($backtrace,JSON_PRETTY_PRINT).PHP_EOL,FILE_APPEND);
  839. }
  840. public static function log_executed_query($string, $data) {
  841. $indexed=$data==array_values($data);
  842. foreach($data as $k=>$v) {
  843. if(is_string($v)) $v="'$v'";
  844. if($indexed) $string=preg_replace('/\?/',$v,$string,1);
  845. else $string=str_replace(":$k",$v,$string);
  846. }
  847. self::logFile($string);
  848. }
  849. }