Exemplo n.º 1
0
 /**
  * Add relation field type.
  *
  * @param Entity $entity
  * @param Collection            $collection
  * @param string                $id
  * @param string                $ref
  * @param bool                  $inline
  *
  * @return BasicRelation
  */
 public function relates($entity, $collection, $id, $ref = null, $inline = false)
 {
     if ($ref === null) {
         $ref = str_plural($id);
     }
     $ref = $entity->getEntitiesRepository()->resolve($ref);
     $model = $entity->newModel();
     if (!method_exists($model, $id)) {
         $className = get_class($model);
         throw new \RuntimeException("The target model [{$className}] doesn't have relation [{$id}] defined.");
     }
     $relation = $model->{$id}();
     if (!$relation instanceof Relation) {
         $className = get_class($model);
         throw new \RuntimeException("The method [{$id}] of model [{$className}] did not return valid relation.");
     }
     $relationClassName = class_basename($relation);
     $className = __NAMESPACE__ . '\\' . ($inline ? 'InlineTypes' : 'Types') . '\\' . $relationClassName;
     if (!class_exists($className)) {
         throw new \RuntimeException("Cruddy does not know how to handle [{$relationClassName}] relation.");
     }
     $instance = new $className($entity, $id, $ref, $relation);
     $collection->add($instance);
     return $instance;
 }