This commit is contained in:
2020-10-06 14:27:47 +07:00
commit 586be80cf6
16613 changed files with 3274099 additions and 0 deletions

106
vendor/yiisoft/yii2/rest/Action.php vendored Normal file
View File

@@ -0,0 +1,106 @@
<?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.
*
* For more details and usage information on Action, see the [guide article on rest controllers](guide:rest-controllers).
*
* @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 $modelClass ActiveRecordInterface */
$modelClass = $this->modelClass;
$keys = $modelClass::primaryKey();
if (count($keys) > 1) {
$values = explode(',', $id);
if (count($keys) === count($values)) {
$model = $modelClass::findOne(array_combine($keys, $values));
}
} elseif ($id !== null) {
$model = $modelClass::findOne($id);
}
if (isset($model)) {
return $model;
}
throw new NotFoundHttpException("Object not found: $id");
}
}

View File

@@ -0,0 +1,137 @@
<?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\base\Model;
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.
*
* For more details and usage information on ActiveController, see the [guide article on rest controllers](guide:rest-controllers).
*
* @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 = Model::SCENARIO_DEFAULT;
/**
* @var string the scenario used for creating a model.
* @see \yii\base\Model::scenarios()
*/
public $createScenario = Model::SCENARIO_DEFAULT;
/**
* {@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,
],
'update' => [
'class' => 'yii\rest\UpdateAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
'scenario' => $this->updateScenario,
],
'delete' => [
'class' => 'yii\rest\DeleteAction',
'modelClass' => $this->modelClass,
'checkAccess' => [$this, 'checkAccess'],
],
'options' => [
'class' => 'yii\rest\OptionsAction',
],
];
}
/**
* {@inheritdoc}
*/
protected function verbs()
{
return [
'index' => ['GET', 'HEAD'],
'view' => ['GET', 'HEAD'],
'create' => ['POST'],
'update' => ['PUT', 'PATCH'],
'delete' => ['DELETE'],
];
}
/**
* 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 string $action the ID of the action to be executed
* @param object $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 = [])
{
}
}

101
vendor/yiisoft/yii2/rest/Controller.php vendored Normal file
View File

@@ -0,0 +1,101 @@
<?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\filters\auth\CompositeAuth;
use yii\filters\ContentNegotiator;
use yii\filters\RateLimiter;
use yii\filters\VerbFilter;
use yii\web\Response;
/**
* 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 (see [[ContentNegotiator]]);
* 2. Validating request method (see [[verbs()]]).
* 3. Authenticating user (see [[\yii\filters\auth\AuthInterface]]);
* 4. Rate limiting (see [[RateLimiter]]);
* 5. Formatting response data (see [[serializeData()]]).
*
* For more details and usage information on Controller, see the [guide article on rest controllers](guide:rest-controllers).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Controller extends \yii\web\Controller
{
/**
* @var string|array the configuration for creating the serializer that formats the response data.
*/
public $serializer = 'yii\rest\Serializer';
/**
* {@inheritdoc}
*/
public $enableCsrfValidation = false;
/**
* {@inheritdoc}
*/
public function behaviors()
{
return [
'contentNegotiator' => [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
'application/xml' => Response::FORMAT_XML,
],
],
'verbFilter' => [
'class' => VerbFilter::className(),
'actions' => $this->verbs(),
],
'authenticator' => [
'class' => CompositeAuth::className(),
],
'rateLimiter' => [
'class' => RateLimiter::className(),
],
];
}
/**
* {@inheritdoc}
*/
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
return $this->serializeData($result);
}
/**
* 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 [];
}
/**
* 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);
}
}

View File

@@ -0,0 +1,63 @@
<?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\Model;
use yii\helpers\Url;
use yii\web\ServerErrorHttpException;
/**
* CreateAction implements the API endpoint for creating a new model from the given data.
*
* For more details and usage information on CreateAction, see the [guide article on rest controllers](guide:rest-controllers).
*
* @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 = Model::SCENARIO_DEFAULT;
/**
* @var string the name of the view action. This property is need to create the URL when the model is successfully created.
*/
public $viewAction = 'view';
/**
* Creates a new model.
* @return \yii\db\ActiveRecordInterface the model newly created
* @throws ServerErrorHttpException if there is any error when creating the model
*/
public function run()
{
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id);
}
/* @var $model \yii\db\ActiveRecord */
$model = new $this->modelClass([
'scenario' => $this->scenario,
]);
$model->load(Yii::$app->getRequest()->getBodyParams(), '');
if ($model->save()) {
$response = Yii::$app->getResponse();
$response->setStatusCode(201);
$id = implode(',', array_values($model->getPrimaryKey(true)));
$response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true));
} elseif (!$model->hasErrors()) {
throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
}
return $model;
}
}

