andersao / andersao/l5-repository

Attribute setter firing twice if validation rules/validator is set.

オープン
#421 コメント 0 件 リアクション 1 件 担当者 0 名 GitHub で見る
主要言語
PHP
スター
4.2k
フォーク
880
PR マージ指標
30日以内にマージされた PR はありません

説明

Package version: "prettus/l5-repository": "^2.6"
Laravel version: 5.4

When validation rules are specified on a concrete repository, if a setter mutator is defined for a model attribute it gets called twice when create() is called on the repository (possibly when other methods are called as well).

This is my model (simplified version):
```
class HistoryItem extends Model implements Transformable
{
use TransformableTrait;

protected $dates = [
'active_to'
];

function setActiveToAttribute($date){
$this->attributes['active_to'] = Carbon::parse($date)->addMinute();
}
}
```

This is the concrete repository:
```
class HistoryItemsRepositoryEloquent extends BaseRepository implements HistoryItemsRepository
{
protected $rules = [
ValidatorInterface::RULE_CREATE => [

],
ValidatorInterface::RULE_UPDATE => [

]
];

/**
* Specify Model class name
*
* @return string
*/
public function model()
{
return HistoryItem::class;
}

/**
* Boot up the repository, pushing criteria
*/
public function boot()
{
$this->pushCriteria(app(RequestCriteria::class));
}
}
```

This is the call to the create function:
```
$this->repository->create(['active_to' => '2017-05-05 00:00:00']);
```

The resulting attribute persisted to the database is a Carbon instance with the value '2017-05-05 00:02:00' instead of '2017-05-05 00:01:00'. Similar thing can be observed when the mutator is ->addMinutes(2), the resulting attribute value is '2017-05-05 00:04:00'.

After a code trace I can confirm this happens here in the BaseRepository (places of occurrence noted by ** ** comments):
```
public function create(array $attributes)
{
if (!is_null($this->validator)) {
// we should pass data that has been casts by the model
// to make sure data type are same because validator may need to use
// this data to compare with data that fetch from database.
**//FIRST SETTERS CALL HERE**
$attributes = $this->model->newInstance()->forceFill($attributes)->makeVisible($this->model->getHidden())->toArray();

$this->validator->with($attributes)->passesOrFail(ValidatorInterface::RULE_CREATE);
}

**//SECOND SETTERS CALL HERE**
$model = $this->model->newInstance($attributes);
$model->save();
$this->resetModel();

event(new RepositoryEntityCreated($this, $model));

return $this->parserResult($model);
}
```

Is this a known issue and are there any plans to address this? If not, I'll be happy to submit a PR.

コントリビューションガイド

コントリビューションガイドを開く

評価

この issue はまだ評価されていません。

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。