/** * Utility method to get an instance of a model given an identifier in the query string * @param $modelClassName * @param string $queryParameter * @return \GGS\Components\Model */ protected static function getModelByRequest($modelClassName, $queryParameter = 'id') { $id = WebApplication::$request->getQueryStringParameter($queryParameter); if (!isset($id)) { // whoopsie, can't live without id static::exitWithException("Invalid Request: Missing id.", 400); } if (!is_numeric($id) || $id < 1) { // so far we are only using positive integer primary keys so it doesn't make sense to search for a model // with negative key static::exitWithException("Invalid Request: id must be positive integer", 400); } // convert id to a proper integer, no string values; $id = intval($id); // get the qualified model class name with namespace $modelClassName = \GGS\Components\Model::getQualifiedModelClassName($modelClassName); // get the model $model = $modelClassName::getByPk($id); if (!isset($model)) { // model not found? how come? I know, a bad request. static::exitWithException("No records found for: {$id}", 404); } // found it. return $model; }
public function validate(\GGS\Components\Model &$object, $attribute) { if (empty($object->{$attribute})) { return parent::validate($object, $attribute); } $qualifiedModelClassName = \GGS\Components\Model::getQualifiedModelClassName($this->modelClass); $exists = $qualifiedModelClassName::exists(array($this->attribute => $object->{$attribute})); if (!$exists) { $this->setError($object, $attribute, 'referenced record can not be found'); } return $exists; }