Skip to content

Commit

Permalink
[Style] maybe a bit of more readable code
Browse files Browse the repository at this point in the history
  • Loading branch information
tunecino committed May 31, 2019
1 parent d0f669c commit 07c2a3c
Show file tree
Hide file tree
Showing 7 changed files with 86 additions and 64 deletions.
14 changes: 9 additions & 5 deletions src/Action.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@ public function init()
parent::init();
$params = Yii::$app->request->queryParams;

if ($this->expectedParams($params) === false)
if ($this->expectedParams($params) === false) {
throw new InvalidConfigException("unexpected configurations.");
}

$this->relativeClass = $params['relativeClass'];
$this->relationName = $params['relationName'];
Expand All @@ -66,8 +67,9 @@ protected function expectedParams($params)
{
$expected = ['relativeClass', 'relationName', 'linkAttribute'];
foreach ($expected as $attr) {
if (isset($params[$attr]) === false) return false;
if ($attr === 'linkAttribute' && isset($params[$params[$attr]]) === false) return false;
if (isset($params[$attr]) === false || ($attr === 'linkAttribute' && isset($params[$params[$attr]]) === false)) {
return false;
}
}
return true;
}
Expand All @@ -82,11 +84,13 @@ public function getRelativeModel()
$relativeClass = $this->relativeClass;
$relModel = $relativeClass::findOne($this->relative_id);

if ($relModel === null)
if ($relModel === null) {
throw new NotFoundHttpException(StringHelper::basename($relativeClass) . " '$this->relative_id' not found.");
}

if ($this->checkAccess)
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id, $relModel);
}

return $relModel;
}
Expand Down
34 changes: 22 additions & 12 deletions src/CreateAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,9 @@ class CreateAction extends Action
*/
public function run()
{
if ($this->checkAccess)
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id);
}

$relModel = $this->getRelativeModel();
$relType = $relModel->getRelation($this->relationName);
Expand All @@ -61,21 +62,25 @@ public function run()
$model_attributes = $model->safeAttributes();
$junction = [];
foreach ($viaData as $key => $value) {
if (!in_array($key, $model_attributes)) $junction[$key] = $value;
if (!in_array($key, $model_attributes)) {
$junction[$key] = $value;
}
}
$viaData = $junction;
}

$model->load($bodyParams, '');

if ($model->save() === false && !$model->hasErrors())
if ($model->save() === false && !$model->hasErrors()) {
throw new ServerErrorHttpException('Failed to update the object for unknown reason.');
else if ($model->hasErrors()) return $model;
} else if ($model->hasErrors()) {
return $model;
}

$id = implode(',', array_values($model->getPrimaryKey(true)));

if ($isManyToMany) {
$extraColumns = $viaData === null ? [] : $viaData ;
$extraColumns = $viaData === null ? [] : $viaData;

if ($isManyToMany_viaClass) {
$viaRelation = $relType->via[1];
Expand All @@ -84,30 +89,35 @@ public function run()
$viaModel = new $viaClass;
$viaModel->scenario = $this->viaScenario;

if ($this->checkAccess)
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id, $viaModel);
}

$modelClass = $this->modelClass;
$pk = $modelClass::primaryKey()[0];

$attributes = array_merge([
$this->linkAttribute => $this->relative_id,
$relType->link[$pk] => $id
],$extraColumns);
], $extraColumns);

$viaModel->load($attributes, '');

if ($viaModel->save() === false && !$viaModel->hasErrors())
if ($viaModel->save() === false && !$viaModel->hasErrors()) {
throw new ServerErrorHttpException('Failed to update the object for unknown reason.');
else if ($viaModel->hasErrors()) return $viaModel;
} else if ($viaModel->hasErrors()) {
return $viaModel;
}
} else {
$relModel->link($this->relationName, $model, $extraColumns);
}
else $relModel->link($this->relationName, $model, $extraColumns);
} else {
$relModel->link($this->relationName, $model);
}
else $relModel->link($this->relationName, $model);

