-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTable.php
More file actions
2092 lines (1626 loc) · 58.1 KB
/
Copy pathTable.php
File metadata and controls
2092 lines (1626 loc) · 58.1 KB
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;
// table
// class to represent an existing table within a database
class Table extends Main\ArrObj implements Main\Contract\Import
{
// trait
use _dbAccess;
use Main\_attrPermission;
// config
protected static array $config = [
'ignore'=>null, // défini si la table est ignoré
'parent'=>null, // nom du parent de la classe table, possible aussi de mettre une classe
'priority'=>null, // code de priorité de la table
'search'=>true, // la table est cherchable
'searchSeparator'=>' ', // séparateur par défaut pour la recherche
'searchMethod'=>'like', // méthode à utiliser pour like
'searchMinLength'=>3, // longueur minimale de la recherche, si null renvoie vers les colonnes
'label'=>null, // chemin label qui remplace le défaut dans lang
'description'=>null, // chemin description qui remplace le défaut dans lang
'active'=>null, // colonne(s) utilisé pour déterminer si une ligne est active
'key'=>0, // colonne(s) utilisé pour key
'name'=>0, // colonne(s) utilisé pour le nom d'une ligne
'content'=>0, // colonne(s) utilisé pour le contenu d'une ligne
'dateCommit'=>null, // crée une relation entre un nom de colonne pour la date et un pour le user, le user peut être vide
'owner'=>null, // champs qui définissent le ou les propriétaires d'une ligne
'order'=>[0=>'desc'], // ordre et direction à utiliser par défaut, prend la première qui existe
'relation'=>['what'=>true], // champs pour représenter le what, order et output de la relation, si what est true utilise la colonne via name
'where'=>null, // where par défaut pour la table
'filter'=>null, // filter par défaut pour la table
'orderCode'=>2, // code d'ordre pour les relations
'limit'=>20, // limit à utiliser par défaut
'reservePrimary'=>false, // spécifie s'il faut réserver un id lors de l'insertion (et passer ce id au onSet)
'deleteAutoIncrement'=>false, // sur suppression, tente de reset le auto increment si la ligne était la dernière
'whereFilterTrueActive'=>true, // s'il faut joindre la colonne active dans le whereFilterTrue
'logSql'=>[ // défini si le type de requête à la table doit être loggé
'select'=>false,
'show'=>false,
'insert'=>true,
'update'=>true,
'delete'=>true,
'create'=>true,
'alter'=>true,
'truncate'=>true,
'drop'=>true],
'cols'=>null, // paramètre pour colonne, si value d'une colonne est pas vide, vérifie l'existence dans colsLoad
'colsExists'=>true, // si l'existance des colonne doit être validés
'permission'=>[
'*'=>[
'access'=>true,
'view'=>true, // pouvoir voir le contenu de la table
'select'=>true,
'show'=>true,
'insert'=>false,
'update'=>false,
'delete'=>false,
'create'=>false,
'alter'=>false,
'truncate'=>false,
'drop'=>false,
'nullPlaceholder'=>false]] // marque NULL comme placeholder si null (plutôt que -)
];
// replaceMode
protected static array $replaceMode = ['=key','=active','=name','=content','=dateCommit','=owner','relation','=where','=filter','=order']; // défini les config à ne pas merger récursivement
// dynamique
protected string $name; // nom de la table
protected Cols $cols; // objet des colonnes
protected bool $colsReady = false; // se met à true lorsque les colonnes sont toutes chargés
protected Rows $rows; // objet des lignes
protected TableClasse $classe; // objet tableClassse
protected ?TableRelation $relation = null; // conserve une copie de l'objet de relation de la table
// construct
// construit l'objet table
final public function __construct(string $name,Db $db,TableClasse $classe,array $attr)
{
$this->setName($name);
$this->setLink($db);
$this->setClasse($classe);
$this->makeAttr($attr);
$this->cols = $this->colsNew()->readOnly(true);
$this->rows = $this->rowsNew()->readOnly(true);
}
// toString
// retourne la nom de la table
final public function __toString():string
{
return $this->name();
}
// onColsLoad
// est appelé après colsLoad
// par défaut est utilisé pour faire un check de l'existance des colonnes décritent dans config/cols si l'attribut colsExists est true
final protected function onColsLoad():void
{
if($this->getAttr('colsExists') === true)
{
$array = $this->getAttr('cols');
if(is_array($array) && !empty($array))
{
$cols = $this->cols();
$missing = [];
$configExists = Col::getConfig('exists');
foreach ($array as $key => $value)
{
if(is_string($key) && !empty($value))
{
$exists = (is_bool($value))? $value:$configExists;
if(is_array($value))
{
if(array_key_exists('exists',$value) && is_bool($value['exists']))
$exists = $value['exists'];
if(array_key_exists('ignore',$value) && $value['ignore'] === true)
$exists = false;
}
if($exists === true && !$cols->exists($key))
$missing[] = $key;
}
}
if(!empty($missing))
static::throw($this,...$missing);
}
}
}
// onMakeAttr
// callback avant de mettre les attributs dans la propriété attr
final protected function onAttr(array $return):array
{
return $return;
}
// onTruncated
// appelé après un truncate réussie via la méthode truncate
final protected function onTruncated(array $option):void
{
return;
}
// onRolePermission
// callback avant chaque appel à permission can, vérifie que la table à la permission access
final protected function onRolePermission($key,array $array):bool
{
return array_key_exists('access',$array) && $array['access'] === true;
}
// toArray
// méthode utilisé pour obtenir du contenu tableau lors du remplacement via une méthode map
final public function toArray():array
{
return $this->keyValue(0,$this->getAttr('name'));
}
// cast
// retourne la valeur cast
final public function _cast():string
{
return $this->name();
}
// offsetGet
// arrayAccess offsetGet fait appel à la méthode row si key est int, ou col si key est string
// tente de charger la row si non existante
// lance une exception si rien d'existant
final public function offsetGet($key):mixed
{
$return = null;
if(is_string($key))
$return = $this->col($key);
else
$return = $this->row($key);
if(!is_object($return))
static::throw('arrayAccess','doesNotExist');
return $return;
}
// offsetSet
// arrayAccess offsetSet n'est pas permis pour la classe
final public function offsetSet($key,$value):void
{
static::throw('arrayAccess','setNotAllowed');
}
// offsetUnset
// unlink une row ou envoie une exception si row non loader
final public function offsetUnset($key):void
{
if(!is_int($key) || !$this->hasRow($key))
static::throw('arrayAcces','doesNotExist');
$this->row($key)->unlink();
}
// arr
// retourne le tableau de rows
final protected function arr():array
{
return $this->rows()->toArray();
}
// isLinked
// retourne vrai si la table est lié à l'objet db
final public function isLinked():bool
{
return $this->hasDb() && $this->db()->table($this) === $this;
}
// alive
// retourne vrai si la table existe dans la base de données
final public function alive():bool
{
return $this->db()->showTable($this) === $this->name();
}
// shouldLogSql
// retourne vrai si une requête pour la table devrait être loggé
final public function shouldLogSql(string $type):bool
{
$log = $this->getAttr(['logSql',$type]);
return $log === true;
}
// attrPermissionRolesObject
// retourne le rôles courants
final public function attrPermissionRolesObject():Main\Roles
{
return $this->db()->roles();
}
// isSearchable
// retourne vrai si la table est cherchable
// il doit aussi y avoir une colonne cherchable dans la table
final public function isSearchable():bool
{
$return = ($this->getAttr('search') === true);
if($return === true)
{
$searchable = $this->cols()->searchable();
$return = ($searchable->isNotEmpty());
}
return $return;
}
// isSearchTermValid
// retourne vrai si le terme de la recherche est valide pour les colonnes cherchables de la table
// valeur peut être scalar, un tableau à un ou plusieurs niveau
final public function isSearchTermValid($value):bool
{
return $this->cols()->searchable()->isSearchTermValid($value);
}
// sameTable
// retourne vrai si l'objet et celui fourni ont la même table
final public function sameTable($table):bool
{
return $this->db()->hasTable($table) && $this === $this->db()->table($table);
}
// setClasse
// stock l'objet tableClasse
final protected function setClasse(TableClasse $classe):void
{
$this->classe = $classe;
}
// classe
// retourne l'objet tableClasse
final public function classe():TableClasse
{
return $this->classe;
}
// setLink
// set la tables et db à l'objet
// envoie une exception si l'objet table existe déjà
final protected function setLink(Db $value):void
{
$this->setDb($value);
if($this->db()->hasTable($this->name()))
static::throw('alreadyInstantiated',$this->name());
}
// setName
// change le nom de la table après validation
final protected function setName(string $name):void
{
if(Base\Validate::isTable($name))
$this->name = $name;
else
static::throw($name,'needsLowerCaseFirstChar','noComplexChars');
}
// name
// retourne le nom de la table
final public function name():string
{
return $this->name;
}
// makeAttr
// merge le tableau de propriété dbAttr avec le tableau static config et le tableau config de row
// les clés avec valeurs null dans static config ne sont pas conservés
// si l'attribut contient la clé du type de l'application, ceci aura priorité sur tout le reste (dernier merge)
// lance onMakeAttr avant d'écrire dans la propriété
// le merge est unidimensionnel sauf pour la clé cols
final protected function makeAttr($dbAttr,bool $config=true):void
{
$db = $this->db();
$rowClass = $this->rowClass();
$rowAttr = $rowClass::config();
$baseAttr = [];
$tableAttr = $db->tableAttr($this);
$callable = static::getInitCallable();
if($config === true)
{
foreach (static::$config as $key => $value)
{
if($value !== null || !array_key_exists($key,$dbAttr))
$baseAttr[$key] = $value;
}
}
$attr = $callable(static::class,$dbAttr,$baseAttr,$tableAttr,$rowAttr);
$attr['parent'] = $this->makeAttrParent($attr['parent'] ?: null);
$attr = $this->onAttr($attr);
$this->checkAttr($attr);
$this->attr = $attr;
}
// makeAttrParent
// gère l'attribut parent si c'est un nom de classe de table ou de row
final protected function makeAttrParent(?string $return):?string
{
if(is_string($return) && Base\Classe::extendOne(Tables::keyClassExtends(),$return))
$return = $return::className(true);
return $return;
}
// checkAttr
// fait un check sur les attributs, vérifie parent et priority
final protected function checkAttr(array $attr):void
{
if(array_key_exists('parent',$attr))
{
if(is_string($attr['parent']))
{
if(!Base\Validate::isTable($attr['parent']))
static::throw($this,'parentInvalidString');
if($attr['parent'] === $this->name())
static::throw($this,'parentCannotBeSelf');
}
elseif($attr['parent'] !== null)
static::throw('invalidParent');
}
if(empty($attr['priority']) || !is_int($attr['priority']))
static::throw('invalidPriority');
}
// parent
// retourne le nom de parent de la table, ou null
final public function parent():?string
{
return $this->getAttr('parent') ?: null;
}
// priority
// retourne le code de priorité de la table
final public function priority():int
{
return $this->getAttr('priority');
}
// where
// retourne le where par défaut pour la table, possible d'append un tableau
final public function where($value=null):array
{
return $this->commonWhereFilter('where',$value);
}
// filter
// retourne le filter par défaut pour la table, possible d'append un tableau
final public function filter($value=null):array
{
return $this->commonWhereFilter('filter',$value);
}
// commonWhereFilter
// méthode utilisé par where et filter
final protected function commonWhereFilter(string $type,$value=null):array
{
$return = $this->getAttr($type);
$db = $this->db();
$true = false;
$return = $this->commonWhereFilterArg($return,$true);
$value = $this->commonWhereFilterArg($value,$true);
if(empty($return))
$return = $value;
else
$return = $db->syntaxCall('whereAppend',$return,$value);
return $return;
}
// commonWhereFilterArg
// méthode utilisé par commonWhereFilter pour traiter la valeur dans attribut ou l'argument value
// les callables sont gérés
final protected function commonWhereFilterArg($return,bool &$true):array
{
$db = $this->db();
if(static::isCallable($return))
$return = $return($this);
if($true === false)
{
if($return === true)
{
$true = true;
$return = $this->whereFilterTrue();
}
elseif(is_array($return) && in_array(true,$return,true))
{
$true = true;
$return = $db->syntaxCall('removeDefault',$return);
$return = $db->syntaxCall('whereAppend',$return,$this->whereFilterTrue());
}
}
if(is_array($return))
$return = Base\Call::dig(true,$return);
return $db->syntaxCall('removeDefault',$return);
}
// whereFilterTrue
// retourne where ou filter à utiliser si la valeur de l'attribut est true
// retourne la colonne active à 1 si existante et si l'attribut whereFilterTrueActive retourne true
// retourne toutes les colonnes requises
final public function whereFilterTrue():array
{
$return = [];
$required = $this->cols()->filter(fn($col) => $col->isRequired());
if($this->getAttr('whereFilterTrueActive',true) === true)
{
$active = $this->colActive();
if(!empty($active))
$return = [$active->name()=>1];
}
if(!empty($required))
{
foreach ($required as $col)
{
$return[] = [$col->name(),true];
}
}
return $return;
}
// whereFilter
// retourne where et filter combiné
final public function whereFilter(?array $value=null,string $method='findInSet'):array
{
$return = (array) $this->where($value);
$filter = $this->filter();
if(!empty($filter))
{
foreach ($filter as $k => $v)
{
if(!empty($v))
$return[] = [$k,$method,$v];
else
$return[] = [$k,null];
}
}
return $return;
}
// whereAll
// retourne une variable where a utilisé pour prendre toutes les lignes de la table
final public function whereAll():array
{
$return = [];
$primary = $this->primary();
$return[] = [$primary,'>=',1];
return $return;
}
// searchMinLength
// retourne le longueur minimale pour une recherche dans la table
// regarde en premier attribut de la table
// sinon ce sera la plus petite longueur de recherche minimale d'une colonne
final public function searchMinLength():int
{
return $this->cols()->searchable()->searchMinLength() ?? $this->getAttr('searchMinLength');
}
// order
// retourne l'ordre et direction à utiliser par défaut
// prend la première colonne existente et qui est ordonnable
// possible de retourner order sous forme associative ou non, par défaut oui
// possible aussi de retourner seulement une valeur du tableau
// envoie une exception si vide
final public function order($get=true)
{
$return = null;
$order = $this->getAttr('order');
if(is_array($order))
{
foreach ($order as $key => $value)
{
if($this->hasCol($key))
{
$col = $this->col($key);
if($col->isOrderable())
{
$direction = strtolower($value);
if($get === true)
$return = [$col->name()=>strtolower($value)];
else
$return = ['order'=>$col,'direction'=>$direction];
if(is_string($get))
$return = (array_key_exists($get,$return))? $return[$get]:null;
break;
}
}
}
}
return $return ?: static::throw();
}
// limit
// retourne la limite par défaut
final public function limit():int
{
return $this->getAttr('limit');
}
// default
// retourne les défaut à utiliser pour la classe base sql
// défaut possible pour where et order
// seuls les requêtes de type select, update ou delete peuvent utiliser les défaut
public function default():?array
{
return ['where'=>$this->where(true),'order'=>$this->order()];
}
// status
// retourne le tableau de status de la table
// possible de mettre le résultat en cache
final public function status(bool $cache=true):array
{
return $this->cache(__METHOD__,fn() => $this->db()->showTableStatus($this),$cache);
}
// engine
// retourne l'engin utilisé par la table, tel que décrit dans table status
final public function engine(bool $cache=true):string
{
return Base\Arr::get('Engine',$this->status($cache));
}
// autoIncrement
// retourne le autoIncrement de la table, tel que décrit dans table status
// par défaut, n'utilise pas la cache
final public function autoIncrement(bool $cache=false):int
{
return Base\Arr::get('Auto_increment',$this->status($cache));
}
// collation
// retourne la collation de la table, tel que décrit dans table status
final public function collation(bool $cache=true):string
{
return Base\Arr::get('Collation',$this->status($cache));
}
// updateTime
// retourne la date de dernière mise à jour de la table
// retounre un timestamp ou une date formatté
final public function updateTime($format=null,bool $cache=true)
{
$return = null;
$value = Base\Arr::get('Update_time',$this->status($cache));
if(is_string($value))
{
$return = Base\Datetime::time($value,'sql');
if(is_int($return) && $format !== null)
$return = Base\Datetime::format($format,$return);
}
return $return;
}
// primary
// retourne la clé primaire de la table
final public function primary():string
{
return $this->db()->primary();
}
// isColLinked
// retourne vrai si l'objet col est linked
final public function isColLinked(Col $col):bool
{
return $this->cols->in($col);
}
// hasCol
// retourne vrai si la colonne existe dans la table
final public function hasCol(...$keys):bool
{
return $this->cols()->exists(...$keys);
}
// isColsReady
// retourne vrai si l'objet colonne est entièrement chargé
final public function isColsReady():bool
{
return $this->colsReady === true;
}
// isColsEmpty
// retourne vrai si cols est empty, donc n'a jamais été initialisé
// ceci permet d'éviter la méthode cols si pas nécessaire
final public function isColsEmpty():bool
{
return $this->cols->isEmpty();
}
// setColsReady
// permet de changer la valeur à l'attribut colsReady
final protected function setColsReady(bool $value=true):void
{
$this->colsReady = $value;
}
// colsNew
// crée et retourne l'objet cols
// si les colonnes n'ont pas encore été chargés, elles le seront
final public function colsNew():Cols
{
$class = $this->classe()->cols() ?: static::throw('noColsClass');
return new $class();
}
// colsCount
// compte le nombre total de colonne dans la table
// si count est true, fait une requête dans la base de donnée
// si cache est true, le résultat de la requête est mis en cache
final public function colsCount(bool $count=false,bool $cache=false):int
{
$return = 0;
if($this->isColsEmpty())
{
if($count === true)
{
$closure = fn() => $this->db()->selectTableColumnCount($this);
$return = $this->cache(__METHOD__,$closure,$cache);
}
}
else
$return = $this->cols()->count();
return $return;
}
// colsLoad
// charge toutes les colonnes de la table, sauf celles ignorés
// onColsLoad est appelé après la création de toutes les colonnes
final public function colsLoad():self
{
$this->checkLink();
if(!$this->isColsEmpty())
static::throw('alreadyLoaded');
$db = $this->db();
$dbCols = $db->schema()->table($this);
if(empty($dbCols))
static::throw('tableHasNoCol');
$priority = 0;
$dbClasse = $db->classe();
$increment = $db->getPriorityIncrement();
$this->cols->readOnly(false);
foreach ($dbCols as $value => $dbAttr)
{
$colSchema = new ColSchema($dbAttr);
if(!is_string($value))
static::throw('invalidCol',$value);
$class = $dbClasse->tableClasseCol($this,$value,$colSchema) ?: static::throw('noColClass');
$priority += $increment;
$col = $this->colMake($class,$value,$colSchema,$priority);
$dbClasse->tableClasseCell($this,$col);
}
$this->cols()->sortDefault()->readOnly(true);
$this->onColsLoad();
$this->setColsReady(true);
return $this;
}
// colMake
// construit et store un objet colonne
final protected function colMake(string $class,string $value,ColSchema $colSchema,int $priority):Col
{
$return = new $class($value,$this,$colSchema,$priority);
if(!$return->isIgnored())
$this->cols->add($return);
return $return;
}
// colAttr
// retourne un tableau des attributs de la colonne présent dans config de la table
// peut retourner null, utiliser par dbClasse, a plus de priorité que db/colAttr
final public function colAttr(string $col):?array
{
$return = $this->attr['cols'][$col] ?? null;
if(is_string($return))
static::throw($this,$col,'stringNotAllowed',$return);
$return = Base\Arr::replace($this->db()->colAttr($col),$return);
return $return;
}
// cols
// retourne l'objet des colonnes
// charge les colonnes si l'objet cols est toujours vide
final public function cols(...$keys):Cols
{
if($this->isColsEmpty())
$this->colsLoad();
return (empty($keys))? $this->cols:$this->cols->gets(...$keys);
}
// col
// retourne l'objet d'une colonne
// peut fournir un index, un tableau qui retournera la première existante, une string, une colonne ou une cellule
// envoie une exception si non existant
final public function col($col):Col
{
return static::typecheck($this->cols()->get($col),Col::class);
}
// colPattern
// retourne l'objet d'une colonne ou null
// si un pattern est fourni, passe dans base/col addPattern
// sinon si la colonne n'existe pas rajoute tous les patterns possibles dans le nom
// sauf les patterns en lien avec la langue et qui n'est pas la langue courante
final public function colPattern(string $col,?string $pattern=null):?Col
{
$return = null;
if(is_string($pattern))
$col = ColSchema::addPattern($pattern,$col);
elseif(!$this->hasCol($col))
$col = ColSchema::possible($col,true);
if(!empty($col) && $this->hasCol($col))
$return = $this->col($col);
return $return;
}
// colActive
// retourne la colonne active
// peut retourner null, n'envoie pas d'exception
final public function colActive():?Col
{
$return = null;
$active = $this->getAttr('active');
if(!empty($active) && $this->hasCol($active))
$return = $this->col($active);
return $return;
}
// colKey
// retourne la colonne key ou envoie une exception si non existante
// possible de spécifier une langue, sinon langue courante ou pas de langue
final public function colKey(?string $lang=null):Col
{
return $this->colCommon('key',$lang);
}
// colName
// retourne la name key ou envoie une exception si non existante
// possible de spécifier une langue, sinon langue courante ou pas de langue
final public function colName(?string $lang=null):Col
{
return $this->colCommon('name',$lang);
}
// colContent
// retourne la colonne content ou envoie une exception si non existante
// possible de spécifier une langue, sinon langue courante ou pas de langue
final public function colContent(?string $lang=null):Col
{
return $this->colCommon('content',$lang);
}
// colCommon
// méthode protégé utilisé par colKey, colName et colContent
final protected function colCommon(string $key,?string $lang=null):Col
{
$return = $this->col($this->getAttr($key));
if(is_string($lang) && !empty($return))
{
$stripPattern = $return->schema()->nameStripPattern();
if(is_string($stripPattern))
$return = $this->colPattern($stripPattern,$lang);
}
return $return;
}
// colsDateCommit
// méthode qui retourne un tableau avec toutes les colonnes représentant un commit de date
// inclut aussi le user associé si existnt
final public function colsDateCommit():array
{
$return = [];
$attr = $this->getAttr('dateCommit');
if(is_array($attr) && !empty($attr))
{
foreach ($attr as $date => $user)
{
if($this->hasCol($date))
{
$r = [];
$colDate = $this->col($date);
$key = $colDate->name();
$r['date'] = $colDate;
$r['user'] = null;
if(!is_bool($user) && $this->hasCol($user))
$r['user'] = $this->col($user);
$return[$key] = $r;
}
}
}
return $return;
}
// colsOwner
// retourne un objet cols avec toutes les colonnes représentant un propriétaire
final public function colsOwner():Cols
{
$return = $this->colsNew();
$attr = $this->getAttr('owner');
if(is_array($attr) && !empty($attr))
{
foreach ($attr as $name)
{
if($this->hasCol($name))
{
$col = $this->col($name);
$return->add($col);
}