+ protected function clamp($value, $min, $max, $silent = false)
+ {
+ if ($min !== null && $value < $min) {
+ if ($silent) {
+ $value = $min;
+ } else {
+ throw new \InvalidArgumentException(
+ 'Value must be at least ' . $min
+ );
+ }
+ }
+ if ($max !== null && $value > $max) {
+ if ($silent) {
+ $value = $max;
+ } else {
+ throw new \InvalidArgumentException(
+ 'Value may be up to ' . $min
+ );
+ }
+ }
+ return $value;
+ }
+
+ /**
+ * Validates an age is numeric. If it is not numeric, it's interpreted as
+ * a ISO 8601 duration specification.
+ *
+ * @param string $value Age in seconds
+ *
+ * @return integer Age in seconds
+ *
+ * @throws \InvalidArgumentException
+ * @link http://en.wikipedia.org/wiki/Iso8601#Durations
+ */
+ public static function validateAge($value)
+ {
+ if (!is_numeric($value)) {
+ //convert short notation to seconds
+ $value = 'P' . ltrim(strtoupper($value), 'P');
+ try {
+ $interval = new \DateInterval($value);
+ } catch (\Exception $e) {
+ throw new \InvalidArgumentException(
+ 'Invalid age: ' . $value
+ );
+ }
+ $value = 86400 * (
+ $interval->y * 365
+ + $interval->m * 30
+ + $interval->d
+ ) + $interval->h * 3600
+ + $interval->m * 60
+ + $interval->s;
+ }
+ return $value;
+ }
+