Commit 39947be6 by Qiang Xue

rest WIP

parent 1f292ef5
......@@ -93,10 +93,9 @@ class ErrorHandler extends Component
return;
}
$useErrorView = !YII_DEBUG || $exception instanceof UserException;
$useErrorView = $response->format === \yii\web\Response::FORMAT_HTML && (!YII_DEBUG || $exception instanceof UserException);
$response = Yii::$app->getResponse();
$response->getHeaders()->removeAll();
if ($useErrorView && $this->errorAction !== null) {
$result = Yii::$app->runAction($this->errorAction);
......@@ -121,7 +120,7 @@ class ErrorHandler extends Component
]);
}
} elseif ($exception instanceof Arrayable) {
$response->data = $exception;
$response->data = $exception->toArray();
} else {
$response->data = [
'type' => get_class($exception),
......
......@@ -517,7 +517,8 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
/**
* Returns the first error of every attribute in the model.
* @return array the first errors. An empty array will be returned if there is no error.
* @return array the first errors. The array keys are the attribute names, and the array
* values are the corresponding error messages. An empty array will be returned if there is no error.
* @see getErrors()
* @see getFirstError()
*/
......@@ -527,13 +528,13 @@ class Model extends Component implements IteratorAggregate, ArrayAccess, Arrayab
return [];
} else {
$errors = [];
foreach ($this->_errors as $attributeErrors) {
if (isset($attributeErrors[0])) {
$errors[] = $attributeErrors[0];
foreach ($this->_errors as $name => $es) {
if (!empty($es)) {
$errors[$name] = reset($es);
}
}
return $errors;
}
return $errors;
}
/**
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rest;
use Yii;
use yii\base\InvalidConfigException;
use yii\db\ActiveRecordInterface;
use yii\web\NotFoundHttpException;
/**
* Action is the base class for action classes that implement RESTful API.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Action extends \yii\base\Action
{
/**
* @var string class name of the model which will be handled by this action.
* The model class must implement [[ActiveRecordInterface]].
* This property must be set.
*/
public $modelClass;
/**
* @var callable a PHP callable that will be called to return the model corresponding
* to the specified primary key value. If not set, [[findModel()]] will be used instead.
* The signature of the callable should be:
*
* ```php
* function ($id, $action) {
* // $id is the primary key value. If composite primary key, the key values
* // will be separated by comma.
* // $action is the action object currently running
* }
* ```
*
* The callable should return the model found, or throw an exception if not found.
*/
public $findModel;
/**
* @var callable a PHP callable that will be called when running an action to determine
* if the current user has the permission to execute the action. If not set, the access
* check will not be performed. The signature of the callable should be as follows,
*
* ```php
* function ($action, $model = null) {
* // $model is the requested model instance.
* // If null, it means no specific model (e.g. IndexAction)
* }
* ```
*/
public $checkAccess;
/**
* @inheritdoc
*/
public function init()
{
if ($this->modelClass === null) {
throw new InvalidConfigException(get_class($this) . '::$modelClass must be set.');
}
}
/**
* Returns the data model based on the primary key given.
* If the data model is not found, a 404 HTTP exception will be raised.
* @param string $id the ID of the model to be loaded. If the model has a composite primary key,
* the ID must be a string of the primary key values separated by commas.
* The order of the primary key values should follow that returned by the `primaryKey()` method
* of the model.
* @return ActiveRecordInterface the model found
* @throws NotFoundHttpException if the model cannot be found
*/
public function findModel($id)
{
if ($this->findModel !== null) {
return call_user_func($this->findModel, $id, $this);
}
/**
* @var ActiveRecordInterface $modelClass
*/
$modelClass = $this->modelClass;
$keys = $modelClass::primaryKey();
if (count($keys) > 1) {
$values = explode(',', $id);
if (count($keys) === count($values)) {
$model = $modelClass::find(array_combine($keys, $values));
}
} else {
$model = $modelClass::find($id);
}
if (isset($model)) {
return $model;
} else {
throw new NotFoundHttpException("Object not found: $id");
}
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rest;
use yii\base\InvalidConfigException;
use yii\web\ForbiddenHttpException;
/**
* ActiveController implements a common set of actions for supporting RESTful access to ActiveRecord.
*
* The class of the ActiveRecord should be specified via [[modelClass]], which must implement [[\yii\db\ActiveRecordInterface]].
* By default, the following actions are supported:
*
* - `index`: list of models
* - `view`: return the details of a model
* - `create`: create a new model
* - `update`: update an existing model
* - `delete`: delete an existing model
* - `options`: return the allowed HTTP methods
*
* You may disable some of these actions by overriding [[actions()]] and unsetting the corresponding actions.
*
* To add a new action, either override [[actions()]] by appending a new action class or write a new action method.
* Make sure you also override [[verbs()]] to properly declare what HTTP methods are allowed by the new action.
*
* You should usually override [[checkAccess()]] to check whether the current user has the privilege to perform
* the specified action against the specified model.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class ActiveController extends Controller
{
/**
* @var string the model class name. This property must be set.
*/
public $modelClass;
/**
* @var string the scenario used for updating a model.
* @see \yii\base\Model::scenarios()
*/
public $updateScenario = 'api-update';
/**
* @var string the scenario used for creating a model.
* @see \yii\base\Model::scenarios()
*/
public $createScenario = 'api-create';
/**
* @var boolean whether to use a DB transaction when creating, updating or deleting a model.
* This property is only useful for relational database.
*/
public $transactional = true;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->modelClass === null) {
throw new InvalidConfigException('The "modelClass" property must be set.');
}
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'index' => [
'class' => 'yii\rest\IndexAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'view' => [
'class' => 'yii\rest\ViewAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'create' => [
'class' => 'yii\rest\CreateAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'scenario' => $this->createScenario,
'transactional' => $this->transactional,
],
'update' => [
'class' => 'yii\rest\UpdateAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'scenario' => $this->updateScenario,
'transactional' => $this->transactional,
],
'delete' => [
'class' => 'yii\rest\DeleteAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'transactional' => $this->transactional,
],
'options' => [
'class' => 'yii\rest\OptionsAction',
],
];
}
/**
* @inheritdoc
*/
protected function verbs()
{
return [
'index' => ['GET', 'HEAD'],
'view' => ['GET', 'HEAD'],
'create' => ['POST'],
'update' => ['PUT', 'PATCH'],
'delete' => ['DELETE'],
'options' => ['OPTIONS'],
];
}
/**
* Checks the privilege of the current user.
*
* This method should be overridden to check whether the current user has the privilege
* to run the specified action against the specified data model.
* If the user does not have access, a [[ForbiddenHttpException]] should be thrown.
*
* @param \yii\base\Action $action the action to be executed
* @param \yii\base\Model $model the model to be accessed. If null, it means no specific model is being accessed.
* @param array $params additional parameters
* @throws ForbiddenHttpException if the user does not have access
*/
public function checkAccess($action, $model = null, $params = [])
{
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rest;
use Yii;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use yii\web\UnauthorizedHttpException;
use yii\web\VerbFilter;
/**
* Controller is the base class for RESTful API controller classes.
*
* Controller implements the following steps in a RESTful API request handling cycle:
*
* 1. Resolving response format and API version number (see [[supportedFormats]], [[supportedVersions]] and [[version]]);
* 2. Validating request method (see [[verbs()]]);
* 3. Authenticating user (see [[authenticate()]]);
* 4. Formatting response data (see [[serializeData()]]).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Controller extends \yii\web\Controller
{
/**
* The name of the header parameter representing the API version number.
*/
const HEADER_VERSION = 'version';
/**
* @var string|array the configuration for creating the serializer that formats the response data.
*/
public $serializer = 'yii\rest\Serializer';
/**
* @inheritdoc
*/
public $enableCsrfValidation = false;
/**
* @var string the chosen API version number
* @see supportedVersions
*/
public $version;
/**
* @var array list of supported API version numbers. If the current request does not specify a version
* number, the first element will be used as the chosen version number. For this reason, you should
* put the latest version number at the first.
*/
public $supportedVersions = ['1.0'];
/**
* @var array list of supported response formats. The array keys are the requested content MIME types,
* and the array values are the corresponding response formats. The first element will be used
* as the response format if the current request does not specify a content type.
*/
public $supportedFormats = [
'application/json' => Response::FORMAT_JSON,
'application/xml' => Response::FORMAT_XML,
];
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbFilter' => [
'class' => VerbFilter::className(),
'actions' => $this->verbs(),
],
];
}
/**
* @inheritdoc
*/
public function init()
{
parent::init();
$this->resolveFormatAndVersion();
}
/**
* @inheritdoc
*/
public function beforeAction($action)
{
if (parent::beforeAction($action)) {
$this->authenticate();
return true;
} else {
return false;
}
}
/**
* @inheritdoc
*/
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
return $this->serializeData($result);
}
/**
* Resolves the response format and the API version number.
* @throws BadRequestHttpException
*/
protected function resolveFormatAndVersion()
{
$this->version = reset($this->supportedVersions);
Yii::$app->getResponse()->format = reset($this->supportedFormats);
$types = Yii::$app->getRequest()->getAcceptableContentTypes();
if (empty($types)) {
$types['*/*'] = [];
}
foreach ($types as $type => $params) {
if (isset($this->supportedFormats[$type])) {
Yii::$app->getResponse()->format = $this->supportedFormats[$type];
if (isset($params[self::HEADER_VERSION])) {
if (in_array($params[self::HEADER_VERSION], $this->supportedVersions, true)) {
$this->version = $params[self::HEADER_VERSION];
} else {
throw new BadRequestHttpException('You are requesting an invalid version number.');
}
}
return;
}
}
if (!isset($types['*/*'])) {
throw new BadRequestHttpException('None of your requested content types is valid.');
}
}
/**
* Declares the allowed HTTP verbs.
* Please refer to [[VerbFilter::actions]] on how to declare the allowed verbs.
* @return array the allowed HTTP verbs.
*/
protected function verbs()
{
return [];
}
/**
* Authenticates the user.
* @throws UnauthorizedHttpException if the user is not authenticated successfully
*/
protected function authenticate()
{
}
/**
* Serializes the specified data.
* The default implementation will create a serializer based on the configuration given by [[serializer]].
* It then uses the serializer to serialize the given data.
* @param mixed $data the data to be serialized
* @return mixed the serialized data.
*/
protected function serializeData($data)
{
return Yii::createObject($this->serializer)->serialize($data);
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rest;
use Yii;
use yii\db\ActiveRecord;
/**
* CreateAction implements the API endpoint for creating a new model from the given data.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class CreateAction extends Action
{
/**
* @var string the scenario to be assigned to the new model before it is validated and saved.
*/
public $scenario = 'api-create';
/**
* @var boolean whether to start a DB transaction when saving the model.
*/
public $transactional = true;
/**
* @var string the name of the view action. This property is need to create the URL when the mode is successfully created.
*/
public $viewAction = 'view';
/**
* Creates a new model.
* @return \yii\db\ActiveRecordInterface the model newly created
* @throws \Exception if there is any error when creating the model
*/
public function run()
{
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this);
}
/**
* @var \yii\db\ActiveRecord $model
*/
$model = new $this->modelClass([
'scenario' => $this->scenario,
]);
$model->load(Yii::$app->getRequest()->getBodyParams(), '');
if ($this->transactional && $model instanceof ActiveRecord) {
if ($model->validate()) {
$transaction = $model->getDb()->beginTransaction();
try {
$model->insert(false);
$transaction->commit();
} catch (\Exception $e) {
$transaction->rollback();
throw $e;
}
}
} else {
$model->save();
}
if (!$model->hasErrors()) {
$response = Yii::$app->getResponse();
$response->setStatusCode(201);
$id = implode(',', array_values($model->getPrimaryKey(true)));
$response->getHeaders()->set('Location', $this->controller->createAbsoluteUrl([$this->viewAction, 'id' => $id]));
}
return $model;
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rest;
use Yii;
use yii\db\ActiveRecord;
/**
* DeleteAction implements the API endpoint for deleting a model.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class DeleteAction extends Action
{
/**
* @var boolean whether to start a DB transaction when deleting the model.
*/
public $transactional = true;
/**
* Deletes a model.
*/
public function run($id)
{
$model = $this->findModel($id);
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this, $model);
}
if ($this->transactional && $model instanceof ActiveRecord) {
$transaction = $model->getDb()->beginTransaction();
try {
$model->delete();
$transaction->commit();
} catch (\Exception $e) {
$transaction->rollback();
throw $e;
}
} else {
$model->delete();
}
Yii::$app->getResponse()->setStatusCode(204);
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rest;
use Yii;
use yii\data\ActiveDataProvider;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class IndexAction extends Action
{
/**
* @var callable a PHP callable that will be called to prepare a data provider that
* should return a collection of the models. If not set, [[prepareDataProvider()]] will be used instead.
* The signature of the callable should be:
*
* ```php
* function ($action) {
* // $action is the action object currently running
* }
* ```
*
* The callable should return an instance of [[ActiveDataProvider]].
*/
public $prepareDataProvider;
/**
* @return ActiveDataProvider
*/
public function run()
{
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this);
}
return $this->prepareDataProvider();
}
/**
* Prepares the data provider that should return the requested collection of the models.
* @return ActiveDataProvider
*/
protected function prepareDataProvider()
{
if ($this->prepareDataProvider !== null) {
return call_user_func($this->prepareDataProvider, $this);
}
/**
* @var \yii\db\BaseActiveRecord $modelClass
*/
$modelClass = $this->modelClass;
return new ActiveDataProvider([
'query' => $modelClass::find(),
]);
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rest;
use Yii;
/**
* OptionsAction responds to the OPTIONS request by sending back an `Allow` header.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class OptionsAction extends \yii\base\Action
{
/**
* @var array the HTTP verbs that are supported by the collection URL
*/
public $collectionOptions = ['GET', 'POST'];
/**
* @var array the HTTP verbs that are supported by the resource URL
*/
public $resourceOptions = ['GET', 'PUT', 'PATCH', 'DELETE'];
/**
* Responds to the OPTIONS request.
* @param string $id
*/
public function run($id = null)
{
$options = $id === null ? $this->collectionOptions : $this->resourceOptions;
Yii::$app->getResponse()->getHeaders()->set('Allow', implode(', ', $options));
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rest;
use Yii;
use yii\base\Component;
use yii\base\Model;
use yii\data\DataProviderInterface;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;
use yii\web\Request;
use yii\web\Response;
/**
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Serializer extends Component
{
public $fieldsParam = 'fields';
public $expandParam = 'expand';
public $totalCountHeader = 'X-Pagination-Total-Count';
public $pageCountHeader = 'X-Pagination-Page-Count';
public $currentPageHeader = 'X-Pagination-Current-Page';
public $perPageHeader = 'X-Pagination-Per-Page';
/**
* @var Request
*/
public $request;
/**
* @var Response
*/
public $response;
public function init()
{
if ($this->request === null) {
$this->request = Yii::$app->getRequest();
}
if ($this->response === null) {
$this->response = Yii::$app->getResponse();
}
}
public function serialize($data)
{
if ($data instanceof Model) {
return $data->hasErrors() ? $this->serializeModelErrors($data) : $this->serializeModel($data);
} elseif ($data instanceof DataProviderInterface) {
return $this->serializeDataProvider($data);
} else {
return $data;
}
}
protected function getRequestedFields()
{
$fields = $this->request->get($this->fieldsParam);
$expand = $this->request->get($this->expandParam);
return [
preg_split('/\s*,\s*/', $fields, -1, PREG_SPLIT_NO_EMPTY),
preg_split('/\s*,\s*/', $expand, -1, PREG_SPLIT_NO_EMPTY),
];
}
/**
* @param DataProviderInterface $dataProvider
* @return array
*/
protected function serializeDataProvider($dataProvider)
{
$models = $dataProvider->getModels();
if (($pagination = $dataProvider->getPagination()) !== false) {
$this->addPaginationHeaders($pagination);
}
if ($this->request->getIsHead()) {
return null;
} else {
return $this->serializeModels($models);
}
}
/**
* @param Pagination $pagination
*/
protected function addPaginationHeaders($pagination)
{
$links = [];
foreach ($pagination->getLinks(true) as $rel => $url) {
$links[] = "<$url>; rel=$rel";
}
$this->response->getHeaders()
->set($this->totalCountHeader, $pagination->totalCount)
->set($this->pageCountHeader, $pagination->getPageCount())
->set($this->currentPageHeader, $pagination->getPage() + 1)
->set($this->perPageHeader, $pagination->pageSize)
->set('Link', implode(', ', $links));
}
/**
* @param Model $model
* @return array
*/
protected function serializeModel($model)
{
if ($this->request->getIsHead()) {
return null;
} else {
list ($fields, $expand) = $this->getRequestedFields();
return $model->toArray($fields, $expand);
}
}
/**
* @param Model $model
* @return array
*/
protected function serializeModelErrors($model)
{
$this->response->setStatusCode(400, 'Data Validation Failure');
$result = [];
foreach ($model->getFirstErrors() as $name => $message) {
$result[] = [
'field' => $name,
'message' => $message,
];
}
return $result;
}
protected function serializeModels(array $models)
{
list ($fields, $expand) = $this->getRequestedFields();
foreach ($models as $i => $model) {
if ($model instanceof Model) {
$models[$i] = $model->toArray($fields, $expand);
} elseif (is_array($model)) {
$models[$i] = ArrayHelper::toArray($model);
}
}
return $models;
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rest;
use Yii;
use yii\db\ActiveRecord;
/**
* UpdateAction implements the API endpoint for updating a model.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class UpdateAction extends Action
{
/**
* @var string the scenario to be assigned to the model before it is validated and updated.
*/
public $scenario = 'api-update';
/**
* @var boolean whether to start a DB transaction when saving the model.
*/
public $transactional = true;
/**
* Updates an existing model.
* @param string $id the primary key of the model.
* @return \yii\db\ActiveRecordInterface the model being updated
* @throws \Exception if there is any error when updating the model
*/
public function run($id)
{
/** @var ActiveRecord $model */
$model = $this->findModel($id);
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this, $model);
}
$model->scenario = $this->scenario;
$model->load(Yii::$app->getRequest()->getBodyParams(), '');
if ($this->transactional && $model instanceof ActiveRecord) {
if ($model->validate()) {
$transaction = $model->getDb()->beginTransaction();
try {
$model->update(false);
$transaction->commit();
} catch (\Exception $e) {
$transaction->rollback();
throw $e;
}
}
} else {
$model->save();
}
return $model;
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rest;
use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\Inflector;
use yii\web\CompositeUrlRule;
/**
* UrlRule is provided to simplify creation of URL rules for RESTful API support.
*
* The simplest usage of UrlRule is to declare a rule like the following in the application configuration,
*
* ```php
* [
* 'class' => 'yii\rest\UrlRule',
* 'controller' => 'user',
* ]
* ```
*
* The above code will create a whole set of URL rules supporting the following RESTful API endpoints:
*
* - `'PUT,PATCH users/<id>' => 'user/update'`: update a user
* - `'DELETE users/<id>' => 'user/delete'`: delete a user
* - `'GET,HEAD users/<id>' => 'user/view'`: return the details of a user (or the overview for HEAD requests)
* - `'OPTIONS users/<id>' => 'user/options'`: return the supported methods for `users/<id>`
* - `'POST users' => 'user/create'`: create a new user
* - `'GET,HEAD users' => 'user/index'`: return a list of users (or the overview for HEAD requests)
* - `'OPTIONS users' => 'user/options'`: return the supported methods for `users`
*
* You may configure [[only]] and/or [[except]] to disable some of the above rules.
* You may configure [[patterns]] to completely redefine your own list of rules.
* You may configure [[controller]] with multiple controller IDs to generate rules for all these controllers.
* For example, the following code will disable the `delete` rule and generate rules for both `user` and `post` controllers:
*
* ```php
* [
* 'class' => 'yii\rest\UrlRule',
* 'controller' => ['user', 'post'],
* 'except' => ['delete'],
* ]
* ```
*
* The property [[controller]] is required and should be the controller ID. It should be prefixed with
* the module ID if the controller is within a module.
*
* The controller ID used in the pattern will be automatically pluralized (e.g. `user` becomes `users`
* as shown in the above examples). You may configure [[urlName]] to explicitly specify the controller ID
* in the pattern.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class UrlRule extends CompositeUrlRule
{
/**
* @var string the common prefix string shared by all patterns.
*/
public $prefix;
/**
* @var string the suffix that will be assigned to [[\yii\web\UrlRule::suffix]] for every generated rule.
*/
public $suffix;
/**
* @var string|array the controller ID (e.g. `user`, `post-comment`) that the rules in this composite rule
* are dealing with. It should be prefixed with the module ID if the controller is within a module (e.g. `admin/user`).
*
* By default, the controller ID will be pluralized automatically when it is put in the patterns of the
* generated rules. If you want to explicitly specify how the controller ID should appear in the patterns,
* you may use an array with the array key being as the controller ID in the pattern, and the array value
* the actual controller ID. For example, `['u' => 'user']`.
*
* You may also pass multiple controller IDs as an array. If this is the case, this composite rule will
* generate applicable URL rules for EVERY specified controller. For example, `['user', 'post']`.
*/
public $controller;
/**
* @var array list of acceptable actions. If not empty, only the actions within this array
* will have the corresponding URL rules created.
* @see patterns
*/
public $only = [];
/**
* @var array list of actions that should be excluded. Any action found in this array
* will NOT have its URL rules created.
* @see patterns
*/
public $except = [];
/**
* @var array list of tokens that should be replaced for each pattern. The keys are the token names,
* and the values are the corresponding replacements.
* @see patterns
*/
public $tokens = [
'{id}' => '<id:\\d+[\\d,]*>',
];
/**
* @var array list of possible patterns and the corresponding actions for creating the URL rules.
* The keys are the patterns and the values are the corresponding actions.
* The format of patterns is `Verbs Path`, where `Verbs` stands for a list of HTTP verbs separated
* by comma (without space). `Path` is optional. It will be prefixed with [[prefix]]/[[controller]]/,
* and tokens in it will be replaced by [[tokens]].
*/
public $patterns = [
'GET,HEAD {id}' => 'view',
'PUT,PATCH {id}' => 'update',
'DELETE {id}' => 'delete',
'OPTIONS {id}' => 'options',
'GET,HEAD' => 'index',
'POST' => 'create',
'OPTIONS' => 'options',
];
public $ruleConfig = [
'class' => 'yii\web\UrlRule',
];
/**
* @inheritdoc
*/
public function init()
{
if (empty($this->controller)) {
throw new InvalidConfigException('"controller" must be set.');
}
$controllers = [];
foreach ((array)$this->controller as $urlName => $controller) {
if (is_integer($urlName)) {
$urlName = Inflector::pluralize($controller);
}
$controllers[$urlName] = $controller;
}
$this->controller = $controllers;
$this->prefix = trim($this->prefix, '/');
parent::init();
}
/**
* @inheritdoc
*/
protected function createRules()
{
$only = array_flip($this->only);
$except = array_flip($this->except);
$rules = [];
foreach ($this->controller as $urlName => $controller) {
$prefix = trim($this->prefix . '/' . $urlName, '/');
foreach ($this->patterns as $pattern => $action) {
if (!isset($except[$action]) && (empty($only) || isset($only[$action]))) {
$rules[] = $this->createRule($pattern, $prefix, $controller . '/' . $action);
}
}
}
return $rules;
}
/**
* Creates a URL rule using the given pattern and action.
* @param string $pattern
* @param string $prefix
* @param string $action
* @return \yii\web\UrlRuleInterface
*/
protected function createRule($pattern, $prefix, $action)
{
if (($pos = strpos($pattern, ' ')) !== false) {
$verbs = substr($pattern, 0, $pos);
$pattern = strtr(substr($pattern, $pos + 1), $this->tokens);
} else {
$verbs = $pattern;
$pattern = '';
}
$config = $this->ruleConfig;
$config['verb'] = explode(',', $verbs);
$config['pattern'] = rtrim($prefix . '/' . $pattern, '/');
$config['route'] = $action;
if (strcasecmp($verbs, 'GET')) {
$config['mode'] = \yii\web\UrlRule::PARSING_ONLY;
}
$config['suffix'] = $this->suffix;
return Yii::createObject($config);
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rest;
use Yii;
/**
* ViewAction implements the API endpoint for returning the detailed information about a model.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class ViewAction extends Action
{
/**
* Displays a model.
* @param string $id the primary key of the model.
* @return \yii\db\ActiveRecordInterface the model being displayed
*/
public function run($id)
{
$model = $this->findModel($id);
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this, $model);
}
return $model;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment