Skip to content

Instantly share code, notes, and snippets.

@linuskohl
Created August 20, 2018 20:21
Show Gist options
  • Save linuskohl/0560dfb5d273e775120e74ca5e55ca60 to your computer and use it in GitHub Desktop.
Save linuskohl/0560dfb5d273e775120e74ca5e55ca60 to your computer and use it in GitHub Desktop.
Custom Yii2 serializer that allows masking and setting default fields and expands
<?php
namespace app\components;
use yii\base\InvalidConfigException;
/**
* Class CustomSerializer
*
* Serializer
*
* @license https://opensource.org/licenses/GPL-3.0 GPL-3.0
* @copyright 2018-2021 Linus Kohl <[email protected]>
*/
class CustomSerializer extends \yii\rest\Serializer
{
/** @var string[] $defaultFields */
public $defaultFields = [];
/** @var string[] $maskedFields */
public $maskedFields = [];
/** @var string[] $defaultExpand */
public $defaultExpand = [];
/** @var string[] $maskedExpands */
public $maskedExpands = [];
/** {@inheritdoc} */
public function init()
{
parent::init();
// validate config
if (!is_array($this->defaultFields) ||
!is_array($this->maskedFields) ||
!is_array($this->defaultExpand) ||
!is_array($this->maskedExpands)) {
throw new InvalidConfigException();
}
}
/** {@inheritdoc} */
protected function getRequestedFields()
{
$fields = [];
$expand = [];
// values passed by request
$fields_string = $this->request->get($this->fieldsParam);
$expand_string = $this->request->get($this->expandParam);
if (!is_null($fields_string)) {
// slit to array of strings
$fields = preg_split('/\s*,\s*/', $fields_string, -1, PREG_SPLIT_NO_EMPTY);
} else {
// set to default
$fields = $this->defaultFields;
}
// filter masked fields
$fields = array_diff($fields, $this->maskedFields);
if (!is_null($expand_string)) {
// slit to array of strings
$expand = preg_split('/\s*,\s*/', $expand_string, -1, PREG_SPLIT_NO_EMPTY);
} else {
// set to default
$fields = $this->defaultExpand;
}
// filter expands
$expand = array_diff($expand, $this->maskedExpands);
return [$fields, $expand];
}
}
@linuskohl
Copy link
Author

Example usage:
public $serializer = [
'class' => CustomSerializer::class,
'defaultFields' => ['id', 'created_at', 'updated_at'],
'defaultExpand' => ['n1'],
'maskedExpands' => ['n2','n3'],
];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment