be66ebeed24a3175c0f1a81a4c23d2f706637feb
[GitHub/WoltLab/WCF.git] /
1 <?php
2 declare(strict_types=1);
3 namespace wcf\system\form\builder\field\dependency;
4 use wcf\system\form\builder\field\IFormField;
5 use wcf\system\form\builder\IFormNode;
6 use wcf\system\WCF;
7
8 /**
9 * Abstract implementation of a form field dependency.
10 *
11 * @author Matthias Schmidt
12 * @copyright 2001-2018 WoltLab GmbH
13 * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
14 * @package WoltLabSuite\Core\System\Form\Builder\Field\Dependency
15 * @since 3.2
16 */
17 abstract class AbstractFormFieldDependency implements IFormFieldDependency {
18 /**
19 * node whose availability depends on the value of a field
20 * @var IFormNode
21 */
22 protected $__dependentNode;
23
24 /**
25 * field the availability of the node dependents on
26 * @var IFormField
27 */
28 protected $__field;
29
30 /**
31 * id of the dependency
32 * @var string
33 */
34 protected $__id;
35
36 /**
37 * name of the template containing the dependency JavaScript code
38 * @var null|string
39 */
40 protected $templateName;
41
42 /**
43 * @inheritDoc
44 */
45 public function dependentNode(IFormNode $node): IFormFieldDependency {
46 $this->__dependentNode = $node;
47
48 return $this;
49 }
50
51 /**
52 * @inheritDoc
53 */
54 public function field(IFormField $field): IFormFieldDependency {
55 $this->__field = $field;
56
57 return $this;
58 }
59
60 /**
61 * @inheritDoc
62 */
63 public function getDependentNode(): IFormNode {
64 if ($this->__dependentNode === null) {
65 throw new \BadMethodCallException("Dependent node has not been set.");
66 }
67
68 return $this->__dependentNode;
69 }
70
71 /**
72 * @inheritDoc
73 */
74 public function getField(): IFormField {
75 if ($this->__field === null) {
76 throw new \BadMethodCallException("Field has not been set.");
77 }
78
79 return $this->__field;
80 }
81
82 /**
83 * @inheritDoc
84 */
85 public function getId(): string {
86 return $this->__id;
87 }
88
89 /**
90 * @inheritDoc
91 */
92 public function getHtml(): string {
93 if ($this->templateName === null) {
94 throw new \LogicException("Template name is not set.");
95 }
96
97 return WCF::getTPL()->fetch($this->templateName, 'wcf', [
98 'dependency' => $this
99 ], true);
100 }
101
102 /**
103 * Sets the id of this dependency and returns this dependency.
104 *
105 * @param string $id id of the dependency
106 * @return static $this this dependency
107 *
108 * @throws \InvalidArgumentException if given id no string or otherwise invalid
109 */
110 protected function id(string $id): IFormFieldDependency {
111 if (preg_match('~^[a-z][A-z0-9-]*$~', $id) !== 1) {
112 throw new \InvalidArgumentException("Invalid id '{$id}' given.");
113 }
114
115 $this->__id = $id;
116
117 return $this;
118 }
119
120 /**
121 * @inheritDoc
122 * @return static
123 */
124 public static function create(string $id): IFormFieldDependency {
125 return (new static)->id($id);
126 }
127 }