_request = $request; $context += [ 'schema' => [], 'required' => [], 'defaults' => [], 'errors' => [], ]; $this->_context = $context; } /** * Get the current value for a given field. * * This method will coalesce the current request data and the 'defaults' * array. * * @param string $field A dot separated path to the field a value * is needed for. * @return mixed */ public function val($field) { $val = $this->_request->data($field); if ($val !== null) { return $val; } if (empty($this->_context['defaults']) || !is_array($this->_context['defaults'])) { return null; } return Hash::get($this->_context['defaults'], $field); } /** * Check if a given field is 'required'. * * In this context class, this is simply defined by the 'required' array. * * @param string $field A dot separated path to check required-ness for. * @return boolean */ public function isRequired($field) { if (!is_array($this->_context['required'])) { return false; } $required = Hash::get($this->_context['required'], $field); return (bool)$required; } /** * Get the abstract field type for a given field name. * * @param string $field A dot separated path to get a schema type for. * @return string An abstract data type. * @see Cake\Database\Type */ public function type($field) { if (!is_array($this->_context['schema'])) { return false; } $schema = Hash::get($this->_context['schema'], $field); return isset($schema['type']) ? $schema['type'] : null; } /** * Get an associative array of other attributes for a field name. * * @param string $field A dot separated path to get a additional data on. * @return array An array of data describing the additional attributes on a field. */ public function attributes($field) { if (!is_array($this->_context['schema'])) { return []; } $schema = Hash::get($this->_context['schema'], $field); $whitelist = ['length' => null, 'precision' => null]; return array_intersect_key($schema, $whitelist); } /** * Check whether or not a field has an error attached to it * * @param string $field A dot separated path to check errors on. * @return boolean Returns true if the errors for the field are not empty. */ public function hasError($field) { if (empty($this->_context['errors'])) { return false; } return (bool)Hash::check($this->_context['errors'], $field); } /** * Get the errors for a given field * * @param string $field A dot separated path to check errors on. * @return mixed Either a string or an array of errors. Null * will be returned when the field path is undefined. */ public function error($field) { if (empty($this->_context['errors'])) { return null; } return Hash::get($this->_context['errors'], $field); } }