$response = Yii::$app->getResponse();
$response->setStatusCode(201);
$response->getHeaders()->set('Location', Url::to('',true) . '/' . $id);
$response->getHeaders()->set('Location', Url::to('', true) . '/' . $id);

return $model;
}
Expand Down
3 changes: 2 additions & 1 deletion src/IndexAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ class IndexAction extends Action
*/
public function run()
{
if ($this->checkAccess)
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id);
}

$relModel = $this->getRelativeModel();
$getter = 'get' . $this->relationName;
Expand Down
40 changes: 18 additions & 22 deletions src/LinkAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,9 @@ public function run($IDs)

if ($linked === false) {
$exist = $modelClass::find()->andWhere([$pk => $pk_value])->exists();

if ($exist === false)
if ($exist === false) {
throw new NotFoundHttpException(StringHelper::basename($modelClass) . " '$pk_value' not found.");

}
$to_link[] = $isManyToMany_viaClass ? $pk_value : $this->findModel($pk_value);
}
}
Expand All @@ -69,45 +68,44 @@ public function run($IDs)
$viaRelation = $relType->via[1];
$viaClass = $viaRelation->modelClass;

if (count($to_link) === 0 && count($bodyParams)===0)
if (count($to_link) === 0 && count($bodyParams)===0) {
Yii::$app->getResponse()->setStatusCode(304);

else {
} else {
foreach ($ids as $pk_value) {

if (in_array($pk_value, $to_link)) {
$viaModel = new $viaClass;
$viaModel->scenario = $this->viaScenario;

if ($this->checkAccess)
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id, $viaModel);
}

$attributes = array_merge([
$this->linkAttribute => $this->relative_id,
$relType->link[$pk] => $pk_value
],$bodyParams);

$viaModel->load($attributes, '');
}

else {
} else {
// already linked -> update data in junction table.
$viaModel = $viaClass::findOne([
$this->linkAttribute => $this->relative_id,
$relType->link[$pk] => $pk_value
]);

if ($this->checkAccess)
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id, $viaModel);
}

$viaModel->scenario = $this->viaScenario;
$viaModel->load($bodyParams, '');
}

if ($viaModel->save() === false && !$viaModel->hasErrors())
if ($viaModel->save() === false && !$viaModel->hasErrors()) {
throw new ServerErrorHttpException('Failed to update the object for unknown reason.');

else if ($viaModel->hasErrors()) return $viaModel;
} else if ($viaModel->hasErrors()) {
return $viaModel;
}
}
Yii::$app->getResponse()->setStatusCode(204);
}
Expand All @@ -118,17 +116,15 @@ public function run($IDs)
$extraColumns = $isManyToMany ? $bodyParams : [];

// junction table update is expected. inserting 2nd record won't be valid solution.
if (count($to_link) === 0 && count($extraColumns) > 0)
if (count($to_link) === 0 && count($extraColumns) > 0) {
throw new ServerErrorHttpException('objects already linked.');

else if (count($to_link) === 0)
} else if (count($to_link) === 0) {
Yii::$app->getResponse()->setStatusCode(304);

else {
} else {
foreach ($to_link as $model) {
if ($this->checkAccess)
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id, $model);

}
$relModel->link($this->relationName, $model, $extraColumns);
}
Yii::$app->getResponse()->setStatusCode(204);
Expand Down
12 changes: 7 additions & 5 deletions src/UnlinkAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,20 +40,22 @@ public function run($IDs)
$to_unlink = [];
foreach ($ids as $pk_value) {
$linked = $relModel->$getter()->andWhere([$pk => $pk_value])->exists();
if ($linked === true) $to_unlink []= $this->findModel($pk_value);
else throw new BadRequestHttpException(StringHelper::basename($modelClass) . " '$pk_value' not linked to ".StringHelper::basename($this->relativeClass)." '$this->relative_id'.");
if ($linked === true) {
$to_unlink[] = $this->findModel($pk_value);
} else {
throw new BadRequestHttpException(StringHelper::basename($modelClass) . " '$pk_value' not linked to ".StringHelper::basename($this->relativeClass)." '$this->relative_id'.");
}
}

$relType = $relModel->getRelation($this->relationName);
$delete = ($relType->multiple === true && $relType->via !== null);

