-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPdo.php
2429 lines (1864 loc) · 75.1 KB
/
Pdo.php
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
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/*
* This file is part of the QuidPHP package <https://quidphp.com>
* Author: Pierre-Philippe Emond <emondpph@gmail.com>
* License: https://github.com/quidphp/orm/blob/master/LICENSE
*/
namespace Quid\Orm;
use Quid\Base;
use Quid\Main;
// pdo
// class used to query the database using the PDO object
class Pdo extends Main\Root
{
// trait
use Main\_inst;
// config
protected static array $config = [
'history'=>true, // les requêtes sont ajoutés à l'historique
'rollback'=>true, // les rollback de requête sont générés, seulement si le tableau contient la table ainsi qu'un id numérique
'debug'=>null, // les requêtes émulés sont retournés sans être lancés à la base de donnée
'cast'=>null, // les valeurs numériques des fetchs sont cast
'primary'=>'id', // nom de la clé primaire
'charset'=>'utf8mb4', // charset
'sql'=>null, // option pour baseSql
'checkVersion'=>true, // s'il faut vérifier la version à la connexion
'connect'=>[ // attribut de connexion
\PDO::ATTR_DEFAULT_FETCH_MODE=>\PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES=>false,
\PDO::ATTR_STRINGIFY_FETCHES=>false,
\PDO::ATTR_ERRMODE=>\PDO::ERRMODE_EXCEPTION],
'defaultPort'=>3306, // port par défaut
'syntax'=>[ // tableau associatif entre driver et classe syntaxe
'mysql'=>Syntax\Mysql::class],
'fetch'=>[ // tableau associatif pour les fetch mode
'assoc'=>\PDO::FETCH_ASSOC,
'assocUnique'=>\PDO::FETCH_ASSOC | \PDO::FETCH_UNIQUE,
'named'=>\PDO::FETCH_NAMED, // les clés duplicats sont merge et pas replace
'num'=>\PDO::FETCH_NUM,
'both'=>\PDO::FETCH_BOTH,
'obj'=>\PDO::FETCH_OBJ,
'lazy'=>\PDO::FETCH_LAZY,
'keyPair'=>\PDO::FETCH_KEY_PAIR,
'column'=>\PDO::FETCH_COLUMN,
'columnGroup'=>\PDO::FETCH_GROUP | \PDO::FETCH_COLUMN],
'output'=>[
'default'=>[ // output par défaut, pour select et show
'select'=>'assocs',
'show'=>'assocs'],
'all'=>[ // configuration des différents output, arg est un tableau d'argument, limit permet de spécifier une limite sql si type select et non présente
'assocs'=>['method'=>'fetchAll','fetch'=>'assoc'],
'assocsUnique'=>['method'=>'fetchAll','fetch'=>'assocUnique'],
'assocsKey'=>['method'=>'fetchAll','fetch'=>'assoc','key'=>0],
'assoc'=>['method'=>'fetch','fetch'=>'assoc','selectLimit'=>1],
'nameds'=>['method'=>'fetchAll','fetch'=>'named'],
'named'=>['method'=>'fetch','fetch'=>'named','selectLimit'=>1],
'nums'=>['method'=>'fetchAll','fetch'=>'num'],
'numsKey'=>['method'=>'fetchAll','fetch'=>'num','key'=>0],
'num'=>['method'=>'fetch','fetch'=>'num','selectLimit'=>1],
'boths'=>['method'=>'fetchAll','fetch'=>'both'],
'both'=>['method'=>'fetch','fetch'=>'both','selectLimit'=>1],
'objs'=>['method'=>'fetchAll','fetch'=>'obj'],
'objsKey'=>['method'=>'fetchAll','fetch'=>'obj','key'=>0],
'obj'=>['method'=>'fetchObject','selectLimit'=>1],
'lazy'=>['method'=>'fetch','fetch'=>'lazy','selectLimit'=>1],
'keyPairs'=>['method'=>'fetchAll','fetch'=>'keyPair','arg'=>null],
'keyPair'=>['method'=>'fetch','fetch'=>'keyPair','selectLimit'=>1,'arg'=>null],
'segments'=>['method'=>'fetchAll','fetch'=>'segment','arg'=>null],
'segment'=>['method'=>'fetch','fetch'=>'segment','selectLimit'=>1,'arg'=>null],
'columns'=>['method'=>'fetchAll','fetch'=>'column','arg'=>0],
'columnsGroup'=>['method'=>'fetchAll','fetch'=>'columnGroup','arg'=>0],
'column'=>['method'=>'fetchColumn','arg'=>0,'selectLimit'=>1],
'rowCount'=>['method'=>'rowCount'],
'columnCount'=>['method'=>'columnCount','selectLimit'=>1],
'columnMeta'=>['method'=>'getColumnMeta'],
'insertId'=>['method'=>'lastInsertId'],
'info'=>['method'=>'infoStatement'],
'*'=>['method'=>'infoStatement'],
'statement'=>[]]],
'importantVariables'=>[
'basedir','datadir','tmpdir','log_error','pid_file','socket','sql_mode','character_sets_dir',
'character_set_connection','character_set_database','character_set_filesystem',
'character_set_results','character_set_server','character_set_system','lower_case_table_names',
'collation_connection','collation_database','collation_server',
'default_storage_engine','default_tmp_storage_engine'],
'minVersion'=>[ // version minimale de la base de donnée
'mariadb'=>'10.4.0',
'mysql'=>'8.0.0']
];
// dynamic
protected ?string $dsn = null; // valeur qui content le dsn
protected ?\Pdo $pdo = null; // valeur qui contient pdo
protected ?string $syntax = null; // classe de syntax à utiliser
protected ?History $history = null; // objet history
// construct
// construction de la classe
public function __construct(string $dsn,string $password,?array $attr=null)
{
$this->makeAttr($attr);
$this->setDsn($dsn);
$this->setSyntax();
$this->connect($password);
}
// destruct
// lors de destruction de la classe
final public function __destruct()
{
$this->pdo = null;
}
// invoke
// appel de la classe, renvoie vers query
final public function __invoke(...$args)
{
return $this->query(...$args);
}
// toString
// retourne le nom de la base de donnée
final public function __toString():string
{
return $this->name();
}
// cast
// retourne la valeur cast
final public function _cast():string
{
return $this->name();
}
// onSetInst
// méthode appeler après setInst
final protected function onSetInst():void
{
$this->checkReady(true);
}
// onBeforeMakeStatement
// callback avant la création du statement dans makeStatement
protected function onBeforeMakeStatement(array $value):void
{
return;
}
// onAfterMakeStatement
// callback après la création du statement dans makeStatement
protected function onAfterMakeStatement(array $value,\PdoStatement $statement):void
{
if(!empty($value['type']))
{
if($this->getAttr('history') === true)
{
if($this->isOutput($value['type'],'insertId'))
$value['insertId'] = $this->lastInsertId();
$this->history()->add($value,$statement,$this);
}
}
}
// instName
// retourne le nom à utiliser pour storage dans inst
final public function instName():string
{
return $this->dsn();
}
// connect
// connect à une base de donnée
public function connect(string $password):self
{
$this->checkReady(false);
$dsn = static::parseDsn($this->dsn(),$this->charset(),$this->defaultPort());
if(empty($dsn))
static::throw('invalidDsn');
if(!static::isDriver($dsn['scheme']))
static::throw('unsupportedDriver');
$pdo = new \PDO($dsn['dsn'],null,$password,$this->getAttr('connect'));
if($this->getAttr('checkVersion') === true)
$this->checkVersion($pdo);
$this->pdo = $pdo;
$this->makeHistory();
return $this;
}
// disconnect
// deconnect d'une base de donnée
public function disconnect():self
{
$this->checkReady();
$this->pdo = null;
$this->history = null;
return $this;
}
// checkVersion
// envoie une exception si la version n'est pas supporté selon la config minimal version
final protected function checkVersion(\Pdo $pdo):void
{
$statement = $pdo->query('SELECT VERSION()');
$version = $statement->fetchColumn(0);
if(!static::isValidVersion($version))
static::throw('invalidDbVersion',$version);
}
// pdo
// retourne l'objet pdo
final public function pdo():\Pdo
{
return $this->pdo;
}
// primary
// retourne le nom de la clé primaire
final public function primary():string
{
return $this->getAttr('primary');
}
// charset
// retourne le nom du charset
final public function charset():string
{
return $this->getAttr('charset');
}
// collation
// retourne la collation de la base de données
final public function collation():?string
{
return $this->showVariable('collation_database');
}
// dsn
// retourne le dsn
final public function dsn():string
{
return $this->dsn;
}
// setDsn
// change le dsn
final protected function setDsn(string $value):void
{
$this->checkReady(false);
$this->dsn = $value;
}
// getFromDsn
// permet de retourner une entrée du dsn
final public function getFromDsn(string $key):?string
{
$parse = static::parseDsn($this->dsn(),$this->charset(),$this->defaultPort());
return $parse[$key] ?? null;
}
// getSyntax
// retourne la classe de syntaxe à utiliser avec la base de donnée
final public function getSyntax():string
{
return $this->syntax;
}
// setSyntax
// permet d'enregister la classe de syntaxe à utiliser
final protected function setSyntax():void
{
$driver = $this->driver();
if(is_string($driver))
{
$syntax = $this->getAttr(['syntax',$driver]);
if(is_string($syntax))
$this->syntax = $syntax::classOverload();
}
if(empty($this->syntax))
static::throw('noSyntaxFound',$driver);
}
// syntaxCall
// permet d'appeler une méthode sur la classe de syntaxe
final public function syntaxCall(string $method,...$args)
{
return $this->getSyntax()::$method(...$args);
}
// driver
// retourne le driver du dsn
final public function driver():?string
{
return $this->getFromDsn('driver');
}
// host
// retourne le host du dsn
final public function host():?string
{
return $this->getFromDsn('host');
}
// dbName
// retourne le dbname du dsn
final public function dbName():?string
{
return $this->getFromDsn('dbname');
}
// username
// retourne le username
final public function username():?string
{
return $this->getFromDsn('user');
}
// name
// retourne le nom de l'objet db
final public function name():string
{
return $this->checkReady()->dsn().'@'.$this->username();
}
// clientVersion
// retourne l'attribut client version
final public function clientVersion():string
{
return $this->getPdoAttr(\PDO::ATTR_CLIENT_VERSION);
}
// connectionStatus
// retourne l'attribut connection status
final public function connectionStatus():string
{
return $this->getPdoAttr(\PDO::ATTR_CONNECTION_STATUS);
}
// serverVersion
// retourne l'attribut server version
final public function serverVersion():string
{
return $this->getPdoAttr(\PDO::ATTR_SERVER_VERSION);
}
// serverInfo
// retourne l'attribut server info
final public function serverInfo():string
{
return $this->getPdoAttr(\PDO::ATTR_SERVER_INFO);
}
// getSqlOption
// retourne les options pour la classe base sql
public function getSqlOption(?array $option=null):array
{
return Base\Arr::plus($this->getAttr('sql'),['primary'=>$this->primary(),'charset'=>$this->charset(),'quoteClosure'=>$this->quoteClosure()],$option);
}
// setDebug
// change la valeur de option debug, si value est null, toggle
final public function setDebug(?bool $value=null):self
{
if($value === null)
$value = ($this->getAttr('debug') === true)? false:true;
return $this->setAttr('debug',$value);
}
// isReady
// retourne vrai si une connection est établi
final public function isReady():bool
{
return $this->pdo instanceof \PDO;
}
// checkReady
// lance une exception si le status n'est pas le même que celui donné en argument
final public function checkReady(bool $value=true):self
{
$ready = $this->isReady();
if($value === true && $ready === false)
static::throw('pdoNotConnected');
elseif($value === false && $ready === true)
static::throw('pdoConnected');
return $this;
}
// setRollback
// change la valeur de option rollback, si value est null, toggle
final public function setRollback(?bool $value=null):self
{
if($value === null)
$value = ($this->getAttr('rollback') === true)? false:true;
return $this->setAttr('rollback',$value);
}
// makeHistory
// créer l'objet history
final protected function makeHistory():void
{
$this->history = History::newOverload();
}
// history
// retourne l'objet de l'historique de db
final public function history():History
{
return $this->history;
}
// setHistory
// change la valeur de option history, si value est null, toggle
final public function setHistory(?bool $value=null):self
{
if($value === null)
$value = ($this->getAttr('history') === true)? false:true;
return $this->setAttr('history',$value);
}
// historyRollback
// lance le rollback sur une requête dnas l'historique
// le type est requis et un index peut être spécifié
final public function historyRollback(string $type,int $index=-1,$output=true)
{
$return = null;
$history = $this->history()->typeIndex($type,$index);
if(!empty($history) && !empty($history['rollback']))
$return = $this->query($history['rollback'],$output);
return $return;
}
// info
// retourne un tableau d'information sur la connexion pdo
public function info():array
{
$return = [];
$this->checkReady(true);
$return['dsn'] = $this->dsn();
$return['driver'] = $this->driver();
$return['username'] = $this->username();
$return['host'] = $this->host();
$return['dbname'] = $this->dbName();
$return['clientVersion'] = $this->clientVersion();
$return['connectionStatus'] = $this->connectionStatus();
$return['serverInfo'] = $this->serverInfo();
$return['serverVersion'] = $this->serverVersion();
$return['persistent'] = $this->getPdoAttr(\PDO::ATTR_PERSISTENT);
$return['autocommit'] = $this->getPdoAttr(\PDO::ATTR_AUTOCOMMIT);
$return['oracleNull'] = $this->getPdoAttr(\PDO::ATTR_ORACLE_NULLS);
$return['defaultFetchMode'] = $this->getPdoAttr(\PDO::ATTR_DEFAULT_FETCH_MODE);
$return['emulatePrepare'] = $this->getPdoAttr(\PDO::ATTR_EMULATE_PREPARES);
$return['importantVariables'] = $this->importantVariables();
$return['historyUni'] = $this->history()->keyValue();
$return['historyCounts'] = $this->history()->total();
return $return;
}
// importantVariables
// retourne un tableau avec toutes les noms et valeurs des variables importantes, tel que défini dans config
// output est keyValues
final public function importantVariables(?array $option=null):?array
{
return $this->showVariables($this->getAttr('importantVariables'),$option);
}
// getPdoAttr
// retourne un attribut de l'objet pdo ou pdoStatement
final public function getPdoAttr(int $key,?\PDOStatement $statement=null)
{
$return = null;
if(!empty($statement))
$return = $statement->getAttribute($key);
else
$return = $this->checkReady()->pdo()->getAttribute($key);
return $return;
}
// setPdoAttr
// change un attribut de l'objet pdo ou pdoStatement
final public function setPdoAttr(int $key,$value,?\PDOStatement $statement=null):bool
{
$return = false;
if(!empty($statement))
$return = $statement->setAttribute($key,$value);
else
$return = $this->checkReady()->pdo()->setAttribute($key,$value);
return $return;
}
// errorCode
// retourne un code décrivant la dernière erreur de pdo ou d'un statement
final public function errorCode(?\PDOStatement $statement=null)
{
$return = null;
if(!empty($statement))
$return = $statement->errorCode();
else
$return = $this->checkReady()->pdo()->errorCode();
return $return;
}
// errorInfo
// retourne un tableau décrivant la dernière erreur de pdo ou d'un statement
final public function errorInfo(?\PDOStatement $statement=null):?array
{
$return = null;
if(!empty($statement))
$return = $statement->errorInfo();
else
$return = $this->checkReady()->pdo()->errorInfo();
return $return;
}
// beginTransaction
// débute une transaction
final public function beginTransaction():bool
{
return $this->checkReady()->pdo()->beginTransaction();
}
// inTransaction
// retourne vrai si une transaction est active
final public function inTransaction():bool
{
return $this->checkReady()->pdo()->inTransaction();
}
// commit
// commet la transaction
final public function commit():bool
{
return $this->checkReady()->pdo()->commit();
}
// rollback
// annule la transaction
final public function rollback():bool
{
return $this->checkReady()->pdo()->rollback();
}
// lastInsertId
// retourne le dernier id inséré
final public function lastInsertId(?string $name=null):?int
{
$return = null;
$this->checkReady();
$insertId = (int) $this->pdo()->lastInsertId($name);
if($insertId > 0)
$return = $insertId;
return $return;
}
// quote
// quote une variable via pdo
final public function quote($value,?int $type=null):?string
{
$return = null;
$this->checkReady();
if(is_scalar($value) || $value === null)
{
$type = static::parseDataType($value);
if(is_int($type))
$return = $this->pdo()->quote($value,$type);
}
return $return;
}
// quoteClosure
// retourne la closure pour quoter la variable
final public function quoteClosure():\Closure
{
return function($value) {
return $this->quote($value);
};
}
// makeStatement
// prend un tableau query et retourne un objet pdo statement
// gère le try catch
// le onAfterMakeStatement a été déplacé dans la fonction query car ça causait des problèmes en cli (logNow)
final public function makeStatement($value,?array $attr=[]):?\PDOStatement
{
$return = null;
$value = $this->syntaxCall('parseReturn',$value);
try
{
if($this->checkReady() && !empty($value))
{
$this->onBeforeMakeStatement($value);
if(!empty($value['prepare']) && is_array($value['prepare']))
$return = $this->preparedStatement($value['sql'],$value['prepare'],$attr);
else
{
$query = $this->pdo->query($value['sql']);
if($query instanceof \PDOStatement)
$return = $query;
}
}
}
catch (\PDOException $e)
{
$this->statementException(null,$e,$value);
}
return $return;
}
// statementException
// lance une exception de db attrapable
public function statementException(?array $option,\Exception $exception,...$values):void
{
static::throw($exception->getMessage(),null,$option);
}
// infoStatement
// retourne le maximum d'informations sur le statement selon le type de requête
final public function infoStatement($value,\PDOStatement $statement):?array
{
$return = $this->debug($value);
if(!empty($return))
{
$type = $return['type'];
$return['statement'] = $statement;
if($this->isOutput($type,'rowCount'))
$return['row'] = $statement->rowCount();
if($this->isOutput($type,'insertId'))
$return['insertId'] = $this->lastInsertId();
if($this->isOutput($type,'columnCount'))
{
$return['all'] = $statement->fetchAll(\PDO::FETCH_ASSOC);
$return['column'] = $statement->columnCount();
$return['cell'] = $return['row'] * $return['column'];
$return['columnMeta'] = $this->getColumnMeta($statement);
}
$return['debugDumpParams'] = Base\Buffer::startCallGet([$statement,'debugDumpParams']);
}
return $return;
}
// outputStatement
// gère le output pour pdoStatement
final public function outputStatement($value,$output,\PDOStatement $statement)
{
$return = null;
$value = $this->syntaxCall('parseReturn',$value);
if(!empty($value))
{
if(!$this->isOutput($value['type'],$output))
static::throw($output,'invalidOutputFor',$value['type']);
$output = $this->output($value['type'],$output);
if(!empty($output))
{
if($output['type'] === 'statement')
$return = $statement;
elseif(!empty($output['method']))
{
$method = $output['method'];
$type = $value['type'];
if($method === 'infoStatement')
$return = $this->infoStatement($value,$statement);
elseif($method === 'rowCount' && $this->isOutput($type,$output['type']))
$return = $statement->rowCount();
elseif($method === 'lastInsertId' && $this->isOutput($type,$output['type']))
$return = $this->lastInsertId();
elseif(in_array($type,['select','show'],true))
$return = $this->outputStatementSelectShow($value,$output,$statement);
}
}
}
return $return;
}
// getColumnMeta
// retourne un tableau multidimensionnel avec les meta des colonnes du statement
final public function getColumnMeta(\PDOStatement $value):array
{
$return = [];
for ($i=0; $i < $value->columnCount(); $i++)
{
$meta = $value->getColumnMeta($i);
if(!empty($meta['name']))
{
$key = $meta['name'];
$return[$key] = $meta;
}
}
return $return;
}
// fetchKeyPairStatement
// retourne une key pair à partir d'un statement
// arg peut être des clés, indexes ou null
// fonctionne même si le statement contient plus de deux colonnes
final public function fetchKeyPairStatement(?array $arg,\PDOStatement $statement):?array
{
$return = null;
$count = $statement->columnCount();
$arg = $this->syntaxCall('shortcut',array_values((array) $arg));
if($count > 2)
{
if(!empty($fetch = $statement->fetch(\PDO::FETCH_ASSOC)))
{
if(!empty($arg) && count($arg) === 2 && !Base\Arr::onlyNumeric($arg))
$return = Base\Arr::keyValue($arg[0],$arg[1],$fetch);
else
{
$arg = (empty($arg) || count($arg) !== 2)? [0,1]:$arg;
$return = Base\Arr::keyValueIndex($arg[0],$arg[1],$fetch);
}
}
}
elseif($count === 2)
$return = $statement->fetch(\PDO::FETCH_KEY_PAIR);
return $return;
}
// fetchKeyPairsStatement
// retourne les key pairs à partir d'un statement
// arg peut être des clés, indexes ou null
// fonctionne même si le statement contient plus de deux colonnes
final public function fetchKeyPairsStatement(?array $arg,\PDOStatement $statement):?array
{
$return = null;
$count = $statement->columnCount();
$arg = $this->syntaxCall('shortcut',array_values((array) $arg));
if($count > 2)
{
if(!empty($fetch = $statement->fetchAll(\PDO::FETCH_ASSOC)))
{
if(!empty($arg) && count($arg) === 2 && !Base\Arr::onlyNumeric($arg))
$return = Base\Column::keyValue($arg[0],$arg[1],$fetch);
else
{
$arg = (empty($arg) || count($arg) !== 2)? [0,1]:$arg;
$return = Base\Column::keyValueIndex($arg[0],$arg[1],$fetch);
}
}
}
elseif($count === 2)
$return = $statement->fetchAll(\PDO::FETCH_KEY_PAIR);
return $return;
}
// fetchColumnStatement
// retourne une colonne d'une ligne à partir d'un statement
// arg peut être index ou nom de colonne
final public function fetchColumnStatement($arg,\PDOStatement $statement)
{
$return = null;
$arg = $this->syntaxCall('shortcut',array_values((array) $arg));
if(!empty($arg) && !Base\Arr::onlyNumeric($arg) && !empty($fetch = $statement->fetch(\PDO::FETCH_ASSOC)))
$return = Base\Arr::get($arg[0],$fetch);
else
{
$arg = $arg ?: [0];
$return = $statement->fetchColumn(...$arg);
}
return $return;
}
// fetchColumnsStatement
// retourne une colonne sur toutes les lignes d'un statement
// arg peut être index ou nom de colonne
final public function fetchColumnsStatement($arg,\PDOStatement $statement):?array
{
$return = null;
$arg = $this->syntaxCall('shortcut',array_values((array) $arg));
if(!empty($arg) && !Base\Arr::onlyNumeric($arg) && !empty($fetch = $statement->fetchAll(\PDO::FETCH_ASSOC)))
$return = Base\Column::value($arg[0],$fetch);
else
{
$arg = $arg ?: [0];
$return = $statement->fetchAll(\PDO::FETCH_COLUMN,...$arg);
}
return $return;
}
// fetchSegmentStatement
// retourne la string avec segments remplacés
// arg doit être un tableau contenant la string comme première valeur
final public function fetchSegmentStatement(array $arg,\PDOStatement $statement):?string
{
$return = null;
$arg = current($arg);
if(is_string($arg) && !empty($arg) && !empty($fetch = $statement->fetch(\PDO::FETCH_ASSOC)))
$return = Base\Segment::sets(null,$fetch,$arg);
return $return;
}
// fetchSegmentsStatement
// retounre un tableau avec les ids comme clés et la string avec segments remplacés comme valeur
// arg doit être un tableau contenant la string comme première valeur
// une exception peut être envoyé si la clé est invalide ou déjà existante dans le tableau de retour
final public function fetchSegmentsStatement(array $arg,\PDOStatement $statement):?array
{
$return = null;
$arg = current($arg);
if(is_string($arg) && !empty($arg) && is_array($fetch = $statement->fetchAll(\PDO::FETCH_ASSOC)))
{
$return = [];
foreach ($fetch as $value)
{
if(is_array($value))
{
$k = current($value);
if(!Base\Arr::isKey($k) || array_key_exists($k,$return))
static::throw('invalidKey',$k);
$return[$k] = Base\Segment::sets(null,$value,$arg);
}
}
}
return $return;
}
// query
// méthode pour effectuer des requetes à la base de données
// la requête n'est pas lancé si option debug est true ou output est debug
// si output est un tableau avec clé beforeAfter, possibilité de retourner la ligne avant et/ou après le insert, update ou delete
// 28/04/2020 onAfterMakeStatement est déplacé ici car problème avec le logNow
public function query($value,$output=true)
{
$return = null;
if($this->getAttr('debug') || $output === 'debug')
$return = $this->debug($value);
elseif(!empty($value = $this->syntaxCall('parseReturn',$value)))
{
$beforeAfter = (is_array($output) && array_key_exists('beforeAfter',$output) && in_array($value['type'],['insert','update','delete'],true));
if($beforeAfter === true)
{
$return = [];
$return['before'] = $this->queryBeforeAfter('before',$value,$output['beforeAfter']);
}
$statement = $this->makeStatement($value);
if(!empty($statement))
{
if($beforeAfter === true)
{
$return['query'] = $this->outputStatement($value,true,$statement);
if($return['query'] !== $statement)
$statement->closeCursor();