forked from formapro/JsFormValidatorBundle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsFormValidatorFactory.php
More file actions
587 lines (526 loc) · 16.5 KB
/
JsFormValidatorFactory.php
File metadata and controls
587 lines (526 loc) · 16.5 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
<?php
namespace Fp\JsFormValidatorBundle\Factory;
use Fp\JsFormValidatorBundle\Exception\UndefinedFormException;
use Fp\JsFormValidatorBundle\Form\Constraint\UniqueEntity;
use Fp\JsFormValidatorBundle\Model\JsConfig;
use Fp\JsFormValidatorBundle\Model\JsFormElement;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\GetterMetadata;
use Symfony\Component\Validator\Mapping\PropertyMetadata;
use Symfony\Component\Validator\ValidatorInterface;
/**
* This factory uses to parse a form to a tree of JsFormElement's
*
* Class JsFormValidatorFactory
*
* @package Fp\JsFormValidatorBundle\Factory
*/
class JsFormValidatorFactory
{
/**
* @var ValidatorInterface
*/
protected $validator;
/**
* @var TranslatorInterface
*/
protected $translator;
/**
* @var \Symfony\Component\Routing\Generator\UrlGeneratorInterface
*/
protected $router;
/**
* @var array
*/
protected $config = array();
/**
* @var Form[]
*/
protected $queue = array();
/**
* @var Form
*/
protected $currentElement = null;
/**
* @var string
*/
protected $transDomain;
/**
* @param ValidatorInterface $validator
* @param TranslatorInterface $translator
* @param \Symfony\Component\Routing\Generator\UrlGeneratorInterface $router
* @param array $config
* @param string $domain
*/
public function __construct(
ValidatorInterface $validator,
TranslatorInterface $translator,
$router,
$config,
$domain
) {
$this->validator = $validator;
$this->translator = $translator;
$this->router = $router;
$this->config = $config;
$this->transDomain = $domain;
}
/**
* Gets metadata from system using the entity class name
*
* @param string $className
*
* @return ClassMetadata
* @codeCoverageIgnore
*/
protected function getMetadataFor($className)
{
return $this->validator->getMetadataFactory()->getMetadataFor($className);
}
/**
* Translate a single message
*
* @param string $message
*
* @return string
* @codeCoverageIgnore
*/
protected function translateMessage($message)
{
return $this->translator->trans($message, array(), $this->transDomain);
}
/**
* Generate an URL from the route
*
* @param string $route
*
* @return string
* @codeCoverageIgnore
*/
protected function generateUrl($route)
{
return $this->router->generate($route);
}
/**
* Get Config
*
* @param null|string $name
*
* @return mixed
*/
public function getConfig($name = null)
{
if ($name) {
return isset($this->config[$name]) ? $this->config[$name] : null;
} else {
return $this->config;
}
}
public function createJsConfigModel()
{
$result = array();
if (!empty($this->config['routing'])) {
foreach ($this->config['routing'] as $param => $value) {
try {
$result['routing'][$param] = $this->generateUrl($value);
} catch (\Exception $e) {
$result['routing'][$param] = null;
}
}
}
$model = new JsConfig;
$model->routing = $result['routing'];
return $model;
}
/**
* Returns the current queue
*
* @return \Symfony\Component\Form\Form[]
*/
public function getQueue()
{
return $this->queue;
}
/**
* Add a new form to processing queue
*
* @param \Symfony\Component\Form\Form $form
*
* @return array
*/
public function addToQueue(Form $form)
{
$this->queue[$form->getName()] = $form;
}
/**
* Check if form is already in queue
*
* @param Form $form
*
* @return bool
*/
public function inQueue(Form $form)
{
return isset($this->queue[$form->getName()]);
}
/**
* Removes from the queue elements which are not parent forms and should not be processes
*
* @return $this
*/
public function siftQueue()
{
foreach ($this->queue as $name => $form) {
$blockName = $form->getConfig()->getOption('block_name');
if ('_token' == $name || 'entry' == $blockName || $form->getParent()) {
unset($this->queue[$name]);
}
}
return $this;
}
/**
* @return JsFormElement[]
*/
public function processQueue()
{
$result = array();
foreach ($this->queue as $form) {
if (null !== ($model = $this->createJsModel($form))) {
$result[] = $model;
}
};
$this->queue = array();
return $result;
}
/**
* The main function that creates nested model
*
* @param Form $form
*
* @return null|JsFormElement
*/
public function createJsModel(Form $form)
{
$this->currentElement = $form;
$conf = $form->getConfig();
// If field is disabled or has no any validations
if (false === $conf->getOption('js_validation')) {
return null;
}
$model = new JsFormElement;
$model->id = $this->getElementId($form);
$model->name = $form->getName();
$model->type = $conf->getType()->getInnerType()->getName();
$model->invalidMessage = $conf->getOption('invalid_message');
$model->transformers = $this->parseTransformers($form->getConfig()->getViewTransformers());
$model->cascade = $conf->getOption('cascade_validation');
$model->bubbling = $conf->getOption('error_bubbling');
$model->data = $this->getValidationData($form);
$model->children = $this->processChildren($form);
$prototype = $form->getConfig()->getAttribute('prototype');
if ($prototype) {
$model->prototype = $this->createJsModel($prototype);
}
// Return self id to add it as child to the parent model
return $model;
}
/**
* Create the JsFormElement for all the children of specified element
*
* @param null|Form $form
*
* @return array
*/
protected function processChildren($form)
{
$result = array();
// If this field has children - process them
foreach ($form as $name => $child) {
if ($this->isProcessableElement($child)) {
$childModel = $this->createJsModel($child);
if (null !== $childModel) {
$result[$name] = $childModel;
}
}
}
return $result;
}
/**
* Generate an Id for the element by merging the current element name
* with all the parents names
*
* @param Form $form
*
* @return string
*/
protected function getElementId(Form $form)
{
/** @var Form $parent */
$parent = $form->getParent();
if (null !== $parent) {
return $this->getElementId($parent) . '_' . $form->getName();
} else {
return $form->getName();
}
}
/**
* @param Form $form
*
* @return array
*/
protected function getValidationData(Form $form)
{
// If parent has metadata
$parent = $form->getParent();
if ($parent && null !== $parent->getConfig()->getDataClass()) {
$classMetadata = $metadata = $this->getMetadataFor($parent->getConfig()->getDataClass());
if ($classMetadata->hasMemberMetadatas($form->getName())) {
$metadata = $classMetadata->getMemberMetadatas($form->getName());
/** @var PropertyMetadata $item */
foreach ($metadata as $item) {
$this->composeValidationData(
$parentData,
$item->getConstraints(),
$getters = !empty($item->getters) ? (array)$item->getters : array()
);
}
}
}
// If has own metadata
if (null !== $form->getConfig()->getDataClass()) {
$metadata = $this->getMetadataFor($form->getConfig()->getDataClass());
$this->composeValidationData(
$ownData,
$metadata->getConstraints(),
$getters = !empty($metadata->getters) ? (array)$metadata->getters : array()
);
}
// If has constraints in a form element
$this->composeValidationData(
$formData,
(array)$form->getConfig()->getOption('constraints'),
array()
);
$result = array();
$groups = $this->getValidationGroups($form);
if (!empty($parentData)) {
$parentData['groups'] = $this->getValidationGroups($parent);
$result['parent'] = $parentData;
}
if (!empty($ownData)) {
$ownData['groups'] = $groups;
$result['entity'] = $ownData;
}
if (!empty($formData)) {
$formData['groups'] = $groups;
$result['form'] = $formData;
}
return $result;
}
protected function mergeDataRecursive(array $array1, array $array2)
{
foreach ($array2 as $key => $value) {
if (empty($array1[$key])) {
$array1[$key] = $value;
} elseif (is_array($value)) {
if ((array_keys($value) !== range(0, count($value) - 1))) {
$array1[$key] = $this->mergeDataRecursive($array1[$key], $value);
} else {
$array1[$key] = array_merge($array1[$key], $value);
}
} else {
$array1[$key] = $value;
}
}
return $array1;
}
/**
* @param array $container
* @param Constraint[] $constraints
* @param GetterMetadata[] $getters
*
* @return void
*/
public function composeValidationData(&$container, $constraints, $getters)
{
if (null == $container) {
$container = array();
}
if ($getters) {
if (!isset($container['getters'])) {
$container['getters'] = array();
}
$container['getters'] = array_merge($container['getters'], $this->parseGetters($getters));
}
if ($constraints) {
if (!isset($container['constraints'])) {
$container['constraints'] = array();
}
$container['constraints'] = array_merge($container['constraints'], $this->parseConstraints($constraints));
}
}
/**
* Get validation groups for the specified form
*
* @param Form|FormInterface $form
*
* @return array|string
*/
protected function getValidationGroups(Form $form)
{
$result = array('Default');
$groups = $form->getConfig()->getOption('validation_groups');
if (empty($groups)) {
// Try to get groups from a parent
if ($form->getParent()) {
$result = $this->getValidationGroups($form->getParent());
}
} elseif (is_array($groups)) {
// If groups is an array - return groups as is
$result = $groups;
} elseif ($groups instanceof \Closure) {
// If groups is a Closure - return the form class name to look for javascript
$result = $this->getElementId($form);
}
return $result;
}
/**
* Not all elements should be processed by thy factory (e.g. buttons, hidden inputs etc)
*
* @param mixed $element
*
* @return bool
*/
protected function isProcessableElement($element)
{
return ($element instanceof Form)
&& ('hidden' !== $element->getConfig()->getType()->getName());
}
/**
* Convert transformers objects to data arrays
*
* @param array $transformers
*
* @return array
*/
protected function parseTransformers(array $transformers)
{
$result = array();
foreach ($transformers as $trans) {
$item = array();
$reflect = new \ReflectionClass($trans);
$properties = $reflect->getProperties();
foreach ($properties as $prop) {
$item[$prop->getName()] = $this->getTransformerParam($trans, $prop->getName());
}
$item['name'] = get_class($trans);
$result[] = $item;
}
return $result;
}
/**
* Get the specified non-public transformer property
*
* @param DataTransformerInterface $transformer
* @param string $paramName
*
* @return mixed
*/
protected function getTransformerParam(DataTransformerInterface $transformer, $paramName)
{
$reflection = new \ReflectionProperty($transformer, $paramName);
$reflection->setAccessible(true);
$value = $reflection->getValue($transformer);
$result = null;
if ('transformers' === $paramName && is_array($value)) {
$result = $this->parseTransformers($value);
} elseif (is_scalar($value) || is_array($value)) {
$result = $value;
} elseif ($value instanceof ChoiceListInterface) {
$result = $value->getChoices();
}
return $result;
}
/**
* Converts list of the GetterMetadata objects to a data array
*
* @param GetterMetadata[] $getters
*
* @return array
*/
protected function parseGetters(array $getters)
{
$result = array();
foreach ($getters as $getter) {
$result[$getter->getName()] = $this->parseConstraints((array)$getter->getConstraints());
}
return $result;
}
/**
* Converts list of constraints objects to a data array
*
* @param array $constraints
*
* @return array
*/
protected function parseConstraints(array $constraints)
{
$result = array();
foreach ($constraints as $item) {
// Translate messages if need and add to result
foreach ($item as $propName => $propValue) {
if (false !== strpos(strtolower($propName), 'message')) {
$item->{$propName} = $this->translateMessage($propValue);
}
}
if ($item instanceof \Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity) {
$item = new UniqueEntity($item, $this->currentElement->getConfig()->getDataClass());
}
$result[get_class($item)][] = $item;
}
return $result;
}
public function getJsConfigString()
{
return '<script type="text/javascript">FpJsFormValidator.config = ' . $this->createJsConfigModel() . ';</script>';
}
/**
* @param string $formName
* @param bool $onLoad
*
* @throws \Fp\JsFormValidatorBundle\Exception\UndefinedFormException
* @return string
*/
public function getJsValidatorString($formName = null, $onLoad = true)
{
$onLoad = $onLoad ? 'true' : 'false';
$this->siftQueue();
$models = array();
// Process just the specified form
if ($formName) {
if (!isset($this->queue[$formName])) {
$list = implode(', ', array_keys($this->queue));
throw new UndefinedFormException("Form '$formName' was not found. Existing forms: $list");
}
$models[] = $this->createJsModel($this->queue[$formName]);
unset($this->queue[$formName]);
} else { // Or process whole queue
$models = $this->processQueue();
}
// If there are no forms to validate
if (!array_filter($models)) {
return '';
}
$result = array();
foreach ($models as $model) {
$result[] = "FpJsFormValidator.addModel({$model}, {$onLoad});";
}
return implode("\n", $result);
}
}