-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFieldFinderTrait.php
More file actions
91 lines (85 loc) · 2.55 KB
/
FieldFinderTrait.php
File metadata and controls
91 lines (85 loc) · 2.55 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
<?php
namespace Bdf\Form\Util;
use Bdf\Form\ElementInterface;
/**
* Helper trait for adding field finding methods
* Must be used on a ChildAggregateInterface implementation, like a subclass of CustomForm
*
* Usage:
* <code>
* class CredentialsForm extends CustomForm
* {
* use FieldFinderTrait;
*
* protected function configure(FormBuilderInterface $builder): void
* {
* $builder->string('username')->required();
* $builder->string('password')->required()->length(['min' => 6]);
* $builder->string('confirm')->depends('password')->satisfy(function ($value) {
* if ($value !== $this->findFieldValue('password')) {
* return 'Invalid password confirmation';
* }
* });
* }
* }
* </code>
*
* @psalm-require-implements \Bdf\Form\ElementInterface
*/
trait FieldFinderTrait
{
/**
* Find a child field by a path
*
* Usage:
* <code>
* $this->findField('/foo/bar'); // Find field bar, under foo element, starting from the root
* $this->findField('foo'); // Find field foo of the current form
* $this->findField('../foo'); // Find field foo of the parent form (i.e. the current form is embedded)
* </code>
*
* @param string $path The field path
*
* @return ElementInterface|null The element, or null if not found
*
* @see FieldPath::parse() For the path syntax
*/
public function findField(string $path): ?ElementInterface
{
return $this->fieldPath($path)->resolve($this);
}
/**
* Get a child field value by a path
*
* Usage:
* <code>
* $this->findField('/foo/bar'); // Get value of field bar, under foo element, starting from the root
* $this->findField('foo'); // Get value of field foo on the current form
* $this->findField('../foo'); // Get value of field foo on the parent form (i.e. the current form is embedded)
* </code>
*
* @param string $path The field path
*
* @return mixed The field value, or null if the field is not found
*
* @see FieldPath::parse() For the path syntax
*/
public function findFieldValue(string $path): mixed
{
return $this->fieldPath($path)->value($this);
}
/**
* Parse the field path
*
* @param string $path
*
* @return FieldPath
*/
private function fieldPath(string $path): FieldPath
{
if ($path[0] !== '.' && $path[0] !== '/') {
$path = './'.$path;
}
return FieldPath::parse($path);
}
}