aboutsummaryrefslogtreecommitdiffstats
path: root/imperium/Query/Query.php
blob: b45fdbf1269f8e89dc8df84f11056280d8a45830 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
<?php
	
	namespace Imperium\Query
	{
		
		use DI\DependencyException;
		use DI\NotFoundException;
		use Imperium\Connexion\Connect;
		use Imperium\Exception\Kedavra;
		use Imperium\Html\Pagination\Pagination;
		use Imperium\Tables\Table;
		use Imperium\Zen;
		use PDO;
		
		/**
		 * Class Query
		 *
		 * @author  Willy Micieli
		 *
		 * @package Imperium\Query
		 *
		 * @license GPL
		 *
		 * @version 10
		 *
		 */
		class Query extends Zen
		{
			
			/**
			 *
			 * The query mode
			 *
			 * @var int
			 *
			 */
			private $mode;
			
			/**
			 *
			 * The join clause
			 *
			 * @var string
			 *
			 */
			private $join;
			
			/**
			 *
			 * The union clause
			 *
			 * @var string
			 *
			 */
			private $union;
			
			/**
			 *
			 * All selected columns
			 *
			 * @var string
			 *
			 */
			private $columns;
			
			/**
			 *
			 * The where clause
			 *
			 * @var string
			 *
			 */
			private $where;
			
			/**
			 *
			 * The connection to the base
			 *
			 * @var Connect
			 *
			 */
			private $connexion;
			
			/**
			 * The from clause
			 *
			 * @var string
			 *
			 */
			private $from;
			
			/**
			 *
			 * The order by clause
			 *
			 * @var string
			 *
			 */
			private $order;
			
			/**
			 *
			 * The limit clause
			 *
			 * @var string
			 *
			 */
			private $limit;
			
			/**
			 *
			 * The first table name
			 *
			 * @var string
			 *
			 */
			private $first_table;
			
			/**
			 *
			 * The second table name
			 *
			 * @var string
			 *
			 */
			private $second_table;
			
			/**
			 *
			 * The where column name
			 *
			 * @var string
			 */
			private $where_param;
			
			/**
			 *
			 * The where condition
			 *
			 * @var string
			 *
			 */
			private $where_condition;
			
			/**
			 *
			 * The where expected value
			 *
			 * @var mixed
			 *
			 */
			private $where_expected;
			
			/**
			 * @var string
			 */
			private $order_cond;
			
			/**
			 * @var string
			 */
			private $second_param;
			
			/**
			 * @var string
			 */
			private $first_param;
			
			/**
			 * @var string
			 */
			private $order_key;
			
			/**
			 * The current table
			 *
			 * @var string
			 *
			 */
			private $table;
			
			/**
			 * @var bool
			 */
			private $use_fetch = false;
			
			/**
			 * @var string
			 */
			private $and;
			
			/**
			 * @var string
			 */
			private $or;
			
			/**
			 * @var int
			 */
			private $pdo_mode = PDO::FETCH_OBJ;
			
			/**
			 * @var string
			 */
			private $offset;
			
			/**
			 *
			 * The primary key
			 *
			 * @var string
			 *
			 */
			private $primary;

            /**
             *
             * The constructor
             *
             * @method __construct
             *
             * @param bool $web
             * @param bool $admin
             * @throws DependencyException
             * @throws NotFoundException
             */
			public function __construct(bool $web = false,bool $admin = false)
			{

			    if ($web)
			        $this->connexion = connect(SQLITE, base('app'). DIRECTORY_SEPARATOR . 'Routing' .DIRECTORY_SEPARATOR. 'web.sqlite3');
                elseif($admin)
                    $this->connexion =  connect(SQLITE, base('app'). DIRECTORY_SEPARATOR . 'Routing' .DIRECTORY_SEPARATOR. 'admin.sqlite3');
                else
                   $this->connexion =  $this->app(Connect::class);
			}
			
			/**
			 *
			 *
			 * @return Connect
			 *
			 */
			public function connexion() : Connect
			{
				return $this->connexion->set($this->pdo_mode);
			}
			
			/**
			 *
			 * List all columns inside the table
			 *
			 * @throws Kedavra
			 *
			 * @return array
			 *
			 */
			public function columns() : array
			{
				
				$fields = collect();
				switch($this->connexion()->driver())
				{
					case MYSQL:
						foreach($this->connexion()->request("SHOW FULL COLUMNS FROM {$this->table}") as $column)
							$fields->push($column->Field);
                    break;
					case POSTGRESQL:
						foreach($this->connexion()->request("SELECT column_name FROM information_schema.columns WHERE table_name ='{$this->table}'") as $column)
							$fields->push($column->column_name);
                    break;
					case SQLITE:
						foreach($this->connexion()->request("PRAGMA table_info({$this->table})") as $column)
							$fields->push($column->name);
                    break;
				}
				
				return $fields->all();
			}

            /**
             *
             *
             * @param string $table
             *
             * @param bool $routes
             * @param bool $admin
             *
             * @return Query
             *
             * @throws DependencyException
             * @throws NotFoundException
             */
			public static function from(string $table, bool $routes = false,bool $admin =false) : Query
			{
				
				return (new static($routes,$admin))->select_table($table);
			}
			
			/**
			 *
			 * Add a limit
			 *
			 * @param  int  $limit
			 *
			 * @param  int  $offset
			 *
			 * @return Query
			 */
			public function take(int $limit, int $offset = 0) : Query
			{
				
				$this->limit = $this->connexion()->mysql() ? "LIMIT $offset,$limit" : "LIMIT $limit OFFSET $offset";
				
				return $this;
			}
			
			/**
			 * @param  string  $key
			 *
			 * @return Query
			 */
			public function primary(string $key = 'id') : Query
			{
				
				$this->primary = $key;
				
				return $this;
			}
			
			/**
			 * @throws Kedavra
			 *
			 * @return string
			 *
			 */
			public function key()
			{
				
				return def($this->primary) ? $this->primary : $this->primary_key();
			}
			
			/**
			 *
			 * Found the primary key
			 *
			 * @throws Kedavra
			 *
			 * @return string
			 *
			 *
			 */
			public function primary_key() : string
			{
				
				switch($this->connexion()->driver())
				{
					case MYSQL:
						foreach($this->connexion()->request("show columns from {$this->table} where `Key` = 'PRI';") as $key)
							return $key->Field;
						break;
					case POSTGRESQL:
						foreach($this->connexion()->request("select column_name FROM information_schema.key_column_usage WHERE table_name = '{$this->table}';") as $key)
							return $key->column_name;
						break;
					case SQLITE:
						foreach($this->connexion()->request("PRAGMA table_info({$this->table})") as $field)
						{
							if(def($field->pk))
								return $field->name;
						}
						break;
				}
				throw  new Kedavra('We have not found a primary key');
			}
			
			/**
			 *
			 * @param  int  $id
			 *
			 * @throws Kedavra
			 *
			 * @return object
			 *
			 */
			public function find(int $id)
			{
				
				return $this->where($this->key(), EQUAL, $id)->fetch(true)->all();
			}
			
			/**
			 *
			 * Get values was different of expected
			 *
			 * @param  string  $column
			 * @param          $expected
			 *
			 * @throws Kedavra
			 * @return Query
			 *
			 */
			public function different(string $column, $expected)
			{
				
				return $this->where($column, DIFFERENT, $expected);
			}
			
			/**
			 *
			 * Count all record
			 *
			 * @throws Kedavra
			 *
			 * @return int
			 *
			 */
			public function sum() : int
			{
				
				return sum($this->all());
			}
			
			/**
			 *
			 * Destroy a record by id
			 *
			 * @param  int  $id
			 *
			 * @throws Kedavra
			 *
			 * @return bool
			 *
			 */
			public function destroy(int $id) : bool
			{
				
				return $this->where($this->key(), EQUAL, $id)->mode(DELETE)->delete();
			}
			
			/**
			 *
			 * Return the query generated
			 *
			 * @method sql
			 *
			 * @throws Kedavra
			 *
			 * @return string
			 *
			 */
			public function sql() : string
			{
				
				$where = def($this->where) ? $this->where : '';
				$order = def($this->order) ? $this->order : '';
				$table = def($this->from) ? $this->from : '';
				$limit = def($this->limit) ? $this->limit : '';
				$offset = def($this->offset) ? $this->offset : '';
				$join = def($this->join) ? $this->join : '';
				$union = def($this->union) ? $this->union : '';
				$mode = def($this->mode) ? $this->mode : '';
				$or = def($this->or) ? $this->or : '';
				$and = def($this->and) ? $this->and : '';
				$columns = def($this->columns) ? $this->columns : "*";
				$mode = def($mode) ? $mode : SELECT;
				switch($mode)
				{
					case SELECT:
						return "SELECT $columns $table $where $and $or $order $limit $offset";
						break;
					case DELETE :
						return "DELETE $table $where $and $or";
						break;
					case UNION:
					case UNION_ALL:
						return "$union $where $and $or $order $limit $offset";
						break;
					case collect(self::JOIN_MODE)->exist($mode) :
						return "$join $order $limit";
						break;
					default:
						throw new Kedavra('The query mode is not define');
						break;
				}
			}
			
			/**
			 *
			 * Generate a where clause
			 *
			 * @method where
			 *
			 * @param  string  $column     The column name
			 * @param  string  $condition  The condition
			 * @param  mixed   $expected   The expected value
			 *
			 * @throws Kedavra
			 *
			 **@return Query
			 *
			 */
			public function where(string $column, string $condition, $expected) : Query
			{
				
				$condition = html_entity_decode($condition);
				$this->where_param = $column;
				$this->where_condition = $condition;
				$this->where_expected = $expected;
				is_true(not_in(self::VALID_OPERATORS, $condition), true, "The operator is invalid");
				$this->where = is_numeric($expected) ? "WHERE $column $condition $expected" : "WHERE $column $condition {$this->connexion->pdo()->quote($expected)}";
				
				return $this;
			}
			
			/**
			 *
			 * Get the table name
			 *
			 * @return string
			 *
			 */
			public function table() : string
			{
				
				return $this->table;
			}
			
			/***
			 *
			 * Select only column
			 *
			 * @param  array  ...$columns
			 *
			 * @return Query
			 */
			public function select(array $columns) : Query
			{
				
				$this->columns = collect($columns)->join(', ');
				
				return $this;
			}
			
			/**
			 *
			 * Generate a between clause
			 *
			 * @method between
			 *
			 * @param  string  $column  The column name
			 * @param  mixed   $begin   The begin value
			 * @param  mixed   $last    The last value
			 *
			 * @return Query
			 *
			 */
			public function between(string $column, $begin, $last) : Query
			{
				
				$begin = $this->connexion()->pdo()->quote($begin);
				$last = $this->connexion()->pdo()->quote($last);
				$this->where = "WHERE $column BETWEEN $begin AND $last";
				
				return $this;
			}
			
			/**
			 *
			 * Generate an order by clause
			 *
			 * @method by
			 *
			 * @param  string  $column  The column name
			 * @param  string  $order   The order by option
			 *
			 * @return Query
			 *
			 */
			public function by(string $column, string $order = DESC) : Query
			{
				
				$this->order_cond = $order;
				$this->order_key = $column;
				$this->order = "ORDER BY $column $order";
				
				return $this;
			}
			
			/**
			 *
			 * Return the result of the generated query in an array
			 *
			 * @method get
			 *
			 * @throws Kedavra
			 *
			 * @return mixed
			 *
			 */
			public function all()
			{
				
				return $this->use_fetch ? $this->connexion->set($this->pdo_mode)->fetch($this->sql()) : $this->connexion->set($this->pdo_mode)->request($this->sql());
			}
			
			/**
			 *
			 * Disable or enable the fetch
			 *
			 *
			 * @method fetch
			 *
			 *
			 * @param  bool  $fetch
			 *
			 * @return Query
			 */
			public function fetch(bool $fetch = false) : Query
			{
				
				$this->use_fetch = $fetch;
				
				return $this;
			}
			
			/**
			 *
			 * Define the query mode
			 *
			 * @method mode
			 *
			 * @param  int  $mode  The mode to use
			 *
			 * @throws Kedavra
			 *
			 * @return Query
			 *
			 */
			public function mode(int $mode) : Query
			{
				
				if(collect(Table::MODE)->has($mode))
					$this->mode = $mode;
				else
					throw new Kedavra("The current mode is not valid");
				
				return $this;
			}
			
			/**
			 *
			 * Change pdo fetch mode
			 *
			 * @method pdo
			 *
			 * @param  int  $mode
			 *
			 * @return Query
			 *
			 */
			public function pdo(int $mode = 0) : Query
			{
				
				$this->pdo_mode = $mode !== 0 ? $mode : PDO::FETCH_OBJ;
				
				return $this;
			}
			
			/**
			 *
			 * Run a delete query by a where clause
			 *
			 * @method delete
			 *
			 * @throws Kedavra
			 *
			 * @return bool
			 *
			 */
			public function delete() : bool
			{
				
				is_false(def($this->from, $this->where, $this->mode), true, "We have not found a where clause");
				
				return $this->connexion->execute($this->sql());
			}
			
			/**
			 *
			 * Generate a join clause
			 *
			 * @method join
			 *
			 * @param  string  $condition
			 * @param  string  $first_table   The first table name
			 * @param  string  $second_table  The second table name
			 * @param  string  $first_param   The first parameter
			 * @param  string  $second_param  The second parameter
			 * @param  string  ...$columns
			 *
			 * @throws Kedavra
			 * @return Query
			 */
			public function join(string $condition, string $first_table, string $second_table, string $first_param, string $second_param, string ...$columns) : Query
			{
				
				$this->first_table = $first_table;
				$this->second_table = $second_table;
				$this->first_param = $first_param;
				$this->second_param = $second_param;
				$columns_define = def($columns);
				$mode = $this->mode;
				$select = '';
				if($columns_define)
				{
					$end = collect($columns)->last();
					foreach($columns as $column)
						different($column, $end) ? append($select, "$first_table.$column, $second_table.$column, ") : append($select, "$first_table.$column, $second_table.$column");
				}
				$mod = 'SELECT';
				$select = $columns_define ? $select : '*';
				switch($mode)
				{
					case INNER_JOIN:
						$this->join = "$mod $select FROM $first_table INNER JOIN $second_table ON $first_table.$first_param $condition $second_table.$second_param";
						break;
					case CROSS_JOIN:
						$this->join = "$mod $select FROM $first_table CROSS JOIN $second_table";
						break;
					case LEFT_JOIN:
						$this->join = "$mod $select FROM $first_table LEFT JOIN $second_table ON $first_table.$first_param $condition $second_table.$second_param";
						break;
					case RIGHT_JOIN:
						$this->join = "$mod $select FROM $first_table RIGHT JOIN $second_table ON $first_table.$first_param $condition $second_table.$second_param";
						break;
					case FULL_JOIN:
						$this->join = "$mod $select FROM $first_table FULL  JOIN $second_table ON $first_table.$first_param $condition $second_table.$second_param";
						break;
				}
				
				return $this;
			}
			
			/**
			 *
			 * Generate an union clause
			 *
			 * @method union
			 *
			 * @param  string  $first_table    The first table name
			 * @param  string  $second_table   The second table name
			 * @param  string  $first_column   The first columns
			 * @param  string  $second_column  The seconds columns
			 *
			 * @return Query
			 *
			 */
			public function union(string $first_table, string $second_table, string $first_column, string $second_column) : Query
			{
				
				switch($this->mode)
				{
					case Query::UNION:
						if(not_def($first_column, $second_column))
							$this->union = "SELECT * FROM $first_table UNION SELECT * FROM $second_table";
						else
							$this->union = "SELECT $first_column FROM $first_table UNION SELECT $second_column FROM $second_table";
						break;
					case Query::UNION_ALL:
						if(not_def($first_column, $second_column))
							$this->union = "SELECT * FROM $first_table UNION ALL SELECT * FROM $second_table";
						else
							$this->union = "SELECT $first_column FROM $first_table UNION ALL SELECT $second_column FROM $second_table";
						break;
				}
				
				return $this;
			}
			
			/**
			 *
			 * Generate a like clause
			 *
			 * @method like
			 *
			 * @param  string  $value  [description]
			 *
			 * @throws Kedavra
			 *
			 * @return Query
			 *
			 */
			public function like(string $value) : Query
			{
				
				if($this->connexion()->mysql() || $this->connexion()->postgresql())
				{
					$columns = collect($this->columns())->join();
					$this->where = "WHERE CONCAT($columns) LIKE '%$value%'";
				}
				else
				{
					$fields = collect($this->columns());
					$end = $fields->last();
					$columns = '';
					foreach($fields->all() as $column)
					{
						if(different($column, $end))
							append($columns, "$column LIKE '%$value%' OR ");
						else
							append($columns, "$column LIKE '%$value%'");
					}
					$this->where = "WHERE $columns";
				}
				
				return $this;
			}
			
			/**
			 *
			 * Add on the where clause an and clause
			 *
			 * @param  string  $column
			 * @param  string  $condition
			 * @param  string  $expected
			 *
			 * @return Query
			 *
			 */
			public function and(string $column, string $condition, string $expected) : Query
			{
				
				append($this->and, " AND $column $condition {$this->connexion->pdo()->quote($expected)}");
				
				return $this;
			}
			
			/**
			 *
			 * Add on the where clause a n or clause
			 *
			 * @param  string  $value
			 * @param  string  $condition
			 * @param  string  $expected
			 *
			 *
			 * @return Query
			 *
			 */
			public function or(string $value, string $condition, string $expected) : Query
			{
				
				append($this->or, " OR $value $condition {$this->connexion->pdo()->quote($expected)}");
				
				return $this;
			}
			
			/**
			 *
			 *
			 * @param  string  $column
			 * @param  mixed   ...$values
			 *
			 *
			 * @return Query
			 *
			 */
			public function not(string $column, ...$values) : Query
			{
				
				if(def($this->where))
				{
					foreach($values as $value)
						append($this->where, " AND $column != {$this->connexion->pdo()->quote($value)}");
				}
				else
				{
					foreach($values as $k => $value)
					{
						$k == 0 ? append($this->where, "WHERE $column != {$this->connexion->pdo()->quote($value)} ") : append($this->where, " AND $column != {$this->connexion->pdo()->quote($value)}");
					}
				}
				
				return $this;
			}
			
			/**
			 *
			 *
			 * @param  string  $column
			 * @param  mixed   ...$values
			 *
			 * @return Query
			 *
			 */
			public function only(string $column, ...$values) : Query
			{
				
				if(def($this->where))
				{
					foreach($values as $value)
						append($this->where, " AND $column = {$this->connexion->pdo()->quote($value)}");
				}
				else
				{
					foreach($values as $k => $value)
					{
						$k == 0 ? append($this->where, "WHERE $column = {$this->connexion->pdo()->quote($value)} ") : append($this->where, " AND $column = {$this->connexion->pdo()->quote($value)}");
					}
				}
				
				return $this;
			}
			
			/**
			 *
			 *
			 *
			 * @param  string  $table
			 *
			 * @return Query
			 *
			 */
			private function select_table(string $table) : Query
			{
				
				$this->from = "FROM $table";
				$this->table = $table;
				
				return $this;
			}
			
			/**
			 * @param       $callable
			 * @param  int  $page
			 * @param  int  $limit
			 *
			 * @throws Kedavra
			 *
			 * @return string
			 *
			 */
			public function paginate($callable, int $page, int $limit) : string
			{
				
				$pagination = (new Pagination($page, $limit, $this->sum()))->paginate();
				
				return collect($this->take($limit, (($page) - 1) * $limit)->by('id')->all())->each($callable)->join('') . ' ' . $pagination;
			}
			
			/**
			 * @param  int  $limit
			 *
			 * @return Query
			 */
			public function limit(int $limit) : Query
			{
				
				$this->limit = "LIMIT $limit";
				
				return $this;
			}
			
		}
	}