View File

@@ -0,0 +1,42 @@
<?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\ServerErrorHttpException;
/**
* DeleteAction implements the API endpoint for deleting a model.
*
* For more details and usage information on DeleteAction, see the [guide article on rest controllers](guide:rest-controllers).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class DeleteAction extends Action
{
/**
* Deletes a model.
* @param mixed $id id of the model to be deleted.
* @throws ServerErrorHttpException on failure.
*/
public function run($id)
{
$model = $this->findModel($id);
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id, $model);
}
if ($model->delete() === false) {
throw new ServerErrorHttpException('Failed to delete the object for unknown reason.');
}
Yii::$app->getResponse()->setStatusCode(204);
}
}

130
vendor/yiisoft/yii2/rest/IndexAction.php vendored Normal file
View File

@@ -0,0 +1,130 @@
<?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;
use yii\data\DataFilter;
/**
* IndexAction implements the API endpoint for listing multiple models.
*
* For more details and usage information on IndexAction, see the [guide article on rest controllers](guide:rest-controllers).
*
* @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 (IndexAction $action) {
* // $action is the action object currently running
* }
* ```
*
* The callable should return an instance of [[ActiveDataProvider]].
*
* If [[dataFilter]] is set the result of [[DataFilter::build()]] will be passed to the callable as a second parameter.
* In this case the signature of the callable should be the following:
*
* ```php
* function (IndexAction $action, mixed $filter) {
* // $action is the action object currently running
* // $filter the built filter condition
* }
* ```
*/
public $prepareDataProvider;
/**
* @var DataFilter|null data filter to be used for the search filter composition.
* You must setup this field explicitly in order to enable filter processing.
* For example:
*
* ```php
* [
* 'class' => 'yii\data\ActiveDataFilter',
* 'searchModel' => function () {
* return (new \yii\base\DynamicModel(['id' => null, 'name' => null, 'price' => null]))
* ->addRule('id', 'integer')
* ->addRule('name', 'trim')
* ->addRule('name', 'string')
* ->addRule('price', 'number');
* },
* ]
* ```
*
* @see DataFilter
*
* @since 2.0.13
*/
public $dataFilter;
/**
* @return ActiveDataProvider
*/
public function run()
{
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id);
}
return $this->prepareDataProvider();
}
/**
* Prepares the data provider that should return the requested collection of the models.
* @return ActiveDataProvider
*/
protected function prepareDataProvider()
{
$requestParams = Yii::$app->getRequest()->getBodyParams();
if (empty($requestParams)) {
$requestParams = Yii::$app->getRequest()->getQueryParams();
}
$filter = null;
if ($this->dataFilter !== null) {
$this->dataFilter = Yii::createObject($this->dataFilter);
if ($this->dataFilter->load($requestParams)) {
$filter = $this->dataFilter->build();
if ($filter === false) {
return $this->dataFilter;
}
}
}
if ($this->prepareDataProvider !== null) {
return call_user_func($this->prepareDataProvider, $this, $filter);
}
/* @var $modelClass \yii\db\BaseActiveRecord */
$modelClass = $this->modelClass;
$query = $modelClass::find();
if (!empty($filter)) {
$query->andWhere($filter);
}
return Yii::createObject([
'class' => ActiveDataProvider::className(),
'query' => $query,
'pagination' => [
'params' => $requestParams,
],
'sort' => [
'params' => $requestParams,
],
]);
}
}

View File

@@ -0,0 +1,46 @@
<?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.
*
* For more details and usage information on OptionsAction, see the [guide article on rest controllers](guide:rest-controllers).
*
* @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', 'HEAD', 'OPTIONS'];
/**
* @var array the HTTP verbs that are supported by the resource URL
*/
public $resourceOptions = ['GET', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
/**
* Responds to the OPTIONS request.
* @param string $id
*/
public function run($id = null)
{
if (Yii::$app->getRequest()->getMethod() !== 'OPTIONS') {
Yii::$app->getResponse()->setStatusCode(405);
}
$options = $id === null ? $this->collectionOptions : $this->resourceOptions;
$headers = Yii::$app->getResponse()->getHeaders();
$headers->set('Allow', implode(', ', $options));
$headers->set('Access-Control-Allow-Methods', implode(', ', $options));
}
}

300
vendor/yiisoft/yii2/rest/Serializer.php vendored Normal file
View File

