2016-04-28 14:16:33 +02:00
|
|
|
<?php namespace App\Http\Requests;
|
|
|
|
|
|
|
|
use Input;
|
|
|
|
use Utils;
|
2016-08-31 21:10:41 +02:00
|
|
|
use App\Libraries\HistoryUtils;
|
2016-12-08 21:51:53 +01:00
|
|
|
use App\Models\EntityModel;
|
2016-04-28 14:16:33 +02:00
|
|
|
|
2016-05-01 13:31:10 +02:00
|
|
|
class EntityRequest extends Request {
|
2016-04-28 14:16:33 +02:00
|
|
|
|
|
|
|
protected $entityType;
|
|
|
|
private $entity;
|
|
|
|
|
2016-06-07 20:13:29 +02:00
|
|
|
public function entity()
|
2016-04-28 14:16:33 +02:00
|
|
|
{
|
|
|
|
if ($this->entity) {
|
|
|
|
return $this->entity;
|
|
|
|
}
|
2016-05-01 13:31:10 +02:00
|
|
|
|
2016-05-09 19:35:50 +02:00
|
|
|
// The entity id can appear as invoices, invoice_id, public_id or id
|
|
|
|
$publicId = false;
|
2016-07-06 20:35:16 +02:00
|
|
|
$field = $this->entityType . '_id';
|
|
|
|
if ( ! empty($this->$field)) {
|
|
|
|
$publicId = $this->$field;
|
|
|
|
}
|
|
|
|
if ( ! $publicId) {
|
|
|
|
$field = Utils::pluralizeEntityType($this->entityType);
|
|
|
|
if ( ! empty($this->$field)) {
|
|
|
|
$publicId = $this->$field;
|
2016-06-07 20:13:29 +02:00
|
|
|
}
|
2016-05-09 19:35:50 +02:00
|
|
|
}
|
|
|
|
if ( ! $publicId) {
|
|
|
|
$publicId = Input::get('public_id') ?: Input::get('id');
|
|
|
|
}
|
2016-04-28 14:16:33 +02:00
|
|
|
if ( ! $publicId) {
|
|
|
|
return null;
|
2016-06-07 20:13:29 +02:00
|
|
|
}
|
|
|
|
|
2016-12-08 21:51:53 +01:00
|
|
|
$class = EntityModel::getClassName($this->entityType);
|
2016-06-07 20:13:29 +02:00
|
|
|
|
2016-12-08 21:51:53 +01:00
|
|
|
if (method_exists($class, 'trashed')) {
|
|
|
|
$this->entity = $class::scope($publicId)->withTrashed()->firstOrFail();
|
|
|
|
} else {
|
|
|
|
$this->entity = $class::scope($publicId)->firstOrFail();
|
|
|
|
}
|
2016-11-04 20:20:33 +01:00
|
|
|
|
2016-04-28 14:16:33 +02:00
|
|
|
return $this->entity;
|
|
|
|
}
|
2016-05-01 13:31:10 +02:00
|
|
|
|
2016-08-08 16:45:37 +02:00
|
|
|
public function setEntity($entity)
|
|
|
|
{
|
|
|
|
$this->entity = $entity;
|
|
|
|
}
|
|
|
|
|
2016-05-01 13:31:10 +02:00
|
|
|
public function authorize()
|
|
|
|
{
|
|
|
|
if ($this->entity()) {
|
2016-08-31 21:10:41 +02:00
|
|
|
if ($this->user()->can('view', $this->entity())) {
|
|
|
|
HistoryUtils::trackViewed($this->entity());
|
|
|
|
return true;
|
|
|
|
}
|
2016-05-01 13:31:10 +02:00
|
|
|
} else {
|
|
|
|
return $this->user()->can('create', $this->entityType);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public function rules()
|
|
|
|
{
|
|
|
|
return [];
|
|
|
|
}
|
2016-08-31 21:10:41 +02:00
|
|
|
|
2016-04-28 14:16:33 +02:00
|
|
|
}
|