ILIAS  release_5-2 Revision v5.2.25-18-g3f80b828510
ComponentHelper.php
Go to the documentation of this file.
1<?php
2
3/* Copyright (c) 2016 Richard Klees <richard.klees@concepts-and-training.de> Extended GPL, see docs/LICENSE */
4
6
10trait ComponentHelper {
20 protected function checkArg($which, $check, $message) {
21 assert('is_string($which)');
22 assert('is_bool($check)');
23 assert('is_string($message)');
24 if (!$check) {
25 throw new \InvalidArgumentException("Argument '$which': $message");
26 }
27 }
28
37 protected function checkIntArg($which, $value) {
38 $this->checkArg($which, is_int($value), $this->wrongTypeMessage("integer", $value));
39 }
40
49 protected function checkStringArg($which, $value) {
50 $this->checkArg($which, is_string($value), $this->wrongTypeMessage("string", $value));
51 }
52
62 protected function checkArgInstanceOf($which, $value, $class) {
63 $this->checkArg($which, $value instanceof $class, $this->wrongTypeMessage($class, $value));
64 }
65
76 protected function checkArgIsElement($which, $value, $array, $name) {
77 if (!is_object($value)) {
78 $message = "expected $name, got '$value'";
79 }
80 else {
81 $message = "expected $name, got object.";
82 }
83 $message =
84 $this->checkArg($which, in_array($value, $array), $message);
85 }
86
97 protected function checkArgList($which, array &$values, \Closure $check, \Closure $message) {
98 $failed_k = null;
99 $failed_v = null;
100 foreach ($values as $key => $value) {
101 $ok = $check($key, $value);
102 if (!$ok) {
103 $failed_k = $key;
104 $failed_v = $value;
105 break;
106 }
107 }
108
109 if ($failed_k !== null) {
110 $m = $message($failed_k, $failed_v);
111 }
112 else {
113 $m = "";
114 }
115
116 $this->checkArg($which, $failed_k === null, $m);
117 }
118
129 protected function checkArgListElements($which, array &$values, &$classes) {
130 $classes = $this->toArray($classes);
131 $this->checkArgList
132 ( $which
133 , $values
134 , function($_, $value) use (&$classes) {
135 foreach ($classes as $cls) {
136 if ($cls === "string" && is_string($value)) {
137 return true;
138 }
139 if ($cls === "int" && is_int($value)) {
140 return true;
141 }
142 else if ($value instanceof $cls) {
143 return true;
144 }
145 }
146 return false;
147 }
148 , function ($_, $failed) use (&$classes) {
149 return $this->wrongTypeMessage(implode(", ", $classes), $failed);
150 });
151 }
152
159 protected function toArray($value) {
160 if (is_array($value)) {
161 return $value;
162 }
163 return array($value);
164 }
165
166 protected function wrongTypeMessage($expected, $value) {
167 $type = gettype($value);
168 if (!is_object($value) && !is_array($value)) {
169 return "expected $expected, got $type '$value'";
170 }
171 else {
172 if (is_object($value)) {
173 $type = get_class($value);
174 }
175 return "expected $expected, got $type";
176 }
177 }
178}
$failed
Definition: Utf8Test.php:85
An exception for terminatinating execution or to throw for unit testing.