src/Laravel5_Api/ModelMapping.php
<?php
namespace SehrGut\Laravel5_Api;
use Illuminate\Database\Eloquent\Model;
use SehrGut\Laravel5_Api\Transformers\Transformer;
class ModelMapping
{
/**
* An array mapping each Eloquent Model to a Tansformer class.
*
* Example:
* ```
* protected $transformers = [
* App\Models\Post::class => App\Transformers\PostTransformer::class
* ]
* ```
*
* @var array
*/
protected $transformers = [];
/**
* An array mapping each Eloquent Model to a Validator class.
*
* Usage is the same as for $transformers.
*
* @var array
*/
protected $validators = [];
/**
* An array mapping each Eloquent Model to a route.
*
* Example:
* The route for the `Post` model is mapped to `api.v1.posts.show`
* using the post's `id` as the `{post_id}` url parameter.
* ```
* protected $routes = [
* App\Models\Post::class => [
* 'name' => 'api.v1.posts.show',
* 'parameters' => ['post_id' => 'id']
* ]
* ]
* ```
*
* @var array
*/
protected $routes = [];
/**
* The default Transformer to use if none specified.
*
* @var array
*/
protected $default_transformer = Transformer::class;
/**
* The default Validator to use if none specified.
*
* @var array
*/
protected $default_validator = Validator::class;
/**
* Get the Transformer for a specific model.
*
* @param string $class Class name of the model
*
* @return Transformer
*/
public function getTransformerFor(String $class)
{
if (array_key_exists($class, $this->transformers)) {
return new $this->transformers[$class]($this);
} else {
return new $this->default_transformer($this);
}
}
/**
* Get the Validator for a specific model.
*
* @param string $class Class name of the model
*
* @return Validator
*/
public function getValidatorFor(String $class)
{
if (array_key_exists($class, $this->validators)) {
return $this->validators[$class];
} else {
return $this->default_validator;
}
}
/**
* Get the url for a specific model.
*
* The url is generated by mapping model attributes to the parameters
* of a named route. The name of the route and the mapping of model
* attributes to url parameters is defined in $this->routes.
*
* @param string $class Class name of the model
* @param bool $absolute Whether to generate an absolute url (Default: true)
*
* @return Validator
*/
public function getUrlFor(Model $model, $absolute = true)
{
$class = get_class($model);
if (array_key_exists($class, $this->routes)) {
$route = $this->routes[$class];
$parameters = [];
foreach ($route['parameters'] as $route_key => $model_key) {
$parameters[$route_key] = $model->$model_key;
}
return route($route['name'], $parameters, $absolute);
}
}
}