@@ -0,0 +1,300 @@
<?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\Arrayable;
use yii\base\Component;
use yii\base\Model;
use yii\data\DataProviderInterface;
use yii\data\Pagination;
use yii\helpers\ArrayHelper;
use yii\web\Link;
use yii\web\Request;
use yii\web\Response;
/**
* Serializer converts resource objects and collections into array representation.
*
* Serializer is mainly used by REST controllers to convert different objects into array representation
* so that they can be further turned into different formats, such as JSON, XML, by response formatters.
*
* The default implementation handles resources as [[Model]] objects and collections as objects
* implementing [[DataProviderInterface]]. You may override [[serialize()]] to handle more types.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Serializer extends Component
{
/**
* @var string the name of the query parameter containing the information about which fields should be returned
* for a [[Model]] object. If the parameter is not provided or empty, the default set of fields as defined
* by [[Model::fields()]] will be returned.
*/
public $fieldsParam = 'fields';
/**
* @var string the name of the query parameter containing the information about which fields should be returned
* in addition to those listed in [[fieldsParam]] for a resource object.
*/
public $expandParam = 'expand';
/**
* @var string the name of the HTTP header containing the information about total number of data items.
* This is used when serving a resource collection with pagination.
*/
public $totalCountHeader = 'X-Pagination-Total-Count';
/**
* @var string the name of the HTTP header containing the information about total number of pages of data.
* This is used when serving a resource collection with pagination.
*/
public $pageCountHeader = 'X-Pagination-Page-Count';
/**
* @var string the name of the HTTP header containing the information about the current page number (1-based).
* This is used when serving a resource collection with pagination.
*/
public $currentPageHeader = 'X-Pagination-Current-Page';
/**
* @var string the name of the HTTP header containing the information about the number of data items in each page.
* This is used when serving a resource collection with pagination.
*/
public $perPageHeader = 'X-Pagination-Per-Page';
/**
* @var string the name of the envelope (e.g. `items`) for returning the resource objects in a collection.
* This is used when serving a resource collection. When this is set and pagination is enabled, the serializer
* will return a collection in the following format:
*
* ```php
* [
* 'items' => [...], // assuming collectionEnvelope is "items"
* '_links' => { // pagination links as returned by Pagination::getLinks()
* 'self' => '...',
* 'next' => '...',
* 'last' => '...',
* },
* '_meta' => { // meta information as returned by Pagination::toArray()
* 'totalCount' => 100,
* 'pageCount' => 5,
* 'currentPage' => 1,
* 'perPage' => 20,
* },
* ]
* ```
*
* If this property is not set, the resource arrays will be directly returned without using envelope.
* The pagination information as shown in `_links` and `_meta` can be accessed from the response HTTP headers.
*/
public $collectionEnvelope;
/**
* @var string the name of the envelope (e.g. `_links`) for returning the links objects.
* It takes effect only, if `collectionEnvelope` is set.
* @since 2.0.4
*/
public $linksEnvelope = '_links';
/**
* @var string the name of the envelope (e.g. `_meta`) for returning the pagination object.
* It takes effect only, if `collectionEnvelope` is set.
* @since 2.0.4
*/
public $metaEnvelope = '_meta';
/**
* @var Request the current request. If not set, the `request` application component will be used.
*/
public $request;
/**
* @var Response the response to be sent. If not set, the `response` application component will be used.
*/
public $response;
/**
* @var bool whether to preserve array keys when serializing collection data.
* Set this to `true` to allow serialization of a collection as a JSON object where array keys are
* used to index the model objects. The default is to serialize all collections as array, regardless
* of how the array is indexed.
* @see serializeDataProvider()
* @since 2.0.10
*/
public $preserveKeys = false;
/**
* {@inheritdoc}
*/
public function init()
{
if ($this->request === null) {
$this->request = Yii::$app->getRequest();
}
if ($this->response === null) {
$this->response = Yii::$app->getResponse();
}
}
/**
* Serializes the given data into a format that can be easily turned into other formats.
* This method mainly converts the objects of recognized types into array representation.
* It will not do conversion for unknown object types or non-object data.
* The default implementation will handle [[Model]] and [[DataProviderInterface]].
* You may override this method to support more object types.
* @param mixed $data the data to be serialized.
* @return mixed the converted data.
*/
public function serialize($data)
{
if ($data instanceof Model && $data->hasErrors()) {
return $this->serializeModelErrors($data);
} elseif ($data instanceof Arrayable) {
return $this->serializeModel($data);
} elseif ($data instanceof DataProviderInterface) {
return $this->serializeDataProvider($data);
}
return $data;
}
/**
* @return array the names of the requested fields. The first element is an array
* representing the list of default fields requested, while the second element is
* an array of the extra fields requested in addition to the default fields.
* @see Model::fields()
* @see Model::extraFields()
*/
protected function getRequestedFields()
{
$fields = $this->request->get($this->fieldsParam);
$expand = $this->request->get($this->expandParam);
return [
is_string($fields) ? preg_split('/\s*,\s*/', $fields, -1, PREG_SPLIT_NO_EMPTY) : [],
is_string($expand) ? preg_split('/\s*,\s*/', $expand, -1, PREG_SPLIT_NO_EMPTY) : [],
];
}
/**
* Serializes a data provider.
* @param DataProviderInterface $dataProvider
* @return array the array representation of the data provider.
*/
protected function serializeDataProvider($dataProvider)
{
if ($this->preserveKeys) {
$models = $dataProvider->getModels();
} else {
$models = array_values($dataProvider->getModels());
}
$models = $this->serializeModels($models);
if (($pagination = $dataProvider->getPagination()) !== false) {
$this->addPaginationHeaders($pagination);
}
if ($this->request->getIsHead()) {
return null;
} elseif ($this->collectionEnvelope === null) {
return $models;
}
$result = [
$this->collectionEnvelope => $models,
];
if ($pagination !== false) {
return array_merge($result, $this->serializePagination($pagination));
}
return $result;
}
/**
* Serializes a pagination into an array.
* @param Pagination $pagination
* @return array the array representation of the pagination
* @see addPaginationHeaders()
*/
protected function serializePagination($pagination)
{
return [
$this->linksEnvelope => Link::serialize($pagination->getLinks(true)),
$this->metaEnvelope => [
'totalCount' => $pagination->totalCount,
'pageCount' => $pagination->getPageCount(),
'currentPage' => $pagination->getPage() + 1,
'perPage' => $pagination->getPageSize(),
],
];
}
/**
* Adds HTTP headers about the pagination to the response.
* @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));
}
/**
* Serializes a model object.
* @param Arrayable $model
* @return array the array representation of the model
*/
protected function serializeModel($model)
{
if ($this->request->getIsHead()) {
return null;
}
list($fields, $expand) = $this->getRequestedFields();
return $model->toArray($fields, $expand);
}
/**
* Serializes the validation errors in a model.
* @param Model $model
* @return array the array representation of the errors
*/
protected function serializeModelErrors($model)
{
$this->response->setStatusCode(422, 'Data Validation Failed.');
$result = [];
foreach ($model->getFirstErrors() as $name => $message) {
$result[] = [
'field' => $name,
'message' => $message,
];
}
return $result;
}
/**
* Serializes a set of models.
* @param array $models
* @return array the array representation of the models
*/
protected function serializeModels(array $models)
{
list($fields, $expand) = $this->getRequestedFields();
foreach ($models as $i => $model) {
if ($model instanceof Arrayable) {
$models[$i] = $model->toArray($fields, $expand);
} elseif (is_array($model)) {
$models[$i] = ArrayHelper::toArray($model);
}
}
return $models;
}
}