foreach ($to_unlink as $model) {
if ($this->checkAccess)
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id, $model);

}
$relModel->unlink($this->relationName, $model, $delete);
}

Yii::$app->getResponse()->setStatusCode(204);
}
}
4 changes: 2 additions & 2 deletions src/UnlinkAllAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
*/
class UnlinkAllAction extends Action
{
/**
/**
* Unlinks all the related models.
* If the relation type is a many_to_many. related row in the junction table will be deleted.
* Otherwise related foreign key will be simply set to NULL.
Expand All @@ -26,7 +26,7 @@ class UnlinkAllAction extends Action
public function run()
{
$relModel = $this->getRelativeModel();

$relType = $relModel->getRelation($this->relationName);
$delete = ($relType->multiple === true && $relType->via !== null);

Expand Down
43 changes: 26 additions & 17 deletions src/UrlRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -131,23 +131,31 @@ protected function setRulesFactory($config)
public function init()
{
parent::init();
if (empty($this->modelClass))
if (empty($this->modelClass)) {
throw new InvalidConfigException('"modelClass" must be set.');
}

if (empty($this->relations))
if (empty($this->relations)) {
throw new InvalidConfigException('"relations" must be set.');
}

$this->config['patterns'] = $this->patterns;
$this->config['tokens'] = $this->tokens;
if (!empty($this->only)) $this->config['only'] = $this->only;
if (!empty($this->except)) $this->config['except'] = $this->except;
if (!empty($this->extraPatterns)) $this->config['extraPatterns'] = $this->extraPatterns;
if (!empty($this->only)) {
$this->config['only'] = $this->only;
}
if (!empty($this->except)) {
$this->config['except'] = $this->except;
}
if (!empty($this->extraPatterns)) {
$this->config['extraPatterns'] = $this->extraPatterns;
}
}

/**
* @inheritdoc
*/
public function createUrl($manager, $route, $params)
public function createUrl($manager, $route, $params)
{
if ($this->rulesFactory) {
unset($params['relativeClass'], $params['relationName'], $params['linkAttribute']);
Expand All @@ -163,34 +171,35 @@ public function parseRequest($manager, $request)
{
$modelName = Inflector::camel2id(StringHelper::basename($this->modelClass));

if ( isset($this->resourceName) ) {
if (isset($this->resourceName)) {
$resourceName = $this->resourceName;
}
else {
} else {
$resourceName = $this->pluralize ? Inflector::pluralize($modelName) : $modelName;
}

$link_attribute = isset($this->linkAttribute) ? $this->linkAttribute : $modelName . '_id';
$this->config['prefix'] = $resourceName . '/<' .$link_attribute. ':\d+>';
$this->config['prefix'] = $resourceName . '/<' . $link_attribute . ':\d+>';

foreach ($this->relations as $key => $value) {
if (is_int($key)) {
$relation = $value;
$urlName = $this->pluralize ? Inflector::camel2id(Inflector::pluralize($relation)) : Inflector::camel2id($relation);
$controller = Inflector::camel2id(Inflector::singularize($relation));
}
else {
} else {
$relation = $key;
if (is_array($value)) list($urlName, $controller) = each($value);
else {
if (is_array($value)) {
list($urlName, $controller) = each($value);
} else {
$urlName = $this->pluralize ? Inflector::camel2id(Inflector::pluralize($relation)) : Inflector::camel2id($relation);
$controller = $value;
}
}

if (YII_DEBUG) (new $this->modelClass)->getRelation($relation);
if (YII_DEBUG) {
(new $this->modelClass)->getRelation($relation);
}

$modulePrefix = isset($this->modulePrefix) ? $this->modulePrefix .'/' : '';
$modulePrefix = isset($this->modulePrefix) ? $this->modulePrefix . '/' : '';
$this->config['controller'][$urlName] = $modulePrefix . $controller;

$this->setRulesFactory($this->config);
Expand All @@ -206,4 +215,4 @@ public function parseRequest($manager, $request)

return false;
}
}
}

0 comments on commit 07c2a3c

Please sign in to comment.