-
Notifications
You must be signed in to change notification settings - Fork 0
/
Schema.php
795 lines (709 loc) · 22.6 KB
/
Schema.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
<?php
declare(strict_types=1);
/**
* Queryflatfile
*
* @package Queryflatfile
* @license https://github.com/soosyze/queryflatfile/blob/master/LICENSE (MIT License)
*/
namespace Queryflatfile;
use Queryflatfile\DriverInterface;
use Queryflatfile\Exception\Exception;
use Queryflatfile\Exception\Query\ColumnsValueException;
use Queryflatfile\Exception\Query\TableNotFoundException;
use Queryflatfile\Exception\TableBuilder\ColumnsNotFoundException;
use Queryflatfile\TableBuilder;
/**
* Pattern fluent pour la gestion d'un schéma de données.
*
* @author Mathieu NOËL <mathieu@soosyze.com>
*/
class Schema
{
/**
* Format de la base de données.
*
* @var DriverInterface
*/
protected $driver;
/**
* Répertoire de stockage.
*
* @var string
*/
protected $path;
/**
* La racine pour le répertoire de stockage.
*
* @var string
*/
protected $root = '';
/**
* Nom du schéma.
*
* @var string
*/
protected $name;
/**
* Chemin, nom et extension du schéma.
*
* @var string
*/
protected $file;
/**
* Schéma des tables.
*
* @var array
*/
protected $schema = [];
/**
* Construis l'objet avec une configuration.
*
* @param string $host Répertoire de stockage des données.
* @param string $name Nom du fichier contenant le schéma de base.
* @param DriverInterface $driver Interface de manipulation de données.
*/
public function __construct(
?string $host = null,
string $name = 'schema',
DriverInterface $driver = null
) {
if ($host !== null) {
$this->setConfig($host, $name, $driver);
}
}
/**
* Enregistre la configuration.
*
* @param string $host Répertoire de stockage des données.
* @param string $name Nom du fichier contenant le schéma de base.
* @param DriverInterface|null $driver Interface de manipulation de données.
*
* @return $this
*/
public function setConfig(
string $host,
string $name = 'schema',
DriverInterface $driver = null
): self {
$this->driver = $driver ?? new Driver\Json();
$this->path = $host;
$this->name = $name;
return $this;
}
/**
* Retourne le chemin relatif au répertoire de stockage.
*
* @return string
*/
public function getPath(): string
{
return $this->path;
}
/**
* Ajoute la racine du répertoire de stockage.
*
* @param string $root
*
* @return $this
*/
public function setPathRoot(string $root = ''): self
{
$this->root = $root;
return $this;
}
/**
* Modifie la valeur incrémentale d'une table.
*
* @param string $table Nom de la table.
* @param int $increment Tableau associatif des valeurs incrémentales.
*
* @throws TableNotFoundException
* @throws Exception
*
* @return bool Si le schéma d'incrémentaion est bien enregistré.
*/
public function setIncrement(string $table, int $increment): bool
{
if (!$this->hasTable($table)) {
throw new TableNotFoundException("Table $table is not exist.");
}
if (!isset($this->schema[ $table ][ 'increments' ])) {
throw new Exception("Table $table does not have an incremental value.");
}
$this->schema[ $table ][ 'increments' ] = $increment;
return $this->save($this->name, $this->schema);
}
/**
* Retourne la valeur incrémentale d'une table.
*
* @param string $table Nom de la table.
*
* @throws TableNotFoundException
* @throws Exception
*
* @return int
*/
public function getIncrement(string $table): int
{
if (!$this->hasTable($table)) {
throw new TableNotFoundException("Table $table is not exist.");
}
if ($this->schema[ $table ][ 'increments' ] === null) {
throw new Exception("Table $table does not have an incremental value.");
}
return $this->schema[ $table ][ 'increments' ];
}
/**
* Génère le schéma s'il n'existe pas en fonction du fichier de configuration.
*
* @return array Schéma de la base de données.
*/
public function getSchema(): array
{
if ($this->schema) {
return $this->schema;
}
$this->create($this->name);
$this->schema = $this->read($this->name);
return $this->schema;
}
/**
* Cherche le schéma de la table passée en paramètre.
*
* @param string $table Nom de la table.
*
* @throws TableNotFoundException
*
* @return array Schéma de la table.
*/
public function getSchemaTable(string $table): array
{
if (!$this->hasTable($table)) {
throw new TableNotFoundException("The $table table is missing in the schema.");
}
return $this->getSchema()[ $table ];
}
/**
* Supprime le schéma courant des données.
*
* @return $this
*/
public function dropSchema(): self
{
$schema = $this->getSchema();
/* Supprime les fichiers des tables. */
foreach (array_keys($schema) as $table) {
$this->delete($table);
}
/* Supprime le fichier de schéma. */
$this->delete($this->name);
/*
* Dans le cas ou le répertoire utilisé contient d'autre fichier
* (Si le répertoire contient que les 2 élements '.' et '..')
* alors nous le supprimons.
*/
$dir = scandir($this->root . $this->path);
if ($dir !== false && count($dir) == 2) {
rmdir($this->root . $this->path);
}
return $this;
}
/**
* Créer une référence dans le schéma et le fichier de la table.
*
* @param string $table Nom de la table.
* @param callable|null $callback fonction(TableBuilder $table) pour créer les champs.
*
* @throws Exception
*
* @return $this
*/
public function createTable(string $table, ?callable $callback = null): self
{
if ($this->hasTable($table)) {
throw new Exception("Table $table exist.");
}
$builder = self::tableBuilder($callback);
$this->schema[ $table ] = $builder->getTableSchema();
$this->save($this->name, $this->schema);
$this->create($table);
return $this;
}
/**
* Créer une référence dans le schéma et un fichier de données si ceux si n'existe pas.
*
* @param string $table Nom de la table.
* @param callable|null $callback fonction(TableBuilder $table) pour créer les champs.
*
* @return $this
*/
public function createTableIfNotExists(string $table, ?callable $callback = null): self
{
/* Créer la table si elle n'existe pas dans le schéma. */
if (!$this->hasTable($table)) {
$this->createTable($table, $callback);
} elseif (!$this->driver->has($this->root . $this->path, $table)) {
/* Si elle existe dans le schéma et que le fichier est absent alors on le créer. */
$this->create($table);
}
return $this;
}
/**
* Modifie les champs du schéma de données.
*
* @param string $table Nom de la table.
* @param callable $callback fonction(TableBuilder $table) pour créer les champs.
*
* @return $this
*/
public function alterTable(string $table, callable $callback): self
{
$schema = $this->getSchemaTable($table);
$fields = $schema[ 'fields' ];
$tableBuilder = self::tableAlterBuilder($callback)->build();
$dataTable = $this->read($table);
foreach ($tableBuilder as $name => $params) {
if (!isset($params[ 'opt' ])) {
self::filterFieldAdd($table, $fields, $name, $params[ 'type' ]);
self::add($schema, $dataTable, $name, $params);
} elseif ($params[ 'opt' ] === TableAlter::OPT_RENAME) {
self::filterFieldRename($table, $fields, $name, $params[ 'to' ]);
self::rename($schema, $dataTable, $name, $params[ 'to' ]);
} elseif ($params[ 'opt' ] === TableAlter::OPT_MODIFY) {
self::filterFieldModify($table, $fields, $name, $params[ 'type' ]);
self::modify($schema, $dataTable, $name, $params);
} elseif ($params[ 'opt' ] === TableAlter::OPT_DROP) {
self::filterFieldDrop($table, $fields, $name);
self::drop($schema, $dataTable, $name);
}
}
$this->schema[ $table ] = $schema;
$this->save($this->name, $this->schema);
$this->save($table, $dataTable);
return $this;
}
/**
* Retourne la valeur par defaut du champ passé en paramêtre.
*
* @param string $name Nom du champ.
* @param array $params Différente configurations.
*
* @throws ColumnsValueException
*
* @return mixed Valeur par defaut.
*/
public static function getValueDefault(string $name, array &$params)
{
if (isset($params[ 'default' ])) {
if ($params[ 'type' ] === TableBuilder::TYPE_DATE && $params[ 'default' ] === TableBuilder::CURRENT_DATE_DEFAULT) {
return date('Y-m-d', time());
}
if ($params[ 'type' ] === TableBuilder::TYPE_DATETIME && $params[ 'default' ] === TableBuilder::CURRENT_DATETIME_DEFAULT) {
return date('Y-m-d H:i:s', time());
}
/* Si les variables magiques ne sont pas utilisé alors la vrais valeur par defaut est retourné. */
return $params[ 'default' ];
}
if (isset($params[ 'nullable' ])) {
return null;
}
throw new ColumnsValueException("$name not nullable or not default.");
}
/**
* Détermine une table existe.
*
* @param string $table Nom de la table.
*
* @return bool Si le schéma de référence et le fichier de données existent.
*/
public function hasTable(string $table): bool
{
return isset($this->getSchema()[ $table ]) && $this->driver->has($this->root . $this->path, $table);
}
/**
* Détermine si une colonne existe.
*
* @param string $table Nom de la table.
* @param string $column Nom de la colonne.
*
* @return bool Si le schéma de référence et le fichier de données existent.
*/
public function hasColumn(string $table, string $column): bool
{
return isset($this->getSchema()[ $table ][ 'fields' ][ $column ]) && $this->driver->has($this->root . $this->path, $table);
}
/**
* Vide la table et initialise les champs incrémentaux.
*
* @param String $table Nom de la table.
*
* @throws TableNotFoundException
*
* @return bool
*/
public function truncateTable(string $table): bool
{
if (!$this->hasTable($table)) {
throw new TableNotFoundException("Table $table is not exist.");
}
$deleteSchema = true;
if ($this->schema[ $table ][ 'increments' ] !== null) {
$this->schema[ $table ][ 'increments' ] = 0;
$deleteSchema = $this->save($this->name, $this->schema);
}
$deleteData = $this->save($table, []);
return $deleteSchema && $deleteData;
}
/**
* Supprime du schéma la référence de la table et son fichier de données.
*
* @param string $table Nom de la table.
*
* @throws TableNotFoundException
*
* @return bool Si la suppression du schema et des données se son bien passé.
*/
public function dropTable(string $table): bool
{
if (!$this->hasTable($table)) {
throw new TableNotFoundException("Table $table is not exist.");
}
unset($this->schema[ $table ]);
$deleteData = $this->delete($table);
$deleteSchema = $this->save($this->name, $this->schema);
return $deleteSchema && $deleteData;
}
/**
* Supprime une table si elle existe.
*
* @param string $table Nom de la table.
*
* @return bool Si la table n'existe plus.
*/
public function dropTableIfExists(string $table): bool
{
return $this->hasTable($table) && $this->dropTable($table);
}
/**
* Utilisation du driver pour connaître l'extension de fichier utilisé.
*
* @return string Extension de fichier sans le '.'.
*/
public function getExtension(): string
{
return $this->driver->getExtension();
}
/**
* Utilisation du driver pour lire un fichier.
*
* @param string $file
*
* @return array le contenu du fichier
*/
public function read(string $file): array
{
return $this->driver->read($this->root . $this->path, $file);
}
/**
* Utilisation du driver pour enregistrer des données dans un fichier.
*
* @param string $file
* @param array $data
*
* @return bool
*/
public function save(string $file, array $data): bool
{
return $this->driver->save($this->root . $this->path, $file, $data);
}
/**
* Utilisation du driver pour créer un fichier.
*
* @param string $file
* @param array $data
*
* @return bool
*/
protected function create(string $file, array $data = []): bool
{
return $this->driver->create($this->root . $this->path, $file, $data);
}
/**
* Utilisation du driver pour supprimer un fichier.
*
* @param string $file
*
* @return bool
*/
protected function delete(string $file): bool
{
return $this->driver->delete($this->root . $this->path, $file);
}
/**
* Ajoute un champ dans les paramètre de la table et ses données.
*
* @param array $schema Schéma de la table.
* @param array $dataTable Les données de la table.
* @param string $name Nom du champ.
* @param array $params Nouveaux paramètres.
*
* @return void
*/
protected static function add(
array &$schema,
array &$dataTable,
string $name,
array $params
): void {
$schema[ 'fields' ][ $name ] = $params;
$increment = $params[ 'type' ] === TableBuilder::TYPE_INCREMENT
? 0
: null;
try {
$valueDefault = self::getValueDefault($name, $params);
} catch (ColumnsValueException $e) {
$valueDefault = '';
}
foreach ($dataTable as &$data) {
$data[ $name ] = $increment === null
? $valueDefault
: ++$increment;
}
if ($params[ 'type' ] === TableBuilder::TYPE_INCREMENT) {
$schema[ 'increments' ] = $increment;
}
}
/**
* Modifie un champ dans les paramètre de la table et ses données.
*
* @param array $schema Schéma de la table.
* @param array $dataTable Les données de la table.
* @param string $name Nom du champ.
* @param array $params Nouveaux paramètres.
*
* @return void
*/
protected static function modify(
array &$schema,
array &$dataTable,
string $name,
array $params
): void {
unset($params[ 'opt' ]);
$schema[ 'fields' ][ $name ] = $params;
$increment = $params[ 'type' ] === TableBuilder::TYPE_INCREMENT
? 0
: null;
try {
$valueDefault = self::getValueDefault($name, $params);
foreach ($dataTable as &$data) {
$data[ $name ] = $valueDefault;
}
} catch (ColumnsValueException $e) {
}
if ($params[ 'type' ] === TableBuilder::TYPE_INCREMENT) {
$schema[ 'increments' ] = $increment;
}
}
/**
* Renomme un champ dans les paramètre de la table et ses données.
*
* @param array $schema Les champs de la table.
* @param array $dataTable Les données de la table.
* @param string $name Nom du champ.
* @param string $to Nouveau nom du champ.
*
* @return void
*/
protected static function rename(
array &$schema,
array &$dataTable,
string $name,
string $to
): void {
$schema[ 'fields' ][ $to ] = $schema[ 'fields' ][ $name ];
unset($schema[ 'fields' ][ $name ]);
foreach ($dataTable as &$data) {
$data[ $to ] = $data[ $name ];
unset($data[ $name ]);
}
}
/**
* Supprime un champ dans les paramètre de la table et ses données.
*
* @param array $schema Les champs de la table.
* @param array $dataTable Les données de la table.
* @param string $name Nom du champ.
*
* @return void
*/
protected static function drop(
array &$schema,
array &$dataTable,
string $name
): void {
foreach (array_keys($dataTable) as $key) {
unset($dataTable[ $key ][ $name ]);
}
if ($schema[ 'fields' ][ $name ][ 'type' ] === TableBuilder::TYPE_INCREMENT) {
$schema[ 'increments' ] = null;
}
unset($schema[ 'fields' ][ $name ]);
}
/**
* Retour true si l'un des champs est de type incrementale.
*
* @param array $fields
*
* @return bool
*/
protected static function isFieldIncrement(array $fields): bool
{
foreach ($fields as $field) {
if ($field[ 'type' ] === TableBuilder::TYPE_INCREMENT) {
return true;
}
}
return false;
}
/**
* Passe en premier paramètre d'une fonction anonyme un objet TableBuilder et le retourne.
*
* @param callable $callback Fonction anonyme.
*
* @return TableBuilder
*/
protected static function tableAlterBuilder(callable $callback): TableBuilder
{
$builder = new TableAlter();
call_user_func_array($callback, [ &$builder ]);
return $builder;
}
/**
* Passe en premier paramètre d'une fonction anonyme un objet TableBuilder et le retourne.
*
* @param callable|null $callback Fonction anonyme.
*
* @return TableBuilder
*/
protected static function tableBuilder(?callable $callback = null): TableBuilder
{
$builder = new TableBuilder();
if ($callback !== null) {
call_user_func_array($callback, [ &$builder ]);
}
return $builder;
}
/**
* Vérifie si les opérations du champ sont conformes.
*
* @param string $table Nom de la table.
* @param array $fields Paramètres du champ en base.
* @param string $name Nom du champ.
* @param string $type Type de donnée.
*
* @throws Exception
* @throws ColumnsNotFoundException
*/
private static function filterFieldAdd(
string $table,
array $fields,
string $name,
string $type
): void {
/* Si un champ est ajouté il ne doit pas exister dans le schéma. */
if (isset($fields[ $name ])) {
throw new Exception("$name field does not exists in $table table.");
}
if ($type === TableBuilder::TYPE_INCREMENT && self::isFieldIncrement($fields)) {
throw new ColumnsValueException(
"The $table table can not have multiple incremental values."
);
}
}
/**
* @param string $table Nom de la table.
* @param array $fields Paramètres du champ en base.
* @param string $name Nom du champ.
* @param string $type Type de donnée.
*
* @throws ColumnsNotFoundException
* @throws ColumnsValueException
* @throws Exception
*/
private static function filterFieldModify(
string $table,
array $fields,
string $name,
string $type
): void {
if (!isset($fields[ $name ])) {
throw new ColumnsNotFoundException(
"$name field does not exists in $table table."
);
}
if ($type === TableBuilder::TYPE_INCREMENT && self::isFieldIncrement($fields)) {
throw new ColumnsValueException(
"The $table table can not have multiple incremental values."
);
}
/* Si le type change, les données présents doivent être d'un type équivalent. */
$modifyNumber = in_array($type, [ 'integer', 'float', 'increments' ]) &&
!in_array($fields[ $name ][ 'type' ], [ 'integer', 'float', 'increments' ]);
$modifyString = in_array($type, [ 'text', 'string', 'char' ]) &&
!in_array($fields[ $name ][ 'type' ], [ 'text', 'string', 'char' ]);
$modifyDate = in_array($type, [ 'date', 'datetime' ]) &&
!in_array($fields[ $name ][ 'type' ], [ 'date', 'datetime', 'string', 'text' ]);
if ($modifyString || $modifyNumber || $modifyDate) {
throw new Exception("The $name column type {$fields[ $name ][ 'type' ]} can not be changed with the $type type");
}
}
/**
* @param string $table Nom de la table.
* @param array $fields Paramètres du champ en base.
* @param string $name Nom du champ.
* @param string $to Nouveau nom du champ.
*
* @throws ColumnsNotFoundException
* @throws Exception
*/
private static function filterFieldRename(
string $table,
array $fields,
string $name,
string $to
): void {
if (!isset($fields[ $name ])) {
throw new ColumnsNotFoundException(
"$name field does not exists in $table table."
);
}
/* Si le champ à renommer existe dans le schema. */
if (isset($fields[ $to ])) {
throw new Exception(
"$name field does exists in $table table."
);
}
}
/**
* @param string $table Nom de la table.
* @param array $fields Paramètres du champ en base.
* @param string $name Nom du champ.
*
* @throws ColumnsNotFoundException
*
* @return void
*/
private static function filterFieldDrop(
string $table,
array $fields,
string $name
): void {
if (!isset($fields[ $name ])) {
throw new ColumnsNotFoundException(
"$name field does not exists in $table table."
);
}
}
}