/
SchemaYamlParser.php
649 lines (582 loc) · 21.9 KB
/
SchemaYamlParser.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
<?php
/**
* This file is part of the LdapTools package.
*
* (c) Chad Sikorra <Chad.Sikorra@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LdapTools\Schema\Parser;
use LdapTools\Connection\LdapControl;
use LdapTools\Exception\SchemaParserException;
use LdapTools\Operation\QueryOperation;
use LdapTools\Schema\LdapObjectSchema;
use LdapTools\Utilities\ArrayToOperator;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;
/**
* Parses a schema definition from a YAML file.
*
* @author Chad Sikorra <Chad.Sikorra@gmail.com>
*/
class SchemaYamlParser implements SchemaParserInterface
{
/**
* The valid directives for the schema.
*
* @internal
*/
const SCHEMA_DIRECTIVES = [
'extends',
'extends_default',
'include',
'include_default',
'objects',
];
/**
* The valid directives for the schema objects.
*
* @internal
*/
const SCHEMA_OBJECT_DIRECTIVES = [
'attributes',
'attributes_to_select',
'base_dn',
'class',
'category',
'controls',
'converters',
'converter_options',
'default_container',
'default_values',
'extends',
'extends_default',
'filter',
'multivalued_attributes',
'repository',
'required_attributes',
'paging',
'rdn',
'scope',
'type',
];
/**
* @var array Schema names to their YAML mappings (ie. ['ad' => [ <yaml array> ]])
*/
protected $schemas = [];
/**
* @var string The folder where the schema files are located.
*/
protected $schemaFolder = '';
/**
* @var string The folder where the default schema files reside.
*/
protected $defaultSchemaFolder = '';
/**
* @var array
*/
protected $optionMap = [
'class' => 'setObjectClass',
'category' => 'setObjectCategory',
'attributes_to_select' => 'setAttributesToSelect',
'repository' => 'setRepository',
'default_values' => 'setDefaultValues',
'required_attributes' => 'setRequiredAttributes',
'default_container' => 'setDefaultContainer',
'multivalued_attributes' => 'setMultivaluedAttributes',
'base_dn' => 'setBaseDn',
'paging' => 'setUsePaging',
'scope' => 'setScope',
'rdn' => 'setRdn',
];
/**
* @var array
*/
protected $normalizer = [
'rdn' => 'normalizeToArray',
];
/**
* @var ArrayToOperator
*/
protected $arrayToOp;
/**
* @param string $schemaFolder
*/
public function __construct($schemaFolder)
{
$this->schemaFolder = $schemaFolder;
$this->defaultSchemaFolder = __DIR__.'/../../../../resources/schema';
$this->arrayToOp = new ArrayToOperator();
}
/**
* Given the schema name, return the last time the schema was modified in DateTime format.
*
* @param string $schemaName
* @return \DateTime
* @throws SchemaParserException
*/
public function getSchemaModificationTime($schemaName)
{
return new \DateTime('@'.filemtime($this->getSchemaFileName($this->schemaFolder, $schemaName)));
}
/**
* {@inheritdoc}
*/
public function parse($schemaName, $objectType)
{
$this->parseSchemaNameToArray($schemaName);
return $this->parseYamlForObject($this->schemas[$this->schemaFolder][$schemaName], $schemaName, $objectType);
}
/**
* {@inheritdoc}
*/
public function parseAll($schemaName)
{
$this->parseSchemaNameToArray($schemaName);
$types = [];
$ldapObjectSchemas = [];
if (isset($this->schemas[$this->schemaFolder][$schemaName]['objects'])) {
$types = array_column($this->schemas[$this->schemaFolder][$schemaName]['objects'], 'type');
}
foreach ($types as $type) {
$ldapObjectSchemas[] = $this->parseYamlForObject(
$this->schemas[$this->schemaFolder][$schemaName],
$schemaName,
$type
);
}
return $ldapObjectSchemas;
}
/**
* Attempt to find the object type definition in the schema and create its object representation.
*
* @param array $schema
* @param string $schemaName
* @param string $objectType
* @return LdapObjectSchema
* @throws SchemaParserException
*/
protected function parseYamlForObject(array $schema, $schemaName, $objectType)
{
$objectSchema = $this->getObjectFromSchema($schema, $objectType);
$objectSchema = $this->mergeAnyExtendedSchemas($objectSchema, $schemaName);
$objectSchema = $this->cleanObjectArray($objectSchema);
$this->updateObjectArray($schemaName, $objectSchema);
$this->validateObjectDirectives($schemaName, $objectType, $objectSchema);
$ldapObjectSchema = new LdapObjectSchema($schemaName, $objectSchema['type']);
foreach ($this->optionMap as $option => $setter) {
if (!array_key_exists($option, $objectSchema)) {
continue;
}
$value = $objectSchema[$option];
if (array_key_exists($option, $this->normalizer)) {
$value = $this->{$this->normalizer[$option]}($value);
}
$ldapObjectSchema->$setter($value);
}
$this->parseConverterOptions($ldapObjectSchema, $objectSchema);
$ldapObjectSchema->setFilter($this->parseFilter($ldapObjectSchema, $objectSchema));
$ldapObjectSchema->setAttributeMap(isset($objectSchema['attributes']) ? $objectSchema['attributes'] : []);
$ldapObjectSchema->setConverterMap($this->parseConverterMap($objectSchema));
$ldapObjectSchema->setControls(...$this->parseControls($objectSchema));
$this->validateObjectSchema($ldapObjectSchema);
return $ldapObjectSchema;
}
/**
* @param string $schemaName
* @throws SchemaParserException
*/
protected function validateSchemaDirectives($schemaName)
{
if (!array_key_exists('objects', $this->schemas[$this->schemaFolder][$schemaName])) {
throw new SchemaParserException(sprintf(
'Cannot find the "objects" section in the schema "%s" in "%s".',
$schemaName,
$this->schemaFolder
));
}
$unrecognized = array_keys(array_diff_key($this->schemas[$this->schemaFolder][$schemaName], array_flip(self::SCHEMA_DIRECTIVES)));
if (!empty($unrecognized)) {
throw new SchemaParserException(sprintf(
'Unrecognized directive(s) for schema "%s": %s. Valid directives are: %s',
$schemaName,
implode(', ', $unrecognized),
implode(', ',self::SCHEMA_DIRECTIVES)
));
}
}
/**
* @param string $schemaName
* @param string $objectType
* @param array $schemaObject
* @throws SchemaParserException
*/
protected function validateObjectDirectives($schemaName, $objectType, array $schemaObject)
{
$unrecognized = array_keys(array_diff_key($schemaObject, array_flip(self::SCHEMA_OBJECT_DIRECTIVES)));
if (!empty($unrecognized)) {
throw new SchemaParserException(sprintf(
'Unrecognized directive(s) for schema "%s" type "%s": %s. Valid directives are: %s',
$schemaName,
$objectType,
implode(', ', $unrecognized),
implode(', ',self::SCHEMA_OBJECT_DIRECTIVES)
));
}
}
/**
* Validates some of the schema values to check that they are allowed.
*
* @param LdapObjectSchema $schema
* @param array $schemaArray
* @throws SchemaParserException
*/
protected function validateSchemaType(LdapObjectSchema $schema, array $schemaArray)
{
if (!((bool)count(array_filter(array_keys($schemaArray['attributes']), 'is_string')))) {
throw new SchemaParserException('The attributes for a schema should be an associative array.');
}
if ($schema->getScope() && !in_array($schema->getScope(), QueryOperation::SCOPE)) {
throw new SchemaParserException(sprintf(
'The scope "%s" is not valid. Valid types are: %s',
$schema->getScope(),
implode(', ', QueryOperation::SCOPE)
));
}
}
/**
* Check for a specific object type in the schema and validate it.
*
* @param array $schema
* @param string $objectType
* @return array
* @throws SchemaParserException
*/
protected function getObjectFromSchema(array $schema, $objectType)
{
$objectSchema = null;
foreach ($schema['objects'] as $ldapObject) {
if (array_key_exists('type', $ldapObject) && strtolower($ldapObject['type']) == strtolower($objectType)) {
$objectSchema = $ldapObject;
}
}
if (is_null($objectSchema)) {
throw new SchemaParserException(sprintf('Cannot find object type "%s" in schema.', $objectType));
}
return $objectSchema;
}
/**
* Update the object in the schema array in case it extended a different object type.
*
* @param string $schemaName
* @param array $schemaObject
*/
protected function updateObjectArray($schemaName, $schemaObject)
{
foreach ($this->schemas[$this->schemaFolder][$schemaName]['objects'] as $name => $value) {
if (array_key_exists('type', $value) && $value['type'] == $schemaObject['type']) {
$this->schemas[$this->schemaFolder][$schemaName]['objects'][$name] = $schemaObject;
}
}
}
/**
* Removes certain keys so they don't get parsed again.
*
* @param array $schemaObject
* @return array
*/
protected function cleanObjectArray(array $schemaObject)
{
unset($schemaObject['extends']);
unset($schemaObject['extends_default']);
return $schemaObject;
}
/**
* Parse the converters section of an object schema definition to generate the attribute converter map.
*
* @param array $objectSchema
* @return array
*/
protected function parseConverterMap(array $objectSchema)
{
$converterMap = [];
if (array_key_exists('converters', $objectSchema)) {
foreach ($objectSchema['converters'] as $converter => $attributes) {
if (is_array($attributes)) {
foreach ($attributes as $attribute) {
$converterMap[$attribute] = $converter;
}
} elseif (is_string($attributes)) {
$converterMap[$attributes] = $converter;
}
}
}
return $converterMap;
}
/**
* Get the filter for the schema object.
*
* @param LdapObjectSchema $objectSchema
* @param array $objectArray
* @return \LdapTools\Query\Operator\BaseOperator
* @throws SchemaParserException
*/
protected function parseFilter(LdapObjectSchema $objectSchema, array $objectArray)
{
$filter = array_key_exists('filter', $objectArray) ? $objectArray['filter'] : [];
if (empty($filter) && empty($objectSchema->getObjectClass()) && empty($objectSchema->getObjectCategory())) {
throw new SchemaParserException(sprintf(
'Object type "%s" must have one of the following defined: %s',
$objectSchema->getObjectType(),
implode(', ', ['class', 'category', 'filter'])
));
}
return $this->arrayToOp->getOperatorForSchema($objectSchema, $filter);
}
/**
* @param array $objectSchema
* @return LdapControl[]
* @throws SchemaParserException
*/
protected function parseControls($objectSchema)
{
$controls = [];
if (array_key_exists('controls', $objectSchema)) {
foreach ($objectSchema['controls'] as $control) {
if (!is_array($control)) {
throw new SchemaParserException('The "controls" directive must contain arrays of controls.');
}
$controls[] = new LdapControl(...$control);
}
}
return $controls;
}
/**
* @param LdapObjectSchema $schema
* @param array $arraySchema
*/
protected function parseConverterOptions(LdapObjectSchema $schema, array $arraySchema)
{
if (!isset($arraySchema['converter_options'])) {
return;
}
foreach ($arraySchema['converter_options'] as $converter => $attributes) {
foreach ($attributes as $attribute => $options) {
$schema->setConverterOptions($converter, $attribute, $options);
}
}
}
/**
* Validate that an object schema meets the minimum requirements.
*
* @param LdapObjectSchema $schema
* @throws SchemaParserException
*/
protected function validateObjectSchema($schema)
{
if (empty($schema->getAttributeMap())) {
throw new SchemaParserException(sprintf('Object type "%s" has no attributes defined.', $schema->getObjectType()));
} elseif (!((bool)count(array_filter(array_keys($schema->getAttributeMap()), 'is_string')))) {
throw new SchemaParserException('The attributes for a schema should be an associative array.');
}
if ($schema->getScope() && !in_array($schema->getScope(), QueryOperation::SCOPE)) {
throw new SchemaParserException(sprintf(
'The scope "%s" is not valid. Valid types are: %s',
$schema->getScope(),
implode(', ', QueryOperation::SCOPE)
));
}
}
/**
* Given a schema name, parse it into the array.
*
* @param string $schemaName
* @throws SchemaParserException
*/
protected function parseSchemaNameToArray($schemaName)
{
if (!isset($this->schemas[$this->schemaFolder][$schemaName])) {
$file = $this->getSchemaFileName($this->schemaFolder, $schemaName);
try {
$this->schemas[$this->schemaFolder][$schemaName] = Yaml::parse(file_get_contents($file));
} catch (ParseException $e) {
throw new SchemaParserException(sprintf('Error in configuration file: %s', $e->getMessage()));
}
$this->mergeDefaultSchemaFile($schemaName);
$this->mergeIncludedSchemas($schemaName);
$this->validateSchemaDirectives($schemaName);
}
}
/**
* If the 'include' directive is used, then merge the specified schemas into the current one.
*
* @param string $schemaName
* @throws SchemaParserException
*/
protected function mergeIncludedSchemas($schemaName)
{
$include = ['include' => [], 'include_default' => []];
foreach (array_keys($include) as $key) {
if (isset($this->schemas[$this->schemaFolder][$schemaName][$key])) {
$include[$key] = $this->schemas[$this->schemaFolder][$schemaName][$key];
$include[$key] = is_array($include[$key]) ? $include[$key] : [$include[$key]];
}
}
foreach ($include['include'] as $schema) {
$this->parseAll($schema);
$this->schemas[$this->schemaFolder][$schemaName]['objects'] = array_merge(
$this->schemas[$this->schemaFolder][$schemaName]['objects'],
$this->schemas[$this->schemaFolder][$schema]['objects']
);
}
$folder = $this->schemaFolder;
$this->schemaFolder = $this->defaultSchemaFolder;
foreach ($include['include_default'] as $schema) {
$this->parseAll($schema);
$this->schemas[$folder][$schemaName]['objects'] = array_merge(
$this->schemas[$folder][$schemaName]['objects'],
$this->schemas[$this->schemaFolder][$schema]['objects']
);
}
$this->schemaFolder = $folder;
}
/**
* If the 'extends_default' directive is used, then merge the specified default schema.
*
* @param string $schemaName
* @throws SchemaParserException
*/
protected function mergeDefaultSchemaFile($schemaName)
{
if (!isset($this->schemas[$this->schemaFolder][$schemaName]['extends_default'])) {
return;
}
$defaultSchemaName = $this->schemas[$this->schemaFolder][$schemaName]['extends_default'];
$folder = $this->schemaFolder;
$this->schemaFolder = $this->defaultSchemaFolder;
$this->parseAll($defaultSchemaName);
// Perhaps an option at some point to specify the merge action/type? ie. replace vs merge.
$this->schemas[$folder][$schemaName] = array_merge_recursive(
$this->schemas[$this->schemaFolder][$defaultSchemaName],
$this->schemas[$folder][$schemaName]
);
$this->schemaFolder = $folder;
}
/**
* If the 'extends' option is given, then merge this schema object with the requested schema object.
*
* @param array $objectSchema
* @param string $schemaName
* @return array
* @throws SchemaParserException
*/
protected function mergeAnyExtendedSchemas(array $objectSchema, $schemaName)
{
if (!(isset($objectSchema['extends']) || isset($objectSchema['extends_default']))) {
return $objectSchema;
}
return $this->mergeSchemaObjectArrays($this->getParentSchemaObject($objectSchema, $schemaName), $objectSchema);
}
/**
* Performs the logic for merging one schema object array with another.
*
* @param array $parent The parent schema object being extended.
* @param array $schema The base schema object being defined.
* @return array
*/
protected function mergeSchemaObjectArrays($parent, $schema)
{
// Directives used that exist in the schema being extended, that are arrays, should be merged.
foreach (array_intersect_key($schema, $parent) as $key => $value) {
# Simple merge on non-multidimensional arrays...
if (is_array($value) && count($value) === count($value, COUNT_RECURSIVE)) {
$schema[$key] = array_merge($parent[$key], $value);
# Recursive merge on multidimensional arrays...
} elseif (is_array($value)) {
$schema[$key] = array_merge_recursive($parent[$key], $value);
}
}
// Directives in the parent that have not been defined should be added.
return array_replace($schema, array_diff_key($parent, $schema));
}
/**
* If we need to retrieve one of the default schemas, then it's probably the case that the schema folder path was
* manually defined. So retrieve the default schema object by parsing the name from the default folder path and then
* reset the schema folder back to what it originally was.
*
* @param array $objectSchema
* @return array
* @throws SchemaParserException
*/
protected function getExtendedDefaultSchemaObject(array $objectSchema)
{
if (!(is_array($objectSchema['extends_default']) && 2 == count($objectSchema['extends_default']))) {
throw new SchemaParserException('The "extends_default" directive should be an array with exactly 2 values.');
}
$folder = $this->schemaFolder;
$this->schemaFolder = $this->defaultSchemaFolder;
$this->parseAll(reset($objectSchema['extends_default']));
$parent = $this->getObjectFromSchema(
$this->schemas[$this->defaultSchemaFolder][$objectSchema['extends_default'][0]],
$objectSchema['extends_default'][1]
);
$this->schemaFolder = $folder;
return $parent;
}
/**
* Determines what parent array object to get based on the directive used.
*
* @param array $objectSchema
* @param string $schemaName
* @return array
* @throws SchemaParserException
*/
protected function getParentSchemaObject(array $objectSchema, $schemaName)
{
if (isset($objectSchema['extends_default'])) {
$parent = $this->getExtendedDefaultSchemaObject($objectSchema);
} elseif (isset($objectSchema['extends']) && is_string($objectSchema['extends'])) {
$parent = $this->getObjectFromSchema($this->schemas[$this->schemaFolder][$schemaName], $objectSchema['extends']);
} elseif (isset($objectSchema['extends']) && is_array($objectSchema['extends']) && 2 == count($objectSchema['extends'])) {
$name = reset($objectSchema['extends']);
$type = $objectSchema['extends'][1];
$this->parseAll($name);
$parent = $this->getObjectFromSchema($this->schemas[$this->schemaFolder][$name], $type);
} else {
throw new SchemaParserException('The directive "extends" must be a string or array with exactly 2 values.');
}
return $parent;
}
/**
* Check for a YML file of the specified schema name and return the full path.
*
* @param string $folder
* @param string $schema
* @return string
* @throws SchemaParserException
*/
protected function getSchemaFileName($folder, $schema)
{
$file = null;
foreach (['yml', 'yaml'] as $ext) {
$fileCheck = $folder.'/'.$schema.'.'.$ext;
if (is_readable($fileCheck)) {
$file = $fileCheck;
break;
}
}
if (is_null($file)) {
throw new SchemaParserException(sprintf('Cannot find schema for "%s" in "%s"', $schema, $folder));
}
return $file;
}
/**
* @param mixed $value
* @return array
*/
protected function normalizeToArray($value)
{
return is_array($value) ? $value : [$value];
}
}