Skip to content

Commit f6fca9e

Browse files
kfreimantuyakhov
authored andcommitted
Add singular types support (#15)
* add singular types support * fix missed Inflector
1 parent ea84908 commit f6fca9e

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

src/ResourceTrait.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ public function getType()
2828
{
2929
$reflect = new \ReflectionClass($this);
3030
$className = $reflect->getShortName();
31-
return Inflector::pluralize(Inflector::camel2id($className));
31+
return Inflector::camel2id($className);
3232
}
3333

3434
/**

src/Serializer.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use yii\web\Linkable;
1515
use yii\web\Request;
1616
use yii\web\Response;
17+
use yii\helpers\Inflector;
1718

1819
class Serializer extends Component
1920
{
@@ -48,7 +49,10 @@ class Serializer extends Component
4849
* @var Response the response to be sent. If not set, the `response` application component will be used.
4950
*/
5051
public $response;
51-
52+
/**
53+
* @var bool whether to automatically pluralize the `type` of resource.
54+
*/
55+
public $pluralize = true;
5256

5357
/**
5458
* @inheritdoc
@@ -113,7 +117,7 @@ protected function serializeModel(ResourceInterface $model)
113117

114118
if (!empty($relationship)) {
115119
if (in_array($name, $included)) {
116-
$data['relationships'][$name]['data'] = $relationship;
120+
$data['relationships'][$name]['data'] = $relationship;
117121
}
118122
}
119123
if ($model instanceof LinksInterface) {
@@ -167,6 +171,9 @@ protected function serializeIdentifier(ResourceIdentifierInterface $identifier)
167171
if ($value === null || is_array($value) || (is_object($value) && !method_exists($value, '__toString'))) {
168172
throw new InvalidValueException("The value {$key} of resource object " . get_class($identifier) . ' MUST be a string.');
169173
}
174+
if ($key === 'type' && $this->pluralize) {
175+
$value = Inflector::pluralize($value);
176+
}
170177
$result[$key] = (string) $value;
171178
}
172179
return $result;

0 commit comments

Comments
 (0)