View File

@@ -0,0 +1,54 @@
<?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\Model;
use yii\db\ActiveRecord;
use yii\web\ServerErrorHttpException;
/**
* UpdateAction implements the API endpoint for updating a model.
*
* For more details and usage information on UpdateAction, see the [guide article on rest controllers](guide:rest-controllers).
*
* @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 = Model::SCENARIO_DEFAULT;
/**
* Updates an existing model.
* @param string $id the primary key of the model.
* @return \yii\db\ActiveRecordInterface the model being updated
* @throws ServerErrorHttpException if there is any error when updating the model
*/
public function run($id)
{
/* @var $model ActiveRecord */
$model = $this->findModel($id);
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id, $model);
}
$model->scenario = $this->scenario;
$model->load(Yii::$app->getRequest()->getBodyParams(), '');
if ($model->save() === false && !$model->hasErrors()) {
throw new ServerErrorHttpException('Failed to update the object for unknown reason.');
}
return $model;
}
}

270
vendor/yiisoft/yii2/rest/UrlRule.php vendored Normal file
View File

@@ -0,0 +1,270 @@
<?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;
use yii\web\UrlRule as WebUrlRule;
use yii\web\UrlRuleInterface;
/**
* UrlRule is provided to simplify the 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/overview/options of a user
* - `'POST users' => 'user/create'`: create a new user
* - `'GET,HEAD users' => 'user/index'`: return a list/overview/options of users
* - `'users/<id>' => 'user/options'`: process all unhandled verbs of a user
* - `'users' => 'user/options'`: process all unhandled verbs of user collection
*
* 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 represent one or multiple controller IDs.
* Each controller ID 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).
*
* For more details and usage information on UrlRule, see the [guide article on rest routing](guide:rest-routing).
*
* @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 patterns for supporting extra actions in addition to those listed in [[patterns]].
* The keys are the patterns and the values are the corresponding action IDs.
* These extra patterns will take precedence over [[patterns]].
*/
public $extraPatterns = [];
/**
* @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 Pattern`, where `Verbs` stands for a list of HTTP verbs separated
* by comma (without space). If `Verbs` is not specified, it means all verbs are allowed.
* `Pattern` is optional. It will be prefixed with [[prefix]]/[[controller]]/,
* and tokens in it will be replaced by [[tokens]].
*/
public $patterns = [
'PUT,PATCH {id}' => 'update',
'DELETE {id}' => 'delete',
'GET,HEAD {id}' => 'view',
'POST' => 'create',
'GET,HEAD' => 'index',
'{id}' => 'options',
'' => 'options',
];
/**
* @var array the default configuration for creating each URL rule contained by this rule.
*/
public $ruleConfig = [
'class' => 'yii\web\UrlRule',
];
/**
* @var bool whether to automatically pluralize the URL names for controllers.
* If true, a controller ID will appear in plural form in URLs. For example, `user` controller
* will appear as `users` in URLs.
* @see controller
*/
public $pluralize = true;
/**
* {@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_int($urlName)) {
$urlName = $this->pluralize ? Inflector::pluralize($controller) : $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);
$patterns = $this->extraPatterns + $this->patterns;
$rules = [];
foreach ($this->controller as $urlName => $controller) {
$prefix = trim($this->prefix . '/' . $urlName, '/');
foreach ($patterns as $pattern => $action) {
if (!isset($except[$action]) && (empty($only) || isset($only[$action]))) {
$rules[$urlName][] = $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 UrlRuleInterface
*/
protected function createRule($pattern, $prefix, $action)
{
$verbs = 'GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS';
if (preg_match("/^((?:($verbs),)*($verbs))(?:\\s+(.*))?$/", $pattern, $matches)) {
$verbs = explode(',', $matches[1]);
$pattern = isset($matches[4]) ? $matches[4] : '';
} else {
$verbs = [];
}
$config = $this->ruleConfig;
$config['verb'] = $verbs;
$config['pattern'] = rtrim($prefix . '/' . strtr($pattern, $this->tokens), '/');
$config['route'] = $action;
if (!empty($verbs) && !in_array('GET', $verbs)) {
$config['mode'] = WebUrlRule::PARSING_ONLY;
}
$config['suffix'] = $this->suffix;
return Yii::createObject($config);
}
/**
* {@inheritdoc}
*/
public function parseRequest($manager, $request)
{
$pathInfo = $request->getPathInfo();
foreach ($this->rules as $urlName => $rules) {
if (strpos($pathInfo, $urlName) !== false) {
foreach ($rules as $rule) {
/* @var $rule WebUrlRule */
$result = $rule->parseRequest($manager, $request);
if (YII_DEBUG) {
Yii::debug([
'rule' => method_exists($rule, '__toString') ? $rule->__toString() : get_class($rule),
'match' => $result !== false,
'parent' => self::className(),
], __METHOD__);
}
if ($result !== false) {
return $result;
}
}
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function createUrl($manager, $route, $params)
{
$this->createStatus = WebUrlRule::CREATE_STATUS_SUCCESS;
foreach ($this->controller as $urlName => $controller) {
if (strpos($route, $controller) !== false) {
/* @var $rules UrlRuleInterface[] */
$rules = $this->rules[$urlName];
$url = $this->iterateRules($rules, $manager, $route, $params);
if ($url !== false) {
return $url;
}
} else {
$this->createStatus |= WebUrlRule::CREATE_STATUS_ROUTE_MISMATCH;
}
}
if ($this->createStatus === WebUrlRule::CREATE_STATUS_SUCCESS) {
// create status was not changed - there is no rules configured
$this->createStatus = WebUrlRule::CREATE_STATUS_PARSING_ONLY;
}
return false;
}
}

36
vendor/yiisoft/yii2/rest/ViewAction.php vendored Normal file
View File

@@ -0,0 +1,36 @@
<?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.
*
* For more details and usage information on ViewAction, see the [guide article on rest controllers](guide:rest-controllers).
*
* @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->id, $model);
}
return $model;
}
}