matthew-p/yii2-extended-api

Extension extends the capabilities of standard classes Yii2 API

2.0.0 2020-02-19 12:27 UTC

This package is auto-updated.

Last update: 2023-08-19 20:53:50 UTC


README

Package extends the capabilities of standard classes Yii2 API

Latest Stable Version node (scoped with tag) Coverage Status Scrutinizer Code Intelligence Software License composer.lock

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist matthew-p/yii2-extended-api "*"

or add

"matthew-p/yii2-extended-api": "@dev"

to the require section of your composer.json file.

Usage

Once the extension is installed, simply use it in your code by:

REST Controller for ExampleProduct model:

use MP\ExtendedApi\EActiveController;

class ProductsController extends EActiveController
{
    /**
     * @var string
     */
    public $modelClass = ExampleProduct::class;

    /**
     * @var string
     */
    public $searchClass = ExampleProductSearch::class;

    /**
     * @var bool
     */
    public $errorFilter = true;
    
    /**
     * @var array
     */
    public $externalActions = [
        'delete-all' => true,
    ];

    /**
     * @inheritdoc
     */
    public function behaviors(): array
    {
        return array_merge(parent::behaviors(), [
            'authenticator' => [
                'class' => HttpBearerAuth::class,
            ],
            'access'        => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => [User::ROLE_API],
                    ],
                ],
            ],
        ]);
    }

    /**
     * @inheritdoc
     * @throws NotFoundHttpException
     */
    public function filterError()
    {
        throw new NotFoundHttpException(Yii::t('app', 'Product not found'), self::FILTER_ERROR_CODE);
    }
}

REST Search model for ExampleProduct:

use MP\ExtendedApi\ModelSearchInterface;

class ExampleProductSearch extends ExampleProduct implements ModelSearchInterface
{
    /**
     * @inheritdoc
     */
    public function rules(): array
    {
        // model rules ...
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search(array $params = []): ActiveDataProvider
    {
        $dataProvider = $this->getDataProvider();

        $query = $dataProvider->query;

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions

        return $dataProvider;
    }

    /**
     * @inheritdoc
     */
    public function getDataProvider(): ActiveDataProvider
    {
        return new ActiveDataProvider([
            'query'      => self::find(),
            'pagination' => [
                'defaultPageSize' => 20,
                'pageSizeLimit'   => [
                    0, 20, 50, 100,
                ],
            ],
        ]);
    }
}

Features:

  • Delete all models action (support filtering, add headers)
  • Update all models action (support filtering, add headers)
  • Filtering via custom data provider
  • Custom error if filter result empty
  • View action trigger
// In controller
$this->action->on(EViewAction::EVENT_RUN_VIEW_ACTION, function (Event $event) use ($action) {
    // you code...
});
  • Edit filter params
//  public function beforeAction($action) in controller
if ($action instanceof EIndexAction) {
    $filterParams = $action->getFilterParams();

    $filterParams['active'] = ExampleProduct::STATUS_ACTIVE;

    $action->setFilterParams($filterParams);
}
  • After prepare data provider trigger
  • Get deleted model for delete action
// public function afterAction($action, $result)
if ($action instanceof EDeleteAction) {
    $model = $action->getModel();
}
  • Custom query condition index and delete-all actions
use MP\ExtendedApi\EActiveController;

class ProductsController extends EActiveController
{
    public $actionsParams = [
       'index' => [
           'addQuery' => [self::class, 'customCondition'],
       ],
    ];
    
    public static function customCondition($query)
    {
        ...
    }
...
  • Filter by user for index and delete-all actions
use MP\ExtendedApi\EActiveController;

class ProductsController extends EActiveController
{
    public $actionsParams = [
       'index' => [
           'filterUser' => 'user_id', // table column name
       ],
    ];
   
...

That's all. Check it.