From f1cb004e9c503e5c53f61bda2d726abed48313e5 Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Wed, 24 Jun 2020 15:33:44 +0100 Subject: [PATCH 01/24] Two links - Add a link for the docs page as well as the postman collection. --- resources/views/welcome.blade.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/resources/views/welcome.blade.php b/resources/views/welcome.blade.php index 572bfc81..0727664f 100644 --- a/resources/views/welcome.blade.php +++ b/resources/views/welcome.blade.php @@ -154,7 +154,8 @@ function gtag(){dataLayer.push(arguments);}

The documentation for the API is available as a Postman collection.

- Documentation + Docs and Examples + Postman Collection


From 26616daca3309fabd6ff8abbec4f0a72a8d2a061 Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Wed, 24 Jun 2020 15:57:44 +0100 Subject: [PATCH 02/24] *** Interim commit *** - Working on reworking the transformers --- .../Controllers/SubcategoryController.php | 6 +- app/Models/Transformers/ResourceType.php | 2 +- app/Models/Transformers/ResourceTypeItem.php | 70 +++++++------------ app/Models/Transformers/Subcategory.php | 23 ++---- app/Models/Transformers/Transformer.php | 36 ++++++++-- 5 files changed, 65 insertions(+), 72 deletions(-) diff --git a/app/Http/Controllers/SubcategoryController.php b/app/Http/Controllers/SubcategoryController.php index 1b5aef11..5d0b15f6 100644 --- a/app/Http/Controllers/SubcategoryController.php +++ b/app/Http/Controllers/SubcategoryController.php @@ -91,7 +91,7 @@ public function index($resource_type_id, $category_id): JsonResponse $collection = array_map( static function ($subcategory) { - return (new SubcategoryTransformer($subcategory))->toArray(); + return (new SubcategoryTransformer($subcategory))->asArray(); }, $subcategories ); @@ -145,7 +145,7 @@ public function show( $headers->item(); return response()->json( - (new SubcategoryTransformer($subcategory))->toArray(), + (new SubcategoryTransformer($subcategory))->asArray(), 200, $headers->headers() ); @@ -294,7 +294,7 @@ public function create($resource_type_id, $category_id): JsonResponse } return response()->json( - (new SubcategoryTransformer((new Subcategory())->instanceToArray($sub_category)))->toArray(), + (new SubcategoryTransformer((new Subcategory())->instanceToArray($sub_category)))->asArray(), 201 ); } diff --git a/app/Models/Transformers/ResourceType.php b/app/Models/Transformers/ResourceType.php index b7bba6a6..6a116615 100644 --- a/app/Models/Transformers/ResourceType.php +++ b/app/Models/Transformers/ResourceType.php @@ -6,7 +6,7 @@ use App\Models\Transformers\Resource as ResourceTransformer; /** - * Transform the data returns from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 diff --git a/app/Models/Transformers/ResourceTypeItem.php b/app/Models/Transformers/ResourceTypeItem.php index 7653158b..143bac35 100644 --- a/app/Models/Transformers/ResourceTypeItem.php +++ b/app/Models/Transformers/ResourceTypeItem.php @@ -4,10 +4,7 @@ namespace App\Models\Transformers; /** - * Transform the data array into the format we require for the API - * - * This is an updated version of the transformers, the other transformers need to - * be updated to operate on array rather than collections + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -15,63 +12,44 @@ */ class ResourceTypeItem extends Transformer { - protected $item; - - /** - * @param array $item - */ - public function __construct(array $item) + protected function format(array $to_transform): void { - parent::__construct(); - - $this->item = $item; - } - - /** - * Return the formatted array - * - * @return array - */ - public function toArray(): array - { - $item = [ - 'id' => $this->hash->item()->encode($this->item['item_id']), - 'name' => $this->item['item_name'], - 'description' => $this->item['item_description'], - 'total' => number_format((float) $this->item['item_total'], 2, '.', ''), - 'percentage' => (int) $this->item['item_percentage'], - 'actualised_total' => number_format((float) $this->item['item_actualised_total'], 2, '.', ''), - 'effective_date' => $this->item['item_effective_date'], - 'created' => $this->item['item_created_at'], + $this->transformed = [ + 'id' => $this->hash->item()->encode($to_transform['item_id']), + 'name' => $to_transform['item_name'], + 'description' => $to_transform['item_description'], + 'total' => number_format((float) $to_transform['item_total'], 2, '.', ''), + 'percentage' => (int) $to_transform['item_percentage'], + 'actualised_total' => number_format((float) $to_transform['item_actualised_total'], 2, '.', ''), + 'effective_date' => $to_transform['item_effective_date'], + 'created' => $to_transform['item_created_at'], 'resource' => [ - 'id' => $this->hash->resource()->encode($this->item['resource_id']), - 'name' => $this->item['resource_name'], - 'description' => $this->item['resource_description'] + 'id' => $this->hash->resource()->encode($to_transform['resource_id']), + 'name' => $to_transform['resource_name'], + 'description' => $to_transform['resource_description'] ] ]; if ( - array_key_exists('category_id', $this->item) === true && - array_key_exists('category_name', $this->item) === true + array_key_exists('category_id', $to_transform) === true && + array_key_exists('category_name', $to_transform) === true ) { $item['category'] = [ - 'id' => $this->hash->category()->encode($this->item['category_id']), - 'name' => $this->item['category_name'], - 'description' => $this->item['category_description'] + 'id' => $this->hash->category()->encode($to_transform['category_id']), + 'name' => $to_transform['category_name'], + 'description' => $to_transform['category_description'] ]; if ( - array_key_exists('subcategory_id', $this->item) === true && - array_key_exists('subcategory_name', $this->item) === true + array_key_exists('subcategory_id', $to_transform) === true && + array_key_exists('subcategory_name', $to_transform) === true ) { $item['subcategory'] = [ - 'id' => $this->hash->subCategory()->encode($this->item['subcategory_id']), - 'name' => $this->item['subcategory_name'], - 'description' => $this->item['subcategory_description'] + 'id' => $this->hash->subCategory()->encode($to_transform['subcategory_id']), + 'name' => $to_transform['subcategory_name'], + 'description' => $to_transform['subcategory_description'] ]; } } - - return $item; } } diff --git a/app/Models/Transformers/Subcategory.php b/app/Models/Transformers/Subcategory.php index f981435a..fe64f8e2 100644 --- a/app/Models/Transformers/Subcategory.php +++ b/app/Models/Transformers/Subcategory.php @@ -4,7 +4,7 @@ namespace App\Models\Transformers; /** - * Transform the data returns from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -12,22 +12,13 @@ */ class Subcategory extends Transformer { - protected $data_to_transform; - - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + protected function format(array $to_transform): void { - return [ - 'id' => $this->hash->subCategory()->encode($this->data_to_transform['subcategory_id']), - 'name' => $this->data_to_transform['subcategory_name'], - 'description' => $this->data_to_transform['subcategory_description'], - 'created' => $this->data_to_transform['subcategory_created_at'] + $this->transformed = [ + 'id' => $this->hash->subCategory()->encode($to_transform['subcategory_id']), + 'name' => $to_transform['subcategory_name'], + 'description' => $to_transform['subcategory_description'], + 'created' => $to_transform['subcategory_created_at'] ]; } } diff --git a/app/Models/Transformers/Transformer.php b/app/Models/Transformers/Transformer.php index 00b59f4e..5f72e447 100644 --- a/app/Models/Transformers/Transformer.php +++ b/app/Models/Transformers/Transformer.php @@ -6,7 +6,8 @@ use App\Utilities\Hash; /** - * Base transformer class, sets up the interface and includes helper methods + * Our base transformer class, used to convert the results of our queries into + * a useful structure and then the required format * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -14,17 +15,40 @@ */ abstract class Transformer { - protected $hash; + protected Hash $hash; - public function __construct() + protected array $transformed; + + /** + * Pass in the data we want to format for output + * + * @param array $to_transform + */ + public function __construct(array $to_transform) { $this->hash = new Hash(); + + $this->format($to_transform); } - abstract public function toArray(): array; + /** + * Format the data + * + * @param array $to_transform + */ + abstract protected function format(array $to_transform): void; + + public function asJson(): ?string + { + try { + return json_encode($this->transformed, JSON_THROW_ON_ERROR | 15); + } catch (\JsonException $e) { + return null; + } + } - public function toJson(): string + public function asArray(): array { - return json_encode($this->toArray()); + return $this->transformed; } } From b734606c39cf99a8c7b8a05657cbbfa9cd4629ac Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Thu, 25 Jun 2020 01:04:33 +0100 Subject: [PATCH 03/24] Refacoring - We have reworked all the transformers, simplifying them. --- .../Controllers/ResourceTypeController.php | 6 +- app/Models/Transformers/Category.php | 53 ++++-------- app/Models/Transformers/Item.php | 66 -------------- app/Models/Transformers/ItemCategory.php | 25 ++---- .../Transformers/ItemPartialTransfer.php | 35 +++----- app/Models/Transformers/ItemSubcategory.php | 25 ++---- app/Models/Transformers/ItemTransfer.php | 33 +++---- app/Models/Transformers/ItemType.php | 35 ++------ .../ItemType/AllocatedExpense.php | 71 +++++++--------- .../Transformers/ItemType/SimpleExpense.php | 65 ++++++-------- .../Transformers/ItemType/SimpleItem.php | 29 ++----- app/Models/Transformers/PermittedUser.php | 23 ++--- app/Models/Transformers/RequestErrorLog.php | 29 +++---- app/Models/Transformers/RequestLog.php | 26 ++---- app/Models/Transformers/Resource.php | 25 ++---- app/Models/Transformers/ResourceType.php | 64 +++++--------- .../ResourceTypeItemType/AllocatedExpense.php | 85 +++++++------------ .../ResourceTypeItemType/SimpleExpense.php | 79 +++++++---------- .../ResourceTypeItemType/SimpleItem.php | 43 +++------- .../Transformers/Summary/ItemCategory.php | 28 ++---- app/Models/Transformers/Summary/ItemMonth.php | 26 ++---- .../Transformers/Summary/ItemSubcategory.php | 28 ++---- app/Models/Transformers/Summary/ItemYear.php | 26 ++---- .../Summary/ResourceTypeItemCategory.php | 28 ++---- .../Summary/ResourceTypeItemMonth.php | 26 ++---- .../Summary/ResourceTypeItemResource.php | 26 ++---- .../Summary/ResourceTypeItemSubcategory.php | 28 ++---- .../Summary/ResourceTypeItemYear.php | 26 ++---- app/Models/Transformers/Transformer.php | 10 ++- 29 files changed, 327 insertions(+), 742 deletions(-) delete mode 100644 app/Models/Transformers/Item.php diff --git a/app/Http/Controllers/ResourceTypeController.php b/app/Http/Controllers/ResourceTypeController.php index 2b557a53..9e390ab2 100644 --- a/app/Http/Controllers/ResourceTypeController.php +++ b/app/Http/Controllers/ResourceTypeController.php @@ -83,7 +83,7 @@ public function index(): JsonResponse $collection = array_map( static function ($resource_type) { - return (new ResourceTypeTransformer($resource_type))->toArray(); + return (new ResourceTypeTransformer($resource_type))->asArray(); }, $resource_types ); @@ -142,7 +142,7 @@ public function show(string $resource_type_id): JsonResponse $headers->item()->addParameters(Parameter\Request::xHeader()); return response()->json( - (new ResourceTypeTransformer($resource_type, $resources))->toArray(), + (new ResourceTypeTransformer($resource_type, ['resources' => $resources]))->asArray(), 200, $headers->headers() ); @@ -279,7 +279,7 @@ public function create(): JsonResponse } return response()->json( - (new ResourceTypeTransformer((New ResourceType())->instanceToArray($resource_type)))->toArray(), + (new ResourceTypeTransformer((New ResourceType())->instanceToArray($resource_type)))->asArray(), 201 ); } diff --git a/app/Models/Transformers/Category.php b/app/Models/Transformers/Category.php index fe46c88d..606152a9 100644 --- a/app/Models/Transformers/Category.php +++ b/app/Models/Transformers/Category.php @@ -4,10 +4,7 @@ namespace App\Models\Transformers; /** - * Transform the data returns from Eloquent into the format we want for the API - * - * This is an updated version of the transformers, the other transformers need to - * be updated to operate on an array rather than collections + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -15,48 +12,30 @@ */ class Category extends Transformer { - private $data_to_transform; - - private $subcategories = []; - - /** - * ResourceType constructor. - * - * @param array $data_to_transform - * @param array $subcategories - */ - public function __construct(array $data_to_transform, array $subcategories = []) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - $this->subcategories = $subcategories; - } - - public function toArray(): array + public function format(array $to_transform): void { - $result = [ - 'id' => $this->hash->category()->encode($this->data_to_transform['category_id']), - 'name' => $this->data_to_transform['category_name'], - 'description' => $this->data_to_transform['category_description'], - 'created' => $this->data_to_transform['category_created_at'], + $this->transformed = [ + 'id' => $this->hash->category()->encode($to_transform['category_id']), + 'name' => $to_transform['category_name'], + 'description' => $to_transform['category_description'], + 'created' => $to_transform['category_created_at'], 'resource_type' => [ - 'id' => $this->hash->resourceType()->encode($this->data_to_transform['resource_type_id']) + 'id' => $this->hash->resourceType()->encode($to_transform['resource_type_id']) ] ]; - if (array_key_exists('resource_type_name', $this->data_to_transform) === true) { - $result['resource_type']['name'] = $this->data_to_transform['resource_type_name']; + if (array_key_exists('resource_type_name', $to_transform) === true) { + $this->transformed['resource_type']['name'] = $to_transform['resource_type_name']; } - if (array_key_exists('category_subcategories', $this->data_to_transform)) { - $result['subcategories']['count'] = $this->data_to_transform['category_subcategories']; + if (array_key_exists('category_subcategories', $to_transform)) { + $this->transformed['subcategories']['count'] = $to_transform['category_subcategories']; } - foreach ($this->subcategories as $subcategory) { - $result['subcategories']['collection'][] = (new Subcategory($subcategory))->toArray(); + if (array_key_exists('subcategories', $this->related) === true) { + foreach ($this->related['subcategories'] as $subcategory) { + $this->transformed['subcategories']['collection'][] = (new Subcategory($subcategory))->asArray(); + } } - - return $result; } } diff --git a/app/Models/Transformers/Item.php b/app/Models/Transformers/Item.php deleted file mode 100644 index ffcb094c..00000000 --- a/app/Models/Transformers/Item.php +++ /dev/null @@ -1,66 +0,0 @@ - - * @copyright Dean Blackborough 2018-2020 - * @license https://github.com/costs-to-expect/api/blob/master/LICENSE - */ -class Item extends Transformer -{ - protected $item; - - public function __construct(array $item) - { - parent::__construct(); - - $this->item = $item; - } - - public function toArray(): array - { - $item = [ - 'id' => $this->hash->item()->encode($this->item['item_id']), - 'name' => $this->item['item_name'], - 'description' => $this->item['item_description'], - 'total' => number_format((float) $this->item['item_total'],2, '.', ''), - 'percentage' => $this->item['item_percentage'], - 'actualised_total' => number_format((float) $this->item['item_actualised_total'], 2, '.', ''), - 'effective_date' => $this->item['item_effective_date'], - 'created' => $this->item['item_created_at'] - ]; - - if ( - array_key_exists('category_id', $this->item) === true && - array_key_exists('category_name', $this->item) === true - ) { - $item['category'] = [ - 'id' => $this->hash->category()->encode($this->item['category_id']), - 'name' => $this->item['category_name'], - 'description' => $this->item['category_description'] - ]; - - if ( - array_key_exists('subcategory_id', $this->item) === true && - array_key_exists('subcategory_name', $this->item) === true - ) { - $item['subcategory'] = [ - 'id' => $this->hash->subCategory()->encode($this->item['subcategory_id']), - 'name' => $this->item['subcategory_name'], - 'description' => $this->item['subcategory_description'] - ]; - } - } - - return $item; - } -} diff --git a/app/Models/Transformers/ItemCategory.php b/app/Models/Transformers/ItemCategory.php index 8501723c..904da481 100644 --- a/app/Models/Transformers/ItemCategory.php +++ b/app/Models/Transformers/ItemCategory.php @@ -4,7 +4,7 @@ namespace App\Models\Transformers; /** - * Transform the data returns from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -12,25 +12,16 @@ */ class ItemCategory extends Transformer { - protected $data_to_transform; - - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->hash->itemCategory()->encode($this->data_to_transform['item_category_id']), + $this->transformed = [ + 'id' => $this->hash->itemCategory()->encode($to_transform['item_category_id']), 'category' => [ - 'id' => $this->hash->category()->encode($this->data_to_transform['item_category_category_id']), - 'name' => $this->data_to_transform['item_category_category_name'], - 'description' => $this->data_to_transform['item_category_category_description'] + 'id' => $this->hash->category()->encode($to_transform['item_category_category_id']), + 'name' => $to_transform['item_category_category_name'], + 'description' => $to_transform['item_category_category_description'] ], - 'created' => $this->data_to_transform['item_category_created_at'] + 'created' => $to_transform['item_category_created_at'] ]; } } diff --git a/app/Models/Transformers/ItemPartialTransfer.php b/app/Models/Transformers/ItemPartialTransfer.php index 49227b5f..29b213f7 100644 --- a/app/Models/Transformers/ItemPartialTransfer.php +++ b/app/Models/Transformers/ItemPartialTransfer.php @@ -4,7 +4,7 @@ namespace App\Models\Transformers; /** - * Transform the data returned from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -12,36 +12,27 @@ */ class ItemPartialTransfer extends Transformer { - private $data_to_transform; - - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->hash->itemPartialTransfer()->encode($this->data_to_transform['id']), + $this->transformed = [ + 'id' => $this->hash->itemPartialTransfer()->encode($to_transform['id']), 'from' => [ - 'id' => $this->hash->resource()->encode($this->data_to_transform['from_resource_id']), - 'name' => $this->data_to_transform['from_resource_name'], + 'id' => $this->hash->resource()->encode($to_transform['from_resource_id']), + 'name' => $to_transform['from_resource_name'], ], 'to' => [ - 'id' => $this->hash->resource()->encode($this->data_to_transform['to_resource_id']), - 'name' => $this->data_to_transform['to_resource_name'], + 'id' => $this->hash->resource()->encode($to_transform['to_resource_id']), + 'name' => $to_transform['to_resource_name'], ], 'item' => [ - 'id' => $this->hash->item()->encode($this->data_to_transform['item_id']) + 'id' => $this->hash->item()->encode($to_transform['item_id']) ], - 'percentage' => intval($this->data_to_transform['percentage']), + 'percentage' => (int) ($to_transform['percentage']), 'transferred' => [ - 'at' => $this->data_to_transform['created_at'], + 'at' => $to_transform['created_at'], 'user' => [ - 'id' => $this->hash->user()->encode($this->data_to_transform['user_id']), - 'name' => $this->data_to_transform['user_name'] + 'id' => $this->hash->user()->encode($to_transform['user_id']), + 'name' => $to_transform['user_name'] ] ] ]; diff --git a/app/Models/Transformers/ItemSubcategory.php b/app/Models/Transformers/ItemSubcategory.php index 01a947a1..8981d70a 100644 --- a/app/Models/Transformers/ItemSubcategory.php +++ b/app/Models/Transformers/ItemSubcategory.php @@ -4,7 +4,7 @@ namespace App\Models\Transformers; /** - * Transform the data returns from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -12,25 +12,16 @@ */ class ItemSubcategory extends Transformer { - protected $data_to_transform; - - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->hash->itemSubCategory()->encode($this->data_to_transform['item_sub_category_id']), + $this->transformed = [ + 'id' => $this->hash->itemSubCategory()->encode($to_transform['item_sub_category_id']), 'subcategory' => [ - 'id' => $this->hash->subcategory()->encode($this->data_to_transform['item_sub_category_sub_category_id']), - 'name' => $this->data_to_transform['item_sub_category_sub_category_name'], - 'description' => $this->data_to_transform['item_sub_category_sub_category_description'] + 'id' => $this->hash->subcategory()->encode($to_transform['item_sub_category_sub_category_id']), + 'name' => $to_transform['item_sub_category_sub_category_name'], + 'description' => $to_transform['item_sub_category_sub_category_description'] ], - 'created' => $this->data_to_transform['item_sub_category_created_at'] + 'created' => $to_transform['item_sub_category_created_at'] ]; } } diff --git a/app/Models/Transformers/ItemTransfer.php b/app/Models/Transformers/ItemTransfer.php index 30217cec..a5173077 100644 --- a/app/Models/Transformers/ItemTransfer.php +++ b/app/Models/Transformers/ItemTransfer.php @@ -4,7 +4,7 @@ namespace App\Models\Transformers; /** - * Transform the data returned from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -12,35 +12,26 @@ */ class ItemTransfer extends Transformer { - private $data_to_transform; - - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->hash->itemTransfer()->encode($this->data_to_transform['id']), + $this->transformed = [ + 'id' => $this->hash->itemTransfer()->encode($to_transform['id']), 'from' => [ - 'id' => $this->hash->resource()->encode($this->data_to_transform['from_resource_id']), - 'name' => $this->data_to_transform['from_resource_name'], + 'id' => $this->hash->resource()->encode($to_transform['from_resource_id']), + 'name' => $to_transform['from_resource_name'], ], 'to' => [ - 'id' => $this->hash->resource()->encode($this->data_to_transform['to_resource_id']), - 'name' => $this->data_to_transform['to_resource_name'], + 'id' => $this->hash->resource()->encode($to_transform['to_resource_id']), + 'name' => $to_transform['to_resource_name'], ], 'item' => [ - 'id' => $this->hash->item()->encode($this->data_to_transform['item_id']) + 'id' => $this->hash->item()->encode($to_transform['item_id']) ], 'transferred' => [ - 'at' => $this->data_to_transform['created_at'], + 'at' => $to_transform['created_at'], 'user' => [ - 'id' => $this->hash->user()->encode($this->data_to_transform['user_id']), - 'name' => $this->data_to_transform['user_name'] + 'id' => $this->hash->user()->encode($to_transform['user_id']), + 'name' => $to_transform['user_name'] ] ] ]; diff --git a/app/Models/Transformers/ItemType.php b/app/Models/Transformers/ItemType.php index 3186b2fc..7900150c 100644 --- a/app/Models/Transformers/ItemType.php +++ b/app/Models/Transformers/ItemType.php @@ -4,7 +4,7 @@ namespace App\Models\Transformers; /** - * Transform the data returned from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -12,32 +12,15 @@ */ class ItemType extends Transformer { - private $data_to_transform; - - /** - * @param array $data_to_transform - */ - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - /** - * Format the data - * - * @return array - */ - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->hash->itemType()->encode($this->data_to_transform['item_type_id']), - 'name' => $this->data_to_transform['item_type_name'], - 'friendly_name' => $this->data_to_transform['item_type_friendly_name'], - 'description' => $this->data_to_transform['item_type_description'], - 'example' => $this->data_to_transform['item_type_example'], - 'created' => $this->data_to_transform['item_type_created_at'] + $this->transformed = [ + 'id' => $this->hash->itemType()->encode($to_transform['item_type_id']), + 'name' => $to_transform['item_type_name'], + 'friendly_name' => $to_transform['item_type_friendly_name'], + 'description' => $to_transform['item_type_description'], + 'example' => $to_transform['item_type_example'], + 'created' => $to_transform['item_type_created_at'] ]; } } diff --git a/app/Models/Transformers/ItemType/AllocatedExpense.php b/app/Models/Transformers/ItemType/AllocatedExpense.php index c0d87de6..ad8ad9e3 100644 --- a/app/Models/Transformers/ItemType/AllocatedExpense.php +++ b/app/Models/Transformers/ItemType/AllocatedExpense.php @@ -6,7 +6,7 @@ use App\Models\Transformers\Transformer; /** - * Transform the data returns from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -14,61 +14,50 @@ */ class AllocatedExpense extends Transformer { - protected $item; - - public function __construct(array $item) - { - parent::__construct(); - - $this->item = $item; - } - - public function toArray(): array + public function format(array $to_transform): void { - $item = [ - 'id' => $this->hash->item()->encode($this->item['item_id']), - 'name' => $this->item['item_name'], - 'description' => $this->item['item_description'], - 'total' => number_format((float) $this->item['item_total'],2, '.', ''), - 'percentage' => $this->item['item_percentage'], - 'actualised_total' => number_format((float) $this->item['item_actualised_total'], 2, '.', ''), - 'effective_date' => $this->item['item_effective_date'], - 'created' => $this->item['item_created_at'], - 'updated' => $this->item['item_updated_at'] + $this->transformed = [ + 'id' => $this->hash->item()->encode($to_transform['item_id']), + 'name' => $to_transform['item_name'], + 'description' => $to_transform['item_description'], + 'total' => number_format((float) $to_transform['item_total'],2, '.', ''), + 'percentage' => $to_transform['item_percentage'], + 'actualised_total' => number_format((float) $to_transform['item_actualised_total'], 2, '.', ''), + 'effective_date' => $to_transform['item_effective_date'], + 'created' => $to_transform['item_created_at'], + 'updated' => $to_transform['item_updated_at'] ]; if ( - array_key_exists('category_id', $this->item) === true && - array_key_exists('category_name', $this->item) === true + array_key_exists('category_id', $to_transform) === true && + array_key_exists('category_name', $to_transform) === true ) { - if ($this->item['category_id'] !== null) { - $item['category'] = [ - 'id' => $this->hash->itemCategory()->encode($this->item['item_category_id']), - 'category_id' => $this->hash->category()->encode($this->item['category_id']), - 'name' => $this->item['category_name'], - 'description' => $this->item['category_description'] + if ($to_transform['category_id'] !== null) { + $this->transformed['category'] = [ + 'id' => $this->hash->itemCategory()->encode($to_transform['item_category_id']), + 'category_id' => $this->hash->category()->encode($to_transform['category_id']), + 'name' => $to_transform['category_name'], + 'description' => $to_transform['category_description'] ]; } else { - $item['category'] = null; + $this->transformed['category'] = null; } if ( - array_key_exists('subcategory_id', $this->item) === true && - array_key_exists('subcategory_name', $this->item) === true + array_key_exists('subcategory_id', $to_transform) === true && + array_key_exists('subcategory_name', $to_transform) === true ) { - if ($this->item['subcategory_id'] !== null) { - $item['subcategory'] = [ - 'id' => $this->hash->itemSubCategory()->encode($this->item['item_subcategory_id']), - 'subcategory_id' => $this->hash->subCategory()->encode($this->item['subcategory_id']), - 'name' => $this->item['subcategory_name'], - 'description' => $this->item['subcategory_description'] + if ($to_transform['subcategory_id'] !== null) { + $this->transformed['subcategory'] = [ + 'id' => $this->hash->itemSubCategory()->encode($to_transform['item_subcategory_id']), + 'subcategory_id' => $this->hash->subCategory()->encode($to_transform['subcategory_id']), + 'name' => $to_transform['subcategory_name'], + 'description' => $to_transform['subcategory_description'] ]; } else { - $item['subcategory'] = null; + $this->transformed['subcategory'] = null; } } } - - return $item; } } diff --git a/app/Models/Transformers/ItemType/SimpleExpense.php b/app/Models/Transformers/ItemType/SimpleExpense.php index 41c3773d..0d78c841 100644 --- a/app/Models/Transformers/ItemType/SimpleExpense.php +++ b/app/Models/Transformers/ItemType/SimpleExpense.php @@ -6,7 +6,7 @@ use App\Models\Transformers\Transformer; /** - * Transform the data returns from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -14,58 +14,47 @@ */ class SimpleExpense extends Transformer { - protected $item; - - public function __construct(array $item) - { - parent::__construct(); - - $this->item = $item; - } - - public function toArray(): array + public function format(array $to_transform): void { - $item = [ - 'id' => $this->hash->item()->encode($this->item['item_id']), - 'name' => $this->item['item_name'], - 'description' => $this->item['item_description'], - 'total' => number_format((float) $this->item['item_total'],2, '.', ''), - 'created' => $this->item['item_created_at'], - 'updated' => $this->item['item_updated_at'] + $this->transformed = [ + 'id' => $this->hash->item()->encode($to_transform['item_id']), + 'name' => $to_transform['item_name'], + 'description' => $to_transform['item_description'], + 'total' => number_format((float) $to_transform['item_total'],2, '.', ''), + 'created' => $to_transform['item_created_at'], + 'updated' => $to_transform['item_updated_at'] ]; if ( - array_key_exists('category_id', $this->item) === true && - array_key_exists('category_name', $this->item) === true + array_key_exists('category_id', $to_transform) === true && + array_key_exists('category_name', $to_transform) === true ) { - if ($this->item['category_id'] !== null) { - $item['category'] = [ - 'id' => $this->hash->itemCategory()->encode($this->item['item_category_id']), - 'category_id' => $this->hash->category()->encode($this->item['category_id']), - 'name' => $this->item['category_name'], - 'description' => $this->item['category_description'] + if ($to_transform['category_id'] !== null) { + $this->transformed['category'] = [ + 'id' => $this->hash->itemCategory()->encode($to_transform['item_category_id']), + 'category_id' => $this->hash->category()->encode($to_transform['category_id']), + 'name' => $to_transform['category_name'], + 'description' => $to_transform['category_description'] ]; } else { - $item['category'] = null; + $this->transformed['category'] = null; } if ( - array_key_exists('subcategory_id', $this->item) === true && - array_key_exists('subcategory_name', $this->item) === true + array_key_exists('subcategory_id', $to_transform) === true && + array_key_exists('subcategory_name', $to_transform) === true ) { - if ($this->item['subcategory_id'] !== null) { - $item['subcategory'] = [ - 'id' => $this->hash->itemSubCategory()->encode($this->item['item_subcategory_id']), - 'subcategory_id' => $this->hash->subCategory()->encode($this->item['subcategory_id']), - 'name' => $this->item['subcategory_name'], - 'description' => $this->item['subcategory_description'] + if ($to_transform['subcategory_id'] !== null) { + $this->transformed['subcategory'] = [ + 'id' => $this->hash->itemSubCategory()->encode($to_transform['item_subcategory_id']), + 'subcategory_id' => $this->hash->subCategory()->encode($to_transform['subcategory_id']), + 'name' => $to_transform['subcategory_name'], + 'description' => $to_transform['subcategory_description'] ]; } else { - $item['subcategory'] = null; + $this->transformed['subcategory'] = null; } } } - - return $item; } } diff --git a/app/Models/Transformers/ItemType/SimpleItem.php b/app/Models/Transformers/ItemType/SimpleItem.php index 5a77a0ef..07ca576c 100644 --- a/app/Models/Transformers/ItemType/SimpleItem.php +++ b/app/Models/Transformers/ItemType/SimpleItem.php @@ -6,7 +6,7 @@ use App\Models\Transformers\Transformer; /** - * Transform the data returns from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -14,26 +14,15 @@ */ class SimpleItem extends Transformer { - protected $item; - - public function __construct(array $item) - { - parent::__construct(); - - $this->item = $item; - } - - public function toArray(): array + public function format(array $to_transform): void { - $item = [ - 'id' => $this->hash->item()->encode($this->item['item_id']), - 'name' => $this->item['item_name'], - 'description' => $this->item['item_description'], - 'quantity' => (int) $this->item['item_quantity'], - 'created' => $this->item['item_created_at'], - 'updated' => $this->item['item_updated_at'] + $this->transformed = [ + 'id' => $this->hash->item()->encode($to_transform['item_id']), + 'name' => $to_transform['item_name'], + 'description' => $to_transform['item_description'], + 'quantity' => (int) $to_transform['item_quantity'], + 'created' => $to_transform['item_created_at'], + 'updated' => $to_transform['item_updated_at'] ]; - - return $item; } } diff --git a/app/Models/Transformers/PermittedUser.php b/app/Models/Transformers/PermittedUser.php index a331ab58..7bd358ee 100644 --- a/app/Models/Transformers/PermittedUser.php +++ b/app/Models/Transformers/PermittedUser.php @@ -4,7 +4,7 @@ namespace App\Models\Transformers; /** - * Transform the data returned from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -12,22 +12,13 @@ */ class PermittedUser extends Transformer { - private $data_to_transform; - - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->hash->permittedUser()->encode($this->data_to_transform['permitted_user_id']), - 'name' => $this->data_to_transform['permitted_user_name'], - 'email' => $this->data_to_transform['permitted_user_email'], - 'created' => $this->data_to_transform['permitted_user_created_at'] + $this->transformed = [ + 'id' => $this->hash->permittedUser()->encode($to_transform['permitted_user_id']), + 'name' => $to_transform['permitted_user_name'], + 'email' => $to_transform['permitted_user_email'], + 'created' => $to_transform['permitted_user_created_at'] ]; } } diff --git a/app/Models/Transformers/RequestErrorLog.php b/app/Models/Transformers/RequestErrorLog.php index 7a7953e3..203e0eb0 100644 --- a/app/Models/Transformers/RequestErrorLog.php +++ b/app/Models/Transformers/RequestErrorLog.php @@ -4,7 +4,7 @@ namespace App\Models\Transformers; /** - * Transform the data returns from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -12,25 +12,16 @@ */ class RequestErrorLog extends Transformer { - protected $data_to_transform; - - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'method' => $this->data_to_transform['request_error_log_method'], - 'expected_status_code' => $this->data_to_transform['request_error_log_expected_status_code'], - 'returned_status_code' => $this->data_to_transform['request_error_log_returned_status_code'], - 'request_uri' => $this->data_to_transform['request_error_log_request_uri'], - 'source' => $this->data_to_transform['request_error_log_source'], - 'created' => $this->data_to_transform['request_error_log_created_at'], - 'debug' => $this->data_to_transform['request_error_log_debug'] + $this->transformed = [ + 'method' => $to_transform['request_error_log_method'], + 'expected_status_code' => $to_transform['request_error_log_expected_status_code'], + 'returned_status_code' => $to_transform['request_error_log_returned_status_code'], + 'request_uri' => $to_transform['request_error_log_request_uri'], + 'source' => $to_transform['request_error_log_source'], + 'created' => $to_transform['request_error_log_created_at'], + 'debug' => $to_transform['request_error_log_debug'] ]; } } diff --git a/app/Models/Transformers/RequestLog.php b/app/Models/Transformers/RequestLog.php index e956a951..302b871f 100644 --- a/app/Models/Transformers/RequestLog.php +++ b/app/Models/Transformers/RequestLog.php @@ -4,10 +4,7 @@ namespace App\Models\Transformers; /** - * Transform the data returns from Eloquent into the format we want for the API - * - * This is an updated version of the transformers, the other transformers need to - * be updated to operate on an array rather than collections + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -15,22 +12,13 @@ */ class RequestLog extends Transformer { - protected $data_to_transform; - - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'method' => $this->data_to_transform['method'], - 'source' => $this->data_to_transform['source'], - 'request_uri' => $this->data_to_transform['request'], - 'created' => $this->data_to_transform['created_at'] + $this->transformed = [ + 'method' => $to_transform['method'], + 'source' => $to_transform['source'], + 'request_uri' => $to_transform['request'], + 'created' => $to_transform['created_at'] ]; } } diff --git a/app/Models/Transformers/Resource.php b/app/Models/Transformers/Resource.php index 7640869f..0535406f 100644 --- a/app/Models/Transformers/Resource.php +++ b/app/Models/Transformers/Resource.php @@ -4,7 +4,7 @@ namespace App\Models\Transformers; /** - * Transform the data returns from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -12,23 +12,14 @@ */ class Resource extends Transformer { - private $data_to_transform; - - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->hash->resource()->encode($this->data_to_transform['resource_id']), - 'name' => $this->data_to_transform['resource_name'], - 'description' => $this->data_to_transform['resource_description'], - 'effective_date' => $this->data_to_transform['resource_effective_date'], - 'created' => $this->data_to_transform['resource_created_at'] + $this->transformed = [ + 'id' => $this->hash->resource()->encode($to_transform['resource_id']), + 'name' => $to_transform['resource_name'], + 'description' => $to_transform['resource_description'], + 'effective_date' => $to_transform['resource_effective_date'], + 'created' => $to_transform['resource_created_at'] ]; } } diff --git a/app/Models/Transformers/ResourceType.php b/app/Models/Transformers/ResourceType.php index 6a116615..c9184384 100644 --- a/app/Models/Transformers/ResourceType.php +++ b/app/Models/Transformers/ResourceType.php @@ -14,60 +14,36 @@ */ class ResourceType extends Transformer { - private $data_to_transform; - - private $resources = []; - - /** - * ResourceType constructor. - * - * @param array $data_to_transform - * @param array $resources - */ - public function __construct(array $data_to_transform, array $resources = []) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - $this->resources = $resources; - } - - /** - * Format the data - * - * @return array - */ - public function toArray(): array + public function format(array $to_transform): void { - $result = [ - 'id' => $this->hash->resourceType()->encode($this->data_to_transform['resource_type_id']), - 'name' => $this->data_to_transform['resource_type_name'], - 'description' => $this->data_to_transform['resource_type_description'], - 'created' => $this->data_to_transform['resource_type_created_at'], - 'public' => boolval($this->data_to_transform['resource_type_public']), + $this->transformed = [ + 'id' => $this->hash->resourceType()->encode($to_transform['resource_type_id']), + 'name' => $to_transform['resource_type_name'], + 'description' => $to_transform['resource_type_description'], + 'created' => $to_transform['resource_type_created_at'], + 'public' => (bool) $to_transform['resource_type_public'], ]; if ( - array_key_exists('resource_type_item_type_id', $this->data_to_transform) === true && - array_key_exists('resource_type_item_type_name', $this->data_to_transform) === true && - array_key_exists('resource_type_item_type_description', $this->data_to_transform) === true + array_key_exists('resource_type_item_type_id', $to_transform) === true && + array_key_exists('resource_type_item_type_name', $to_transform) === true && + array_key_exists('resource_type_item_type_description', $to_transform) === true ) { - $result['item_type'] = [ - 'id' => $this->hash->itemType()->encode($this->data_to_transform['resource_type_item_type_id']), - 'name' => $this->data_to_transform['resource_type_item_type_name'], - 'description' => $this->data_to_transform['resource_type_item_type_description'] + $this->transformed['item_type'] = [ + 'id' => $this->hash->itemType()->encode($to_transform['resource_type_item_type_id']), + 'name' => $to_transform['resource_type_item_type_name'], + 'description' => $to_transform['resource_type_item_type_description'] ]; } - if (array_key_exists('resource_type_resources', $this->data_to_transform)) { - $result['resources']['count'] = $this->data_to_transform['resource_type_resources']; + if (array_key_exists('resource_type_resources', $to_transform)) { + $this->transformed['resources']['count'] = $to_transform['resource_type_resources']; } - foreach ($this->resources as $resource) { - $result['resources']['collection'][] = (new ResourceTransformer($resource))->toArray(); + if (array_key_exists('resources', $this->related) === true) { + foreach ($this->related['resources'] as $resource) { + $this->transformed['resources']['collection'][] = (new ResourceTransformer($resource))->asArray(); + } } - - - return $result; } } diff --git a/app/Models/Transformers/ResourceTypeItemType/AllocatedExpense.php b/app/Models/Transformers/ResourceTypeItemType/AllocatedExpense.php index 2f59737a..0fcdc32b 100644 --- a/app/Models/Transformers/ResourceTypeItemType/AllocatedExpense.php +++ b/app/Models/Transformers/ResourceTypeItemType/AllocatedExpense.php @@ -6,7 +6,7 @@ use App\Models\Transformers\Transformer; /** - * Transform the data array into the format we require for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -14,74 +14,55 @@ */ class AllocatedExpense extends Transformer { - protected $item; - - /** - * @param array $item - */ - public function __construct(array $item) - { - parent::__construct(); - - $this->item = $item; - } - - /** - * Return the formatted array - * - * @return array - */ - public function toArray(): array + public function format(array $to_transform): void { - $item = [ - 'id' => $this->hash->item()->encode($this->item['item_id']), - 'name' => $this->item['item_name'], - 'description' => $this->item['item_description'], - 'total' => number_format((float) $this->item['item_total'], 2, '.', ''), - 'percentage' => (int) $this->item['item_percentage'], - 'actualised_total' => number_format((float) $this->item['item_actualised_total'], 2, '.', ''), - 'effective_date' => $this->item['item_effective_date'], - 'created' => $this->item['item_created_at'], - 'updated' => $this->item['item_updated_at'], + $this->transformed = [ + 'id' => $this->hash->item()->encode($to_transform['item_id']), + 'name' => $to_transform['item_name'], + 'description' => $to_transform['item_description'], + 'total' => number_format((float) $to_transform['item_total'], 2, '.', ''), + 'percentage' => (int) $to_transform['item_percentage'], + 'actualised_total' => number_format((float) $to_transform['item_actualised_total'], 2, '.', ''), + 'effective_date' => $to_transform['item_effective_date'], + 'created' => $to_transform['item_created_at'], + 'updated' => $to_transform['item_updated_at'], 'resource' => [ - 'id' => $this->hash->resource()->encode($this->item['resource_id']), - 'name' => $this->item['resource_name'], - 'description' => $this->item['resource_description'] + 'id' => $this->hash->resource()->encode($to_transform['resource_id']), + 'name' => $to_transform['resource_name'], + 'description' => $to_transform['resource_description'] ] ]; if ( - array_key_exists('category_id', $this->item) === true && - array_key_exists('category_name', $this->item) === true + array_key_exists('category_id', $to_transform) === true && + array_key_exists('category_name', $to_transform) === true ) { - if ($this->item['category_id'] !== null) { - $item['category'] = [ - 'id' => $this->hash->itemCategory()->encode($this->item['item_category_id']), - 'category_id' => $this->hash->category()->encode($this->item['category_id']), - 'name' => $this->item['category_name'], - 'description' => $this->item['category_description'] + if ($to_transform['category_id'] !== null) { + $this->transformed['category'] = [ + 'id' => $this->hash->itemCategory()->encode($to_transform['item_category_id']), + 'category_id' => $this->hash->category()->encode($to_transform['category_id']), + 'name' => $to_transform['category_name'], + 'description' => $to_transform['category_description'] ]; } else { - $item['category'] = null; + $this->transformed['category'] = null; } if ( - array_key_exists('subcategory_id', $this->item) === true && - array_key_exists('subcategory_name', $this->item) === true + array_key_exists('subcategory_id', $to_transform) === true && + array_key_exists('subcategory_name', $to_transform) === true ) { - if ($this->item['subcategory_id'] !== null) { - $item['subcategory'] = [ - 'id' => $this->hash->itemSubCategory()->encode($this->item['item_subcategory_id']), - 'subcategory_id' => $this->hash->subCategory()->encode($this->item['subcategory_id']), - 'name' => $this->item['subcategory_name'], - 'description' => $this->item['subcategory_description'] + if ($to_transform['subcategory_id'] !== null) { + $this->transformed['subcategory'] = [ + 'id' => $this->hash->itemSubCategory()->encode($to_transform['item_subcategory_id']), + 'subcategory_id' => $this->hash->subCategory()->encode($to_transform['subcategory_id']), + 'name' => $to_transform['subcategory_name'], + 'description' => $to_transform['subcategory_description'] ]; } else { - $item['subcategory'] = null; + $this->transformed['subcategory'] = null; } } } - - return $item; } } diff --git a/app/Models/Transformers/ResourceTypeItemType/SimpleExpense.php b/app/Models/Transformers/ResourceTypeItemType/SimpleExpense.php index 7f3e342d..74ff6747 100644 --- a/app/Models/Transformers/ResourceTypeItemType/SimpleExpense.php +++ b/app/Models/Transformers/ResourceTypeItemType/SimpleExpense.php @@ -6,7 +6,7 @@ use App\Models\Transformers\Transformer; /** - * Transform the data array into the format we require for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -14,71 +14,52 @@ */ class SimpleExpense extends Transformer { - protected $item; - - /** - * @param array $item - */ - public function __construct(array $item) - { - parent::__construct(); - - $this->item = $item; - } - - /** - * Return the formatted array - * - * @return array - */ - public function toArray(): array + public function format(array $to_transform): void { - $item = [ - 'id' => $this->hash->item()->encode($this->item['item_id']), - 'name' => $this->item['item_name'], - 'description' => $this->item['item_description'], - 'total' => number_format((float) $this->item['item_total'], 2, '.', ''), - 'created' => $this->item['item_created_at'], - 'updated' => $this->item['item_updated_at'], + $this->transformed = [ + 'id' => $this->hash->item()->encode($to_transform['item_id']), + 'name' => $to_transform['item_name'], + 'description' => $to_transform['item_description'], + 'total' => number_format((float) $to_transform['item_total'], 2, '.', ''), + 'created' => $to_transform['item_created_at'], + 'updated' => $to_transform['item_updated_at'], 'resource' => [ - 'id' => $this->hash->resource()->encode($this->item['resource_id']), - 'name' => $this->item['resource_name'], - 'description' => $this->item['resource_description'] + 'id' => $this->hash->resource()->encode($to_transform['resource_id']), + 'name' => $to_transform['resource_name'], + 'description' => $to_transform['resource_description'] ] ]; if ( - array_key_exists('category_id', $this->item) === true && - array_key_exists('category_name', $this->item) === true + array_key_exists('category_id', $to_transform) === true && + array_key_exists('category_name', $to_transform) === true ) { - if ($this->item['category_id'] !== null) { - $item['category'] = [ - 'id' => $this->hash->itemCategory()->encode($this->item['item_category_id']), - 'subcategory_id' => $this->hash->category()->encode($this->item['category_id']), - 'name' => $this->item['category_name'], - 'description' => $this->item['category_description'] + if ($to_transform['category_id'] !== null) { + $this->transformed['category'] = [ + 'id' => $this->hash->itemCategory()->encode($to_transform['item_category_id']), + 'subcategory_id' => $this->hash->category()->encode($to_transform['category_id']), + 'name' => $to_transform['category_name'], + 'description' => $to_transform['category_description'] ]; } else { - $item['category'] = null; + $this->transformed['category'] = null; } if ( - array_key_exists('subcategory_id', $this->item) === true && - array_key_exists('subcategory_name', $this->item) === true + array_key_exists('subcategory_id', $to_transform) === true && + array_key_exists('subcategory_name', $to_transform) === true ) { - if ($this->item['subcategory_id'] !== null) { - $item['subcategory'] = [ - 'item_subcategory_id' => $this->hash->itemSubCategory()->encode($this->item['item_subcategory_id']), - 'id' => $this->hash->subCategory()->encode($this->item['subcategory_id']), - 'name' => $this->item['subcategory_name'], - 'description' => $this->item['subcategory_description'] + if ($to_transform['subcategory_id'] !== null) { + $this->transformed['subcategory'] = [ + 'item_subcategory_id' => $this->hash->itemSubCategory()->encode($to_transform['item_subcategory_id']), + 'id' => $this->hash->subCategory()->encode($to_transform['subcategory_id']), + 'name' => $to_transform['subcategory_name'], + 'description' => $to_transform['subcategory_description'] ]; } else { - $item['subcategory'] = null; + $this->transformed['subcategory'] = null; } } } - - return $item; } } diff --git a/app/Models/Transformers/ResourceTypeItemType/SimpleItem.php b/app/Models/Transformers/ResourceTypeItemType/SimpleItem.php index 776de0fd..42aecfb8 100644 --- a/app/Models/Transformers/ResourceTypeItemType/SimpleItem.php +++ b/app/Models/Transformers/ResourceTypeItemType/SimpleItem.php @@ -6,7 +6,7 @@ use App\Models\Transformers\Transformer; /** - * Transform the data array into the format we require for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -14,39 +14,20 @@ */ class SimpleItem extends Transformer { - protected $item; - - /** - * @param array $item - */ - public function __construct(array $item) - { - parent::__construct(); - - $this->item = $item; - } - - /** - * Return the formatted array - * - * @return array - */ - public function toArray(): array + public function format(array $to_transform): void { - $item = [ - 'id' => $this->hash->item()->encode($this->item['item_id']), - 'name' => $this->item['item_name'], - 'description' => $this->item['item_description'], - 'quantity' => (int) $this->item['item_quantity'], - 'created' => $this->item['item_created_at'], - 'updated' => $this->item['item_updated_at'], + $this->transformed = [ + 'id' => $this->hash->item()->encode($to_transform['item_id']), + 'name' => $to_transform['item_name'], + 'description' => $to_transform['item_description'], + 'quantity' => (int) $to_transform['item_quantity'], + 'created' => $to_transform['item_created_at'], + 'updated' => $to_transform['item_updated_at'], 'resource' => [ - 'id' => $this->hash->resource()->encode($this->item['resource_id']), - 'name' => $this->item['resource_name'], - 'description' => $this->item['resource_description'] + 'id' => $this->hash->resource()->encode($to_transform['resource_id']), + 'name' => $to_transform['resource_name'], + 'description' => $to_transform['resource_description'] ] ]; - - return $item; } } diff --git a/app/Models/Transformers/Summary/ItemCategory.php b/app/Models/Transformers/Summary/ItemCategory.php index dda0bc03..47af3280 100644 --- a/app/Models/Transformers/Summary/ItemCategory.php +++ b/app/Models/Transformers/Summary/ItemCategory.php @@ -6,7 +6,7 @@ use App\Models\Transformers\Transformer; /** - * Transform the data returns from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -14,27 +14,13 @@ */ class ItemCategory extends Transformer { - private $data_to_transform; - - /** - * ResourceType constructor. - * - * @param array $data_to_transform - */ - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->hash->category()->encode($this->data_to_transform['id']), - 'name' => $this->data_to_transform['name'], - 'description' => $this->data_to_transform['description'], - 'total' => number_format((float) $this->data_to_transform['total'], 2, '.', '') + $this->transformed = [ + 'id' => $this->hash->category()->encode($to_transform['id']), + 'name' => $to_transform['name'], + 'description' => $to_transform['description'], + 'total' => number_format((float) $to_transform['total'], 2, '.', '') ]; } } diff --git a/app/Models/Transformers/Summary/ItemMonth.php b/app/Models/Transformers/Summary/ItemMonth.php index 33ba1125..c667d402 100644 --- a/app/Models/Transformers/Summary/ItemMonth.php +++ b/app/Models/Transformers/Summary/ItemMonth.php @@ -6,7 +6,7 @@ use App\Models\Transformers\Transformer; /** - * Transform the data returns from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -14,26 +14,12 @@ */ class ItemMonth extends Transformer { - private $data_to_transform; - - /** - * ResourceType constructor. - * - * @param array $data_to_transform - */ - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->data_to_transform['month'], - 'month' => date("F", mktime(0, 0, 0, $this->data_to_transform['month'], 1)), - 'total' => number_format((float) $this->data_to_transform['total'], 2, '.', '') + $this->transformed = [ + 'id' => $to_transform['month'], + 'month' => date("F", mktime(0, 0, 0, $to_transform['month'], 1)), + 'total' => number_format((float) $to_transform['total'], 2, '.', '') ]; } } diff --git a/app/Models/Transformers/Summary/ItemSubcategory.php b/app/Models/Transformers/Summary/ItemSubcategory.php index ef18f89d..c898511d 100644 --- a/app/Models/Transformers/Summary/ItemSubcategory.php +++ b/app/Models/Transformers/Summary/ItemSubcategory.php @@ -6,7 +6,7 @@ use App\Models\Transformers\Transformer; /** - * Transform the data returns from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -14,27 +14,13 @@ */ class ItemSubcategory extends Transformer { - private $data_to_transform; - - /** - * ResourceType constructor. - * - * @param array $data_to_transform - */ - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->hash->subCategory()->encode($this->data_to_transform['id']), - 'name' => $this->data_to_transform['name'], - 'description' => $this->data_to_transform['description'], - 'total' => number_format((float) $this->data_to_transform['total'],2, '.', '') + $this->transformed = [ + 'id' => $this->hash->subCategory()->encode($to_transform['id']), + 'name' => $to_transform['name'], + 'description' => $to_transform['description'], + 'total' => number_format((float) $to_transform['total'],2, '.', '') ]; } } diff --git a/app/Models/Transformers/Summary/ItemYear.php b/app/Models/Transformers/Summary/ItemYear.php index e8edbde5..d98f8267 100644 --- a/app/Models/Transformers/Summary/ItemYear.php +++ b/app/Models/Transformers/Summary/ItemYear.php @@ -6,7 +6,7 @@ use App\Models\Transformers\Transformer; /** - * Transform the data returns from Eloquent into the format we want for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -14,26 +14,12 @@ */ class ItemYear extends Transformer { - private $data_to_transform; - - /** - * ResourceType constructor. - * - * @param array $data_to_transform - */ - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->data_to_transform['year'], - 'year' => $this->data_to_transform['year'], - 'total' => number_format((float) $this->data_to_transform['total'], 2, '.', '') + $this->transformed = [ + 'id' => $to_transform['year'], + 'year' => $to_transform['year'], + 'total' => number_format((float) $to_transform['total'], 2, '.', '') ]; } } diff --git a/app/Models/Transformers/Summary/ResourceTypeItemCategory.php b/app/Models/Transformers/Summary/ResourceTypeItemCategory.php index 26f9393d..e16e796f 100644 --- a/app/Models/Transformers/Summary/ResourceTypeItemCategory.php +++ b/app/Models/Transformers/Summary/ResourceTypeItemCategory.php @@ -6,7 +6,7 @@ use App\Models\Transformers\Transformer; /** - * Transform the data array into the format we require for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -14,27 +14,13 @@ */ class ResourceTypeItemCategory extends Transformer { - private $data_to_transform; - - /** - * ResourceType constructor. - * - * @param array $data_to_transform - */ - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->hash->category()->encode($this->data_to_transform['id']), - 'name' => $this->data_to_transform['name'], - 'description' => $this->data_to_transform['description'], - 'total' => number_format((float) $this->data_to_transform['total'], 2, '.', '') + $this->transformed = [ + 'id' => $this->hash->category()->encode($to_transform['id']), + 'name' => $to_transform['name'], + 'description' => $to_transform['description'], + 'total' => number_format((float) $to_transform['total'], 2, '.', '') ]; } } diff --git a/app/Models/Transformers/Summary/ResourceTypeItemMonth.php b/app/Models/Transformers/Summary/ResourceTypeItemMonth.php index acb7e703..558b3149 100644 --- a/app/Models/Transformers/Summary/ResourceTypeItemMonth.php +++ b/app/Models/Transformers/Summary/ResourceTypeItemMonth.php @@ -7,7 +7,7 @@ use App\Models\Transformers\Transformer; /** - * Transform the data array into the format we require for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -15,26 +15,12 @@ */ class ResourceTypeItemMonth extends Transformer { - private $data_to_transform; - - /** - * ResourceType constructor. - * - * @param array $data_to_transform - */ - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->data_to_transform['month'], - 'month' => date("F", mktime(0, 0, 0, $this->data_to_transform['month'], 1)), - 'total' => (float)$this->data_to_transform['total'] + $this->transformed = [ + 'id' => $to_transform['month'], + 'month' => date("F", mktime(0, 0, 0, $to_transform['month'], 1)), + 'total' => (float)$to_transform['total'] ]; } } diff --git a/app/Models/Transformers/Summary/ResourceTypeItemResource.php b/app/Models/Transformers/Summary/ResourceTypeItemResource.php index 99bae63f..f7350e4c 100644 --- a/app/Models/Transformers/Summary/ResourceTypeItemResource.php +++ b/app/Models/Transformers/Summary/ResourceTypeItemResource.php @@ -6,7 +6,7 @@ use App\Models\Transformers\Transformer; /** - * Transform the data array into the format we require for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -14,26 +14,12 @@ */ class ResourceTypeItemResource extends Transformer { - private $data_to_transform; - - /** - * ResourceType constructor. - * - * @param array $data_to_transform - */ - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->hash->resource()->encode($this->data_to_transform['id']), - 'name' => $this->data_to_transform['name'], - 'total' => number_format((float) $this->data_to_transform['total'], 2, '.', '') + $this->transformed = [ + 'id' => $this->hash->resource()->encode($to_transform['id']), + 'name' => $to_transform['name'], + 'total' => number_format((float) $to_transform['total'], 2, '.', '') ]; } } diff --git a/app/Models/Transformers/Summary/ResourceTypeItemSubcategory.php b/app/Models/Transformers/Summary/ResourceTypeItemSubcategory.php index 65abf9d2..4af993ef 100644 --- a/app/Models/Transformers/Summary/ResourceTypeItemSubcategory.php +++ b/app/Models/Transformers/Summary/ResourceTypeItemSubcategory.php @@ -6,7 +6,7 @@ use App\Models\Transformers\Transformer; /** - * Transform the data array into the format we require for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -14,27 +14,13 @@ */ class ResourceTypeItemSubcategory extends Transformer { - private $data_to_transform; - - /** - * ResourceType constructor. - * - * @param array $data_to_transform - */ - public function __construct(array $data_to_transform) - { - parent::__construct(); - - $this->data_to_transform = $data_to_transform; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->hash->subCategory()->encode($this->data_to_transform['id']), - 'name' => $this->data_to_transform['name'], - 'description' => $this->data_to_transform['description'], - 'total' => number_format((float) $this->data_to_transform['total'], 2, '.', '') + $this->transformed = [ + 'id' => $this->hash->subCategory()->encode($to_transform['id']), + 'name' => $to_transform['name'], + 'description' => $to_transform['description'], + 'total' => number_format((float) $to_transform['total'], 2, '.', '') ]; } } diff --git a/app/Models/Transformers/Summary/ResourceTypeItemYear.php b/app/Models/Transformers/Summary/ResourceTypeItemYear.php index 18c3177b..e45f7d3b 100644 --- a/app/Models/Transformers/Summary/ResourceTypeItemYear.php +++ b/app/Models/Transformers/Summary/ResourceTypeItemYear.php @@ -7,7 +7,7 @@ use App\Models\Transformers\Transformer; /** - * Transform the data array into the format we require for the API + * Transform the data from our queries into the format we want to display * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -15,26 +15,12 @@ */ class ResourceTypeItemYear extends Transformer { - private $year_summary; - - /** - * ResourceType constructor. - * - * @param array $year_summary - */ - public function __construct(array $year_summary) - { - parent::__construct(); - - $this->year_summary = $year_summary; - } - - public function toArray(): array + public function format(array $to_transform): void { - return [ - 'id' => $this->year_summary['year'], - 'year' => $this->year_summary['year'], - 'total' => (float)$this->year_summary['total'] + $this->transformed = [ + 'id' => $to_transform['year'], + 'year' => $to_transform['year'], + 'total' => (float) $to_transform['total'] ]; } } diff --git a/app/Models/Transformers/Transformer.php b/app/Models/Transformers/Transformer.php index 5f72e447..dee45ffa 100644 --- a/app/Models/Transformers/Transformer.php +++ b/app/Models/Transformers/Transformer.php @@ -17,17 +17,21 @@ abstract class Transformer { protected Hash $hash; + protected array $related; + protected array $transformed; /** - * Pass in the data we want to format for output - * * @param array $to_transform + * @param array $related Pass in optional related data arrays */ - public function __construct(array $to_transform) + public function __construct(array $to_transform, array $related = []) { $this->hash = new Hash(); + $this->transformed = []; + $this->related = $related; + $this->format($to_transform); } From d3a4df37908089f08fe4ce0716bbe16fad684656 Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Thu, 25 Jun 2020 01:25:19 +0100 Subject: [PATCH 04/24] Refactoring - Updated controllers to use new transformers --- app/Http/Controllers/CategoryController.php | 6 +++--- app/Http/Controllers/IndexController.php | 1 - .../Controllers/ItemCategoryController.php | 7 +++---- app/Http/Controllers/ItemController.php | 6 +++--- .../ItemPartialTransferController.php | 6 +++--- .../Controllers/ItemSubcategoryController.php | 6 +++--- .../Controllers/ItemTransferController.php | 4 ++-- app/Http/Controllers/ItemTypeController.php | 4 ++-- .../Controllers/PermittedUserController.php | 3 +-- app/Http/Controllers/RequestController.php | 4 ++-- app/Http/Controllers/ResourceController.php | 6 +++--- .../Controllers/ResourceTypeItemController.php | 2 +- .../Controllers/Summary/ItemController.php | 16 ++++++++-------- .../Summary/ResourceTypeItemController.php | 18 +++++++++--------- 14 files changed, 43 insertions(+), 46 deletions(-) diff --git a/app/Http/Controllers/CategoryController.php b/app/Http/Controllers/CategoryController.php index 847d3771..2ee1c98a 100644 --- a/app/Http/Controllers/CategoryController.php +++ b/app/Http/Controllers/CategoryController.php @@ -90,7 +90,7 @@ public function index($resource_type_id): JsonResponse $collection = array_map( static function ($category) { - return (new CategoryTransformer($category))->toArray(); + return (new CategoryTransformer($category))->asArray(); }, $categories ); @@ -158,7 +158,7 @@ public function show($resource_type_id, $category_id): JsonResponse } return response()->json( - (new CategoryTransformer($category, $subcategories))->toArray(), + (new CategoryTransformer($category, $subcategories))->asArray(), 200, $headers->headers() ); @@ -296,7 +296,7 @@ public function create($resource_type_id): JsonResponse } return response()->json( - (new CategoryTransformer((new Category)->instanceToArray($category)))->toArray(), + (new CategoryTransformer((new Category)->instanceToArray($category)))->asArray(), 201 ); } diff --git a/app/Http/Controllers/IndexController.php b/app/Http/Controllers/IndexController.php index 9bcdd365..244f8989 100644 --- a/app/Http/Controllers/IndexController.php +++ b/app/Http/Controllers/IndexController.php @@ -3,7 +3,6 @@ namespace App\Http\Controllers; use App\Response\Header\Header; -use Illuminate\Http\Request; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Route; use Illuminate\Support\Str; diff --git a/app/Http/Controllers/ItemCategoryController.php b/app/Http/Controllers/ItemCategoryController.php index 8b675fa1..19240dfb 100644 --- a/app/Http/Controllers/ItemCategoryController.php +++ b/app/Http/Controllers/ItemCategoryController.php @@ -11,7 +11,6 @@ use App\Models\Category; use App\Models\ItemCategory; use App\Models\Transformers\ItemCategory as ItemCategoryTransformer; -use App\Response\Header\Headers; use App\Request\Validate\ItemCategory as ItemCategoryValidator; use Exception; use Illuminate\Database\QueryException; @@ -62,7 +61,7 @@ public function index(string $resource_type_id, string $resource_id, string $ite if ($item_category === null || (is_array($item_category) === true && count($item_category) === 0)) { $collection = []; } else { - $collection = [(new ItemCategoryTransformer($item_category[0]))->toArray()]; + $collection = [(new ItemCategoryTransformer($item_category[0]))->asArray()]; } $headers = new Header(); @@ -120,7 +119,7 @@ public function show( $headers->item(); return response()->json( - (new ItemCategoryTransformer($item_category))->toArray(), + (new ItemCategoryTransformer($item_category))->asArray(), 200, $headers->headers() ); @@ -296,7 +295,7 @@ public function create( } return response()->json( - (new ItemCategoryTransformer((new ItemCategory())->instanceToArray($item_category)))->toArray(), + (new ItemCategoryTransformer((new ItemCategory())->instanceToArray($item_category)))->asArray(), 201 ); } diff --git a/app/Http/Controllers/ItemController.php b/app/Http/Controllers/ItemController.php index 700927be..807e913f 100644 --- a/app/Http/Controllers/ItemController.php +++ b/app/Http/Controllers/ItemController.php @@ -107,7 +107,7 @@ public function index( $collection = array_map( static function ($item) use ($item_interface) { - return $item_interface->transformer($item)->toArray(); + return $item_interface->transformer($item)->asArray(); }, $items ); @@ -175,7 +175,7 @@ public function show( $headers->item(); return response()->json( - $item_interface->transformer($item)->toArray(), + $item_interface->transformer($item)->asArray(), 200, $headers->headers() ); @@ -370,7 +370,7 @@ public function create( } return response()->json( - $item_interface->transformer($model->instanceToArray($item, $item_type))->toArray(), + $item_interface->transformer($model->instanceToArray($item, $item_type))->asArray(), 201 ); } diff --git a/app/Http/Controllers/ItemPartialTransferController.php b/app/Http/Controllers/ItemPartialTransferController.php index 71784942..1dbdf063 100644 --- a/app/Http/Controllers/ItemPartialTransferController.php +++ b/app/Http/Controllers/ItemPartialTransferController.php @@ -80,7 +80,7 @@ public function index($resource_type_id): JsonResponse $collection = array_map( static function ($transfer) { - return (new ItemPartialTransferTransformer($transfer))->toArray(); + return (new ItemPartialTransferTransformer($transfer))->asArray(); }, $transfers ); @@ -179,7 +179,7 @@ public function show( $headers->item(); return response()->json( - (new ItemPartialTransferTransformer($item_partial_transfer))->toArray(), + (new ItemPartialTransferTransformer($item_partial_transfer))->asArray(), 200, $headers->headers() ); @@ -254,7 +254,7 @@ public function transfer( } return response()->json( - (new ItemPartialTransferTransformer($item_partial_transfer))->toArray(), + (new ItemPartialTransferTransformer($item_partial_transfer))->asArray(), 201 ); } diff --git a/app/Http/Controllers/ItemSubcategoryController.php b/app/Http/Controllers/ItemSubcategoryController.php index f804df65..5c54ccf5 100644 --- a/app/Http/Controllers/ItemSubcategoryController.php +++ b/app/Http/Controllers/ItemSubcategoryController.php @@ -69,7 +69,7 @@ public function index( if ($item_sub_category === null || (is_array($item_sub_category) && count($item_sub_category) === 0)) { $collection = []; } else { - $collection = [(new ItemSubcategoryTransformer($item_sub_category[0]))->toArray()]; + $collection = [(new ItemSubcategoryTransformer($item_sub_category[0]))->asArray()]; } $headers = new Header(); @@ -130,7 +130,7 @@ public function show( $headers->item(); return response()->json( - (new ItemSubcategoryTransformer($item_sub_category))->toArray(), + (new ItemSubcategoryTransformer($item_sub_category))->asArray(), 200, $headers->headers() ); @@ -334,7 +334,7 @@ public function create( } return response()->json( - (new ItemSubcategoryTransformer((new ItemSubcategory())->instanceToArray($item_sub_category)))->toArray(), + (new ItemSubcategoryTransformer((new ItemSubcategory())->instanceToArray($item_sub_category)))->asArray(), 201 ); } diff --git a/app/Http/Controllers/ItemTransferController.php b/app/Http/Controllers/ItemTransferController.php index b2e480ec..91019fab 100644 --- a/app/Http/Controllers/ItemTransferController.php +++ b/app/Http/Controllers/ItemTransferController.php @@ -80,7 +80,7 @@ public function index($resource_type_id): JsonResponse $collection = array_map( static function ($transfer) { - return (new ItemTransferTransformer($transfer))->toArray(); + return (new ItemTransferTransformer($transfer))->asArray(); }, $transfers ); @@ -227,7 +227,7 @@ public function show( $headers->item(); return response()->json( - (new ItemTransferTransformer($item_transfer))->toArray(), + (new ItemTransferTransformer($item_transfer))->asArray(), 200, $headers->headers() ); diff --git a/app/Http/Controllers/ItemTypeController.php b/app/Http/Controllers/ItemTypeController.php index 892a760f..c946e015 100644 --- a/app/Http/Controllers/ItemTypeController.php +++ b/app/Http/Controllers/ItemTypeController.php @@ -68,7 +68,7 @@ public function index(): JsonResponse $collection = array_map( static function($item_type) { - return (new ItemTypeTransformer($item_type))->toArray(); + return (new ItemTypeTransformer($item_type))->asArray(); }, $item_types ); @@ -108,7 +108,7 @@ public function show(string $item_type_id): JsonResponse $headers->item(); return response()->json( - (new ItemTypeTransformer($item_type))->toArray(), + (new ItemTypeTransformer($item_type))->asArray(), 200, $headers->headers() ); diff --git a/app/Http/Controllers/PermittedUserController.php b/app/Http/Controllers/PermittedUserController.php index f23f54b9..1774ce6a 100644 --- a/app/Http/Controllers/PermittedUserController.php +++ b/app/Http/Controllers/PermittedUserController.php @@ -7,7 +7,6 @@ use App\Option\Get; use App\Option\Post; use App\Response\Cache; -use App\Response\Header\Header; use App\Request\Parameter; use App\Request\Route; use App\Response\Header\Headers; @@ -78,7 +77,7 @@ public function index(string $resource_type_id): JsonResponse $collection = array_map( static function ($permitted_user) { - return (new PermittedUserTransformer($permitted_user))->toArray(); + return (new PermittedUserTransformer($permitted_user))->asArray(); }, $permitted_users ); diff --git a/app/Http/Controllers/RequestController.php b/app/Http/Controllers/RequestController.php index c1329864..7118543a 100644 --- a/app/Http/Controllers/RequestController.php +++ b/app/Http/Controllers/RequestController.php @@ -57,7 +57,7 @@ public function errorLog(): JsonResponse return response()->json( array_map( function($log) { - return (new RequestErrorLogTransformer($log))->toArray(); + return (new RequestErrorLogTransformer($log))->asArray(); }, $logs ), @@ -97,7 +97,7 @@ public function accessLog(): JsonResponse $json = []; foreach ($log as $log_item) { - $json[] = (new RequestLogTransformer($log_item))->toArray(); + $json[] = (new RequestLogTransformer($log_item))->asArray(); } return response()->json($json, 200, $headers->headers()); diff --git a/app/Http/Controllers/ResourceController.php b/app/Http/Controllers/ResourceController.php index 2596a28e..27c14f75 100644 --- a/app/Http/Controllers/ResourceController.php +++ b/app/Http/Controllers/ResourceController.php @@ -89,7 +89,7 @@ public function index(string $resource_type_id): JsonResponse $collection = array_map( static function ($resource) { - return (new ResourceTransformer($resource))->toArray(); + return (new ResourceTransformer($resource))->asArray(); }, $resources ); @@ -137,7 +137,7 @@ public function show( $headers->item(); return response()->json( - (new ResourceTransformer($resource))->toArray(), + (new ResourceTransformer($resource))->asArray(), 200, $headers->headers() ); @@ -284,7 +284,7 @@ public function create(string $resource_type_id): JsonResponse } return response()->json( - (new ResourceTransformer((New Resource())->instanceToArray($resource)))->toArray(), + (new ResourceTransformer((New Resource())->instanceToArray($resource)))->asArray(), 201 ); } diff --git a/app/Http/Controllers/ResourceTypeItemController.php b/app/Http/Controllers/ResourceTypeItemController.php index 452e883d..86175af7 100644 --- a/app/Http/Controllers/ResourceTypeItemController.php +++ b/app/Http/Controllers/ResourceTypeItemController.php @@ -88,7 +88,7 @@ public function index(string $resource_type_id): JsonResponse $collection = array_map( static function ($item) use ($item_interface) { - return $item_interface->transformer($item)->toArray(); + return $item_interface->transformer($item)->asArray(); }, $items ); diff --git a/app/Http/Controllers/Summary/ItemController.php b/app/Http/Controllers/Summary/ItemController.php index d6f08094..6534e0a5 100644 --- a/app/Http/Controllers/Summary/ItemController.php +++ b/app/Http/Controllers/Summary/ItemController.php @@ -257,7 +257,7 @@ private function yearsSummary( $collection = array_map( static function ($year) { - return (new ItemYearTransformer($year))->toArray(); + return (new ItemYearTransformer($year))->asArray(); }, $summary ); @@ -334,7 +334,7 @@ private function monthsSummary( $collection = array_map( static function ($month) { - return (new ItemMonthTransformer($month))->toArray(); + return (new ItemMonthTransformer($month))->asArray(); }, $summary ); @@ -386,7 +386,7 @@ private function monthSummary( $collection = []; if (array_key_exists(0, $summary)) { - $collection = (new ItemMonthTransformer($summary[0]))->toArray(); + $collection = (new ItemMonthTransformer($summary[0]))->asArray(); } $this->assignContentToCache( @@ -433,7 +433,7 @@ private function yearSummary( $collection = []; if (array_key_exists(0, $summary)) { - $collection = (new ItemYearTransformer($summary[0]))->toArray(); + $collection = (new ItemYearTransformer($summary[0]))->asArray(); } $this->assignContentToCache( @@ -476,7 +476,7 @@ private function categoriesSummary( $collection = array_map( static function ($category) { - return (new ItemCategoryTransformer($category))->toArray(); + return (new ItemCategoryTransformer($category))->asArray(); }, $summary ); @@ -525,7 +525,7 @@ private function subcategoriesSummary( $collection = array_map( static function ($subcategory) { - return (new ItemSubcategoryTransformer($subcategory))->toArray(); + return (new ItemSubcategoryTransformer($subcategory))->asArray(); }, $summary ); @@ -577,7 +577,7 @@ private function subcategorySummary( $collection = []; if (array_key_exists(0, $summary)) { - $collection = (new ItemSubcategoryTransformer($summary[0]))->toArray(); + $collection = (new ItemSubcategoryTransformer($summary[0]))->asArray(); } $this->assignContentToCache( @@ -624,7 +624,7 @@ private function categorySummary( $collection = []; if (array_key_exists(0, $summary)) { - $collection = (new ItemCategoryTransformer($summary[0]))->toArray(); + $collection = (new ItemCategoryTransformer($summary[0]))->asArray(); } $this->assignContentToCache( diff --git a/app/Http/Controllers/Summary/ResourceTypeItemController.php b/app/Http/Controllers/Summary/ResourceTypeItemController.php index 2b3b90c9..261834ff 100644 --- a/app/Http/Controllers/Summary/ResourceTypeItemController.php +++ b/app/Http/Controllers/Summary/ResourceTypeItemController.php @@ -332,7 +332,7 @@ private function resourcesSummary( $collection = array_map( static function ($resource) { - return (new ResourceTypeItemResourceTransformer($resource))->toArray(); + return (new ResourceTypeItemResourceTransformer($resource))->asArray(); }, $summary ); @@ -377,7 +377,7 @@ private function yearsSummary( $collection = array_map( static function ($year) { - return (new ResourceTypeItemYearTransformer($year))->toArray(); + return (new ResourceTypeItemYearTransformer($year))->asArray(); }, $summary ); @@ -425,7 +425,7 @@ private function yearSummary( $collection = []; if (array_key_exists(0, $summary)) { - $collection = (new ResourceTypeItemYearTransformer($summary[0]))->toArray(); + $collection = (new ResourceTypeItemYearTransformer($summary[0]))->asArray(); } $this->assignContentToCache( @@ -471,7 +471,7 @@ private function monthsSummary( $collection = array_map( static function ($month) { - return (new ResourceTypeItemMonthTransformer($month))->toArray(); + return (new ResourceTypeItemMonthTransformer($month))->asArray(); }, $summary ); @@ -522,7 +522,7 @@ private function monthSummary( $collection = []; if (array_key_exists(0, $summary)) { - $collection = (new ResourceTypeItemMonthTransformer($summary[0]))->toArray(); + $collection = (new ResourceTypeItemMonthTransformer($summary[0]))->asArray(); } $this->assignContentToCache( @@ -565,7 +565,7 @@ private function categoriesSummary( $collection = array_map( static function ($category) { - return (new ResourceTypeItemCategoryTransformer($category))->toArray(); + return (new ResourceTypeItemCategoryTransformer($category))->asArray(); }, $summary ); @@ -613,7 +613,7 @@ private function categorySummary( $collection = []; if (array_key_exists(0, $summary)) { - $collection = (new ResourceTypeItemCategoryTransformer($summary[0]))->toArray(); + $collection = (new ResourceTypeItemCategoryTransformer($summary[0]))->asArray(); } $this->assignContentToCache( @@ -723,7 +723,7 @@ private function subcategoriesSummary( $collection = array_map( static function ($category) { - return (new ResourceTypeItemSubcategoryTransformer($category))->toArray(); + return (new ResourceTypeItemSubcategoryTransformer($category))->asArray(); }, $summary ); @@ -774,7 +774,7 @@ private function subcategorySummary( $collection = []; if (array_key_exists(0, $summary)) { - $collection = (new ResourceTypeItemSubcategoryTransformer($summary[0]))->toArray(); + $collection = (new ResourceTypeItemSubcategoryTransformer($summary[0]))->asArray(); } $this->assignContentToCache( From e2dc541a0bb0ff9ec5286c8a939b3f7813376770 Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Thu, 25 Jun 2020 13:40:35 +0100 Subject: [PATCH 05/24] Skip cache - Added support for a request header to skip response caching --- app/Response/Cache/Control.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/app/Response/Cache/Control.php b/app/Response/Cache/Control.php index b70bb471..1de0b7f8 100644 --- a/app/Response/Cache/Control.php +++ b/app/Response/Cache/Control.php @@ -59,6 +59,12 @@ public function __construct(int $prefix = null) */ public function cacheable(): bool { + $skip_cache = request()->header('x-skip-cache'); + + if ($skip_cache !== null) { + return false; + } + return $this->cacheable; } From 45c656c8ca5aa006ef785e58a5300ad425168afa Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Thu, 25 Jun 2020 14:56:05 +0100 Subject: [PATCH 06/24] Sort on public - Sort resource types by public setting --- config/api/resource-type/sortable.php | 1 + 1 file changed, 1 insertion(+) diff --git a/config/api/resource-type/sortable.php b/config/api/resource-type/sortable.php index 4202d0b2..0ac45597 100644 --- a/config/api/resource-type/sortable.php +++ b/config/api/resource-type/sortable.php @@ -5,5 +5,6 @@ return [ 'name', 'description', + 'public', 'created' ]; From 716dc03ee503ae53bed569d8232f5430a33bde4b Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Thu, 25 Jun 2020 15:02:25 +0100 Subject: [PATCH 07/24] Moved pagination class - We have moved the pagination class to a new namespace --- app/Http/Controllers/CategoryController.php | 2 +- app/Http/Controllers/ItemController.php | 2 +- app/Http/Controllers/ItemPartialTransferController.php | 2 +- app/Http/Controllers/ItemTransferController.php | 2 +- app/Http/Controllers/ItemTypeController.php | 2 +- app/Http/Controllers/PermittedUserController.php | 2 +- app/Http/Controllers/RequestController.php | 2 +- app/Http/Controllers/ResourceController.php | 2 +- app/Http/Controllers/ResourceTypeController.php | 2 +- app/Http/Controllers/ResourceTypeItemController.php | 2 +- app/Http/Controllers/SubcategoryController.php | 2 +- app/{Utilities => Response}/Pagination.php | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) rename app/{Utilities => Response}/Pagination.php (99%) diff --git a/app/Http/Controllers/CategoryController.php b/app/Http/Controllers/CategoryController.php index 2ee1c98a..3896fd57 100644 --- a/app/Http/Controllers/CategoryController.php +++ b/app/Http/Controllers/CategoryController.php @@ -12,7 +12,7 @@ use App\Request\Parameter; use App\Request\Route; use App\Response\Header\Headers; -use App\Utilities\Pagination as UtilityPagination; +use App\Response\Pagination as UtilityPagination; use App\Models\Category; use App\Models\Transformers\Category as CategoryTransformer; use App\Request\Validate\Category as CategoryValidator; diff --git a/app/Http/Controllers/ItemController.php b/app/Http/Controllers/ItemController.php index 807e913f..16297b5b 100644 --- a/app/Http/Controllers/ItemController.php +++ b/app/Http/Controllers/ItemController.php @@ -16,7 +16,7 @@ use App\Models\Item; use App\Models\Subcategory; use App\Response\Header\Headers; -use App\Utilities\Pagination as UtilityPagination; +use App\Response\Pagination as UtilityPagination; use Exception; use Illuminate\Database\QueryException; use Illuminate\Http\JsonResponse; diff --git a/app/Http/Controllers/ItemPartialTransferController.php b/app/Http/Controllers/ItemPartialTransferController.php index 1dbdf063..3848e03a 100644 --- a/app/Http/Controllers/ItemPartialTransferController.php +++ b/app/Http/Controllers/ItemPartialTransferController.php @@ -12,7 +12,7 @@ use App\Response\Header\Headers; use App\Request\Parameter; use App\Request\Route; -use App\Utilities\Pagination as UtilityPagination; +use App\Response\Pagination as UtilityPagination; use App\Request\Validate\ItemPartialTransfer as ItemPartialTransferValidator; use Exception; use Illuminate\Database\QueryException; diff --git a/app/Http/Controllers/ItemTransferController.php b/app/Http/Controllers/ItemTransferController.php index 91019fab..0bface2b 100644 --- a/app/Http/Controllers/ItemTransferController.php +++ b/app/Http/Controllers/ItemTransferController.php @@ -12,7 +12,7 @@ use App\Response\Header\Headers; use App\Request\Parameter; use App\Request\Route; -use App\Utilities\Pagination as UtilityPagination; +use App\Response\Pagination as UtilityPagination; use App\Request\Validate\ItemTransfer as ItemTransferValidator; use Exception; use Illuminate\Database\QueryException; diff --git a/app/Http/Controllers/ItemTypeController.php b/app/Http/Controllers/ItemTypeController.php index c946e015..7b2428e2 100644 --- a/app/Http/Controllers/ItemTypeController.php +++ b/app/Http/Controllers/ItemTypeController.php @@ -8,7 +8,7 @@ use App\Response\Header\Headers; use App\Request\Parameter; use App\Request\Route; -use App\Utilities\Pagination as UtilityPagination; +use App\Response\Pagination as UtilityPagination; use App\Models\Transformers\ItemType as ItemTypeTransformer; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Config; diff --git a/app/Http/Controllers/PermittedUserController.php b/app/Http/Controllers/PermittedUserController.php index 1774ce6a..da612334 100644 --- a/app/Http/Controllers/PermittedUserController.php +++ b/app/Http/Controllers/PermittedUserController.php @@ -10,7 +10,7 @@ use App\Request\Parameter; use App\Request\Route; use App\Response\Header\Headers; -use App\Utilities\Pagination as UtilityPagination; +use App\Response\Pagination as UtilityPagination; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Config; diff --git a/app/Http/Controllers/RequestController.php b/app/Http/Controllers/RequestController.php index 7118543a..a1acafc4 100644 --- a/app/Http/Controllers/RequestController.php +++ b/app/Http/Controllers/RequestController.php @@ -11,7 +11,7 @@ use App\Models\RequestLog; use App\Models\Transformers\RequestErrorLog as RequestErrorLogTransformer; use App\Models\Transformers\RequestLog as RequestLogTransformer; -use App\Utilities\Pagination as UtilityPagination; +use App\Response\Pagination as UtilityPagination; use App\Request\Validate\RequestErrorLog as RequestErrorLogValidator; use Exception; use Illuminate\Http\JsonResponse; diff --git a/app/Http/Controllers/ResourceController.php b/app/Http/Controllers/ResourceController.php index 27c14f75..b499f070 100644 --- a/app/Http/Controllers/ResourceController.php +++ b/app/Http/Controllers/ResourceController.php @@ -11,7 +11,7 @@ use App\Request\Parameter; use App\Request\Route; use App\Response\Header\Headers; -use App\Utilities\Pagination as UtilityPagination; +use App\Response\Pagination as UtilityPagination; use App\Models\Resource; use App\Models\Transformers\Resource as ResourceTransformer; use App\Request\Validate\Resource as ResourceValidator; diff --git a/app/Http/Controllers/ResourceTypeController.php b/app/Http/Controllers/ResourceTypeController.php index 9e390ab2..1a9ed01a 100644 --- a/app/Http/Controllers/ResourceTypeController.php +++ b/app/Http/Controllers/ResourceTypeController.php @@ -15,7 +15,7 @@ use App\Response\Header\Headers; use App\Request\Parameter; use App\Request\Route; -use App\Utilities\Pagination as UtilityPagination; +use App\Response\Pagination as UtilityPagination; use App\Models\ResourceType; use App\Models\Transformers\ResourceType as ResourceTypeTransformer; use App\Request\Validate\ResourceType as ResourceTypeValidator; diff --git a/app/Http/Controllers/ResourceTypeItemController.php b/app/Http/Controllers/ResourceTypeItemController.php index 86175af7..0d614483 100644 --- a/app/Http/Controllers/ResourceTypeItemController.php +++ b/app/Http/Controllers/ResourceTypeItemController.php @@ -10,7 +10,7 @@ use App\Models\Category; use App\Models\Subcategory; use App\Response\Header\Headers; -use App\Utilities\Pagination as UtilityPagination; +use App\Response\Pagination as UtilityPagination; use Illuminate\Http\JsonResponse; /** diff --git a/app/Http/Controllers/SubcategoryController.php b/app/Http/Controllers/SubcategoryController.php index 5d0b15f6..da347d36 100644 --- a/app/Http/Controllers/SubcategoryController.php +++ b/app/Http/Controllers/SubcategoryController.php @@ -11,7 +11,7 @@ use App\Request\Parameter; use App\Request\Route; use App\Response\Header\Headers; -use App\Utilities\Pagination as UtilityPagination; +use App\Response\Pagination as UtilityPagination; use App\Models\Subcategory; use App\Models\Transformers\Subcategory as SubcategoryTransformer; use App\Request\Validate\Subcategory as SubcategoryValidator; diff --git a/app/Utilities/Pagination.php b/app/Response/Pagination.php similarity index 99% rename from app/Utilities/Pagination.php rename to app/Response/Pagination.php index dc85cc11..3724c52c 100644 --- a/app/Utilities/Pagination.php +++ b/app/Response/Pagination.php @@ -1,7 +1,7 @@ Date: Thu, 25 Jun 2020 15:18:54 +0100 Subject: [PATCH 08/24] Fixes - Moved namespace so Hash no longer available. - Correctly assign subcategories to transformer. --- app/Http/Controllers/CategoryController.php | 2 +- app/Response/Pagination.php | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/app/Http/Controllers/CategoryController.php b/app/Http/Controllers/CategoryController.php index 3896fd57..5aafbab5 100644 --- a/app/Http/Controllers/CategoryController.php +++ b/app/Http/Controllers/CategoryController.php @@ -158,7 +158,7 @@ public function show($resource_type_id, $category_id): JsonResponse } return response()->json( - (new CategoryTransformer($category, $subcategories))->asArray(), + (new CategoryTransformer($category, ['subcategories'=>$subcategories]))->asArray(), 200, $headers->headers() ); diff --git a/app/Response/Pagination.php b/app/Response/Pagination.php index 3724c52c..c7095ee7 100644 --- a/app/Response/Pagination.php +++ b/app/Response/Pagination.php @@ -5,6 +5,7 @@ use App\Request\Validate\Boolean; +use App\Utilities\Hash; use Illuminate\Support\Facades\Config; /** From b75d7bfb2e416ffc2a4b56e70450446da6c8a3ef Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Thu, 25 Jun 2020 16:22:29 +0100 Subject: [PATCH 09/24] *** Interim commit *** - Reworking the pagination helper. - Correcting all calls to pagination helprr. - Added filtering params to pagination helper. --- .../Controllers/ResourceTypeController.php | 19 +- .../ResourceTypeItemController.php | 19 +- app/Response/Pagination.php | 263 ++++++++---------- 3 files changed, 138 insertions(+), 163 deletions(-) diff --git a/app/Http/Controllers/ResourceTypeController.php b/app/Http/Controllers/ResourceTypeController.php index 1a9ed01a..60fc22c3 100644 --- a/app/Http/Controllers/ResourceTypeController.php +++ b/app/Http/Controllers/ResourceTypeController.php @@ -65,18 +65,17 @@ public function index(): JsonResponse $search_parameters ); - $pagination = UtilityPagination::init( - request()->path(), - $total, - 10, - $this->allow_entire_collection - )->setSearchParameters($search_parameters)->setSortParameters($sort_parameters)->paging(); + $pagination = new UtilityPagination(request()->path(), $total); + $pagination_parameters = $pagination->allowPaginationOverride($this->allow_entire_collection)-> + setSearchParameters($search_parameters)-> + setSortParameters($sort_parameters)-> + parameters(); $resource_types = (new ResourceType())->paginatedCollection( $this->permitted_resource_types, $this->include_public, - $pagination['offset'], - $pagination['limit'], + $pagination_parameters['offset'], + $pagination_parameters['limit'], $search_parameters, $sort_parameters ); @@ -89,13 +88,13 @@ static function ($resource_type) { ); $headers = new Headers(); - $headers->collection($pagination, count($resource_types), $total)-> + $headers->collection($pagination_parameters, count($resource_types), $total)-> addCacheControl($cache_control->visibility(), $cache_control->ttl())-> addETag($collection)-> addSearch(Parameter\Search::xHeader())-> addSort(Parameter\Sort::xHeader()); - $cache_collection->create($total, $collection, $pagination, $headers->headers()); + $cache_collection->create($total, $collection, $pagination_parameters, $headers->headers()); $cache_control->put(request()->getRequestUri(), $cache_collection->content()); } diff --git a/app/Http/Controllers/ResourceTypeItemController.php b/app/Http/Controllers/ResourceTypeItemController.php index 0d614483..b1b56d9e 100644 --- a/app/Http/Controllers/ResourceTypeItemController.php +++ b/app/Http/Controllers/ResourceTypeItemController.php @@ -72,14 +72,19 @@ public function index(string $resource_type_id): JsonResponse $filter_parameters ); - $pagination = UtilityPagination::init(request()->path(), $total) - ->setParameters() - ->paging(); + $pagination = new UtilityPagination(request()->path(), $total); + $pagination_parameters = $pagination->allowPaginationOverride($this->allow_entire_collection)-> + setSearchParameters($search_parameters)-> + setSortParameters($sort_fields)-> + setParameters($collection_parameters)-> + setFilteringParameters($filter_parameters)-> + parameters(); + $items = $resource_type_item_model->paginatedCollection( $resource_type_id, - $pagination['offset'], - $pagination['limit'], + $pagination_parameters['offset'], + $pagination_parameters['limit'], $collection_parameters, $search_parameters, $filter_parameters, @@ -94,7 +99,7 @@ static function ($item) use ($item_interface) { ); $headers = new Headers(); - $headers->collection($pagination, count($items), $total)-> + $headers->collection($pagination_parameters, count($items), $total)-> addCacheControl($cache_control->visibility(), $cache_control->ttl())-> addETag($collection)-> addSearch(Parameter\Search::xHeader())-> @@ -102,7 +107,7 @@ static function ($item) use ($item_interface) { addParameters(Parameter\Request::xHeader())-> addFilters(Parameter\Filter::xHeader()); - $cache_collection->create($total, $collection, $pagination, $headers->headers()); + $cache_collection->create($total, $collection, $pagination_parameters, $headers->headers()); $cache_control->put(request()->getRequestUri(), $cache_collection->content()); } diff --git a/app/Response/Pagination.php b/app/Response/Pagination.php index c7095ee7..8b7154a0 100644 --- a/app/Response/Pagination.php +++ b/app/Response/Pagination.php @@ -9,11 +9,7 @@ use Illuminate\Support\Facades\Config; /** - * Pagination helper - * - * As with all utility classes, eventually they may be moved into libraries if - * they gain more than a few functions and the creation of a library makes - * sense. + * Generate the pagination URIs based on th request * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 @@ -21,160 +17,137 @@ */ class Pagination { - private static $instance; + private array $parameters; + private array $sort_parameters; + private array $search_parameters; + private array $filtering_parameters; + + private int $offset; + + private bool $collection; + private bool $allow_override; + + private Hash $hash; + + private string $uri; + private int $total; + private int $limit; /** - * @var array - */ - private static $parameters; - /** - * @var array - */ - private static $sort_parameters; - /** - * @var array - */ - private static $search_parameters; - /** - * @var int - */ - private static $limit; - /** - * @var int - */ - private static $offset; - /** - * @var boolean - */ - private static $collection; - /** - * @var boolean - */ - private static $allow_override; - /** - * @var int - */ - private static $total; - /** - * @var string + * @param string $uri The base URI for the pagination URIs + * @param int $total Set the total number of items in collection + * @param int $limit Set the 'per page' limit */ - private static $uri; + public function __construct( + string $uri, + int $total, + int $limit = 10 + ) { + $this->parameters = []; + $this->sort_parameters = []; + $this->search_parameters = []; + + $this->limit = $limit; + $this->total = $total; + $this->uri = $uri; + $this->hash = new Hash(); + $this->offset = 0; + $this->allow_override = false; + $this->collection = false; + } + /** - * @var Hash + * Is the user able to request the entire collection? + * + * @param bool $allow_override + * + * @return Pagination */ - private static $hash; + public function allowPaginationOverride(bool $allow_override): Pagination + { + $this->allow_override = $allow_override; + + return $this; + } /** - * Constructor + * Set any request parameters * - * @param string $uri Set the pagination uri - * @param int $total Set the total number of items in collection - * @param int $limit Set the 'per page' limit - * @param boolean $allow_override Allow the pagination to be overridden via the collection parameter + * @param array $parameters * * @return Pagination */ - public static function init( - string $uri, - int $total, - int $limit = 10, - bool $allow_override = false - ): Pagination + public function setParameters(array $parameters = []): Pagination { - if (self::$instance === null) { - self::$instance = new self; - } + $this->parameters = $parameters; - self::$parameters = []; - self::$sort_parameters = []; - self::$search_parameters = []; - self::$limit = $limit; - self::$total = $total; - self::$uri = $uri; - self::$hash = new Hash(); - self::$offset = 0; - self::$allow_override = $allow_override; - self::$collection = false; - - return self::$instance; + return $this; } /** - * Set any optional route parameters + * Set any request filtering parameters * * @param array $parameters * * @return Pagination */ - public static function setParameters(array $parameters = []): Pagination + public function setFilteringParameters(array $parameters = []): Pagination { - self::$parameters = $parameters; + $this->filtering_parameters = $parameters; - return self::$instance; + return $this; } /** - * Set any optional sort parameters + * Set any request sort parameters * * @param array $parameters * * @return Pagination */ - public static function setSortParameters(array $parameters = []): Pagination + public function setSortParameters(array $parameters = []): Pagination { - self::$sort_parameters = $parameters; + $this->sort_parameters = $parameters; - return self::$instance; + return $this; } /** - * Set any optional search parameters + * Set any request search parameters * * @param array $parameters * * @return Pagination */ - public static function setSearchParameters(array $parameters = []): Pagination + public function setSearchParameters(array $parameters = []): Pagination { - self::$search_parameters = $parameters; + $this->search_parameters = $parameters; - return self::$instance; + return $this; } /** - * Return the pagination array + * Return the generated pagination parameters, the uris for next and + * previous, the defined offset and limit * * @return array */ - public static function paging(): array + public function parameters(): array { - $pagination_uris = self::render(); - - if (self::$collection === false) { - return [ - 'links' => $pagination_uris, - 'offset' => self::$offset, - 'limit' => self::$limit - ]; - } + $uris = $this->generateUris(); return [ - 'links' => $pagination_uris, - 'offset' => 0, - 'limit' => self::$total + 'links' => $uris, + 'offset' => ($this->collection === false ? $this->offset : 0), + 'limit' => ($this->collection === false ? $this->limit : $this->total) ]; } - /** - * Process any passed in parameters, encoding as required - * - * @return string - */ - private static function processParameters(): string + private function processParameters(): string { $parameters = ''; - if (count(self::$parameters) > 0) { - foreach (self::$parameters as $parameter => $parameter_value) { + if (count($this->parameters) > 0) { + foreach ($this->parameters as $parameter => $parameter_value) { if ($parameter_value !== null) { if ($parameters !== '') { $parameters .= '&'; @@ -184,7 +157,7 @@ private static function processParameters(): string case 'category': case 'subcategory': $parameters .= $parameter . '=' . - self::$hash->encode($parameter, $parameter_value); + $this->hash->encode($parameter, $parameter_value); break; default: @@ -202,15 +175,24 @@ private static function processParameters(): string return $parameters; } - /** - * Process any sort parameters - * - * @return string - */ - private static function processSortParameters(): string + private function processFilterParameters(): string + { + $filter_parameters = ''; + foreach ($this->filtering_parameters as $field => $ranges) { + $filter_parameters .= '|' . $field . ':' . $ranges['from'] . ':' . $ranges['to']; + } + + if ($filter_parameters !== '') { + $filter_parameters = 'filter=' . ltrim($filter_parameters, '|') . '&'; + } + + return $filter_parameters; + } + + private function processSortParameters(): string { $sort_parameters = ''; - foreach (self::$sort_parameters as $field => $order) { + foreach ($this->sort_parameters as $field => $order) { $sort_parameters .= '|' . $field . ':' . $order; } @@ -221,15 +203,10 @@ private static function processSortParameters(): string return $sort_parameters; } - /** - * Process any search parameters - * - * @return string - */ - private static function processSearchParameters(): string + private function processSearchParameters(): string { $search_parameters = ''; - foreach (self::$search_parameters as $field => $partial_term) { + foreach ($this->search_parameters as $field => $partial_term) { $search_parameters .= '|' . $field . ':' . urlencode($partial_term); } @@ -240,22 +217,13 @@ private static function processSearchParameters(): string return $search_parameters; } - /** - * Create the paging uris - * - * @return array - */ - private static function render(): array + private function generateUris(): array { - self::$offset = (int) request()->query('offset', 0); - self::$limit = (int) request()->query('limit', self::$limit); - if (self::$allow_override === true) { - - self::$collection = false; + $this->offset = (int) request()->query('offset', 0); + $this->limit = (int) request()->query('limit', $this->limit); - if (Boolean::convertedValue(request()->query('collection')) === true) { - self::$collection = true; - } + if ($this->allow_override === true && Boolean::convertedValue(request()->query('collection')) === true) { + $this->collection = true; } $uris = [ @@ -263,34 +231,37 @@ private static function render(): array 'previous' => null ]; - if (self::$collection === false) { + if ($this->collection === false) { $previous_offset = null; $next_offset = null; - if (self::$offset !== 0) { - $previous_offset = abs(self::$offset - self::$limit); + if ($this->offset !== 0) { + $previous_offset = abs($this->offset - $this->limit); } - if (self::$offset + self::$limit < self::$total) { - $next_offset = self::$offset + self::$limit; + if ($this->offset + $this->limit < $this->total) { + $next_offset = $this->offset + $this->limit; } - $parameters = self::processParameters(); - $sort_parameters = self::processSortParameters(); - $search_parameters = self::processSearchParameters(); + $parameters = $this->processParameters(); + $sort_parameters = $this->processSortParameters(); + $search_parameters = $this->processSearchParameters(); + $filter_parameters = $this->processFilterParameters(); - self::$uri .= '?'; + $this->uri .= '?'; if ($previous_offset !== null) { - $uris['previous'] .= Config::get('api.app.url') . '/' . self::$uri . - $parameters . $sort_parameters . $search_parameters . 'offset=' . $previous_offset . '&limit=' . - self::$limit; + $uris['previous'] .= Config::get('api.app.url') . '/' . $this->uri . + $parameters . $sort_parameters . $search_parameters . + $filter_parameters . 'offset=' . $previous_offset . '&limit=' . + $this->limit; } if ($next_offset !== null) { - $uris['next'] .= Config::get('api.app.url') . '/' . self::$uri . - $parameters . $sort_parameters . $search_parameters . 'offset=' . $next_offset . '&limit=' . - self::$limit; + $uris['next'] .= Config::get('api.app.url') . '/' . $this->uri . + $parameters . $sort_parameters . $search_parameters . + $filter_parameters . 'offset=' . $next_offset . '&limit=' . + $this->limit; } } From 779781c2458a303c7e6d57f13b2ee805f5a9edb8 Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Fri, 26 Jun 2020 00:33:51 +0100 Subject: [PATCH 10/24] Pagaintion - Update controllers to use reworked pagination class. --- app/Http/Controllers/CategoryController.php | 18 +++++------- app/Http/Controllers/ItemController.php | 20 +++++++------ .../ItemPartialTransferController.php | 18 ++++++------ .../Controllers/ItemTransferController.php | 18 ++++++------ app/Http/Controllers/ItemTypeController.php | 18 +++++------- .../Controllers/PermittedUserController.php | 19 ++++++------- app/Http/Controllers/RequestController.php | 28 ++++++++++--------- app/Http/Controllers/ResourceController.php | 18 +++++------- .../Controllers/SubcategoryController.php | 18 +++++------- .../Controllers/Summary/RequestController.php | 1 - .../Summary/ResourceController.php | 1 - .../Summary/ResourceTypeController.php | 1 - app/Response/Pagination.php | 1 + 13 files changed, 80 insertions(+), 99 deletions(-) diff --git a/app/Http/Controllers/CategoryController.php b/app/Http/Controllers/CategoryController.php index 5aafbab5..f86e479b 100644 --- a/app/Http/Controllers/CategoryController.php +++ b/app/Http/Controllers/CategoryController.php @@ -68,22 +68,18 @@ public function index($resource_type_id): JsonResponse $search_parameters ); - $pagination = UtilityPagination::init( - request()->path(), - $total, - 10, - $this->allow_entire_collection - )-> + $pagination = new UtilityPagination(request()->path(), $total); + $pagination_parameters = $pagination->allowPaginationOverride($this->allow_entire_collection)-> setSearchParameters($search_parameters)-> setSortParameters($sort_parameters)-> - paging(); + parameters(); $categories = (new Category())->paginatedCollection( (int)$resource_type_id, $this->permitted_resource_types, $this->include_public, - $pagination['offset'], - $pagination['limit'], + $pagination_parameters['offset'], + $pagination_parameters['limit'], $search_parameters, $sort_parameters ); @@ -96,13 +92,13 @@ static function ($category) { ); $headers = new Headers(); - $headers->collection($pagination, count($categories), $total)-> + $headers->collection($pagination_parameters, count($categories), $total)-> addCacheControl($cache_control->visibility(), $cache_control->ttl())-> addETag($collection)-> addSearch(Parameter\Search::xHeader())-> addSort(Parameter\Sort::xHeader()); - $cache_collection->create($total, $collection, $pagination, $headers->headers()); + $cache_collection->create($total, $collection, $pagination_parameters, $headers->headers()); $cache_control->put(request()->getRequestUri(), $cache_collection->content()); } diff --git a/app/Http/Controllers/ItemController.php b/app/Http/Controllers/ItemController.php index 16297b5b..67d4fa98 100644 --- a/app/Http/Controllers/ItemController.php +++ b/app/Http/Controllers/ItemController.php @@ -88,17 +88,19 @@ public function index( $filter_parameters ); - $pagination = UtilityPagination::init(request()->path(), $total) - ->setParameters($parameters) - ->setSortParameters($sort_parameters) - ->setSearchParameters($search_parameters) - ->paging(); + $pagination = new UtilityPagination(request()->path(), $total); + $pagination_parameters = $pagination->allowPaginationOverride($this->allow_entire_collection)-> + setParameters($parameters)-> + setSearchParameters($search_parameters)-> + setSortParameters($sort_parameters)-> + setFilteringParameters($filter_parameters)-> + parameters(); $items = $item_model->paginatedCollection( $resource_type_id, $resource_id, - $pagination['offset'], - $pagination['limit'], + $pagination_parameters['offset'], + $pagination_parameters['limit'], $parameters, $search_parameters, $filter_parameters, @@ -113,7 +115,7 @@ static function ($item) use ($item_interface) { ); $headers = new Headers(); - $headers->collection($pagination, count($items), $total)-> + $headers->collection($pagination_parameters, count($items), $total)-> addCacheControl($cache_control->visibility(), $cache_control->ttl())-> addETag($collection)-> addSearch(Parameter\Search::xHeader())-> @@ -121,7 +123,7 @@ static function ($item) use ($item_interface) { addParameters(Parameter\Request::xHeader())-> addFilters(Parameter\Filter::xHeader()); - $cache_collection->create($total, $collection, $pagination, $headers->headers()); + $cache_collection->create($total, $collection, $pagination_parameters, $headers->headers()); $cache_control->put(request()->getRequestUri(), $cache_collection->content()); } diff --git a/app/Http/Controllers/ItemPartialTransferController.php b/app/Http/Controllers/ItemPartialTransferController.php index 3848e03a..60b44d09 100644 --- a/app/Http/Controllers/ItemPartialTransferController.php +++ b/app/Http/Controllers/ItemPartialTransferController.php @@ -62,19 +62,17 @@ public function index($resource_type_id): JsonResponse $parameters ); - $pagination = UtilityPagination::init( - request()->path(), - $total, - 10, - $this->allow_entire_collection - )->paging(); + $pagination = new UtilityPagination(request()->path(), $total); + $pagination_parameters = $pagination->allowPaginationOverride($this->allow_entire_collection)-> + setParameters($parameters)-> + parameters(); $transfers = (new ItemPartialTransfer())->paginatedCollection( (int)$resource_type_id, $this->permitted_resource_types, $this->include_public, - $pagination['offset'], - $pagination['limit'], + $pagination_parameters['offset'], + $pagination_parameters['limit'], $parameters ); @@ -86,11 +84,11 @@ static function ($transfer) { ); $headers = new Headers(); - $headers->collection($pagination, count($transfers), $total)-> + $headers->collection($pagination_parameters, count($transfers), $total)-> addCacheControl($cache_control->visibility(), $cache_control->ttl())-> addETag($collection); - $cache_collection->create($total, $collection, $pagination, $headers->headers()); + $cache_collection->create($total, $collection, $pagination_parameters, $headers->headers()); $cache_control->put(request()->getRequestUri(), $cache_collection->content()); } diff --git a/app/Http/Controllers/ItemTransferController.php b/app/Http/Controllers/ItemTransferController.php index 0bface2b..e6f414d5 100644 --- a/app/Http/Controllers/ItemTransferController.php +++ b/app/Http/Controllers/ItemTransferController.php @@ -62,19 +62,17 @@ public function index($resource_type_id): JsonResponse $parameters ); - $pagination = UtilityPagination::init( - request()->path(), - $total, - 10, - $this->allow_entire_collection - )->paging(); + $pagination = new UtilityPagination(request()->path(), $total); + $pagination_parameters = $pagination->allowPaginationOverride($this->allow_entire_collection)-> + setParameters($parameters)-> + parameters(); $transfers = (new ItemTransfer())->paginatedCollection( (int)$resource_type_id, $this->permitted_resource_types, $this->include_public, - $pagination['offset'], - $pagination['limit'], + $pagination_parameters['offset'], + $pagination_parameters['limit'], $parameters ); @@ -86,11 +84,11 @@ static function ($transfer) { ); $headers = new Headers(); - $headers->collection($pagination, count($transfers), $total)-> + $headers->collection($pagination_parameters, count($transfers), $total)-> addCacheControl($cache_control->visibility(), $cache_control->ttl())-> addETag($collection); - $cache_collection->create($total, $collection, $pagination, $headers->headers()); + $cache_collection->create($total, $collection, $pagination_parameters, $headers->headers()); $cache_control->put(request()->getRequestUri(), $cache_collection->content()); } diff --git a/app/Http/Controllers/ItemTypeController.php b/app/Http/Controllers/ItemTypeController.php index 7b2428e2..ad33a4d3 100644 --- a/app/Http/Controllers/ItemTypeController.php +++ b/app/Http/Controllers/ItemTypeController.php @@ -49,19 +49,15 @@ public function index(): JsonResponse $total = (new ItemType())->totalCount($search_parameters); - $pagination = UtilityPagination::init( - request()->path(), - $total, - 10, - $this->allow_entire_collection - )-> + $pagination = new UtilityPagination(request()->path(), $total); + $pagination_parameters = $pagination->allowPaginationOverride($this->allow_entire_collection)-> setSearchParameters($search_parameters)-> setSortParameters($sort_parameters)-> - paging(); + parameters(); $item_types = (new ItemType())->paginatedCollection( - $pagination['offset'], - $pagination['limit'], + $pagination_parameters['offset'], + $pagination_parameters['limit'], $search_parameters, $sort_parameters ); @@ -74,13 +70,13 @@ static function($item_type) { ); $headers = new Headers(); - $headers->collection($pagination, count($item_types), $total)-> + $headers->collection($pagination_parameters, count($item_types), $total)-> addCacheControl($cache_control->visibility(), $cache_control->ttl())-> addETag($collection)-> addSearch(Parameter\Search::xHeader())-> addSort(Parameter\Sort::xHeader()); - $cache_collection->create($total, $collection, $pagination, $headers->headers()); + $cache_collection->create($total, $collection, $pagination_parameters, $headers->headers()); $cache_control->put(request()->getRequestUri(), $cache_collection->content()); } diff --git a/app/Http/Controllers/PermittedUserController.php b/app/Http/Controllers/PermittedUserController.php index da612334..6fc4283a 100644 --- a/app/Http/Controllers/PermittedUserController.php +++ b/app/Http/Controllers/PermittedUserController.php @@ -60,17 +60,16 @@ public function index(string $resource_type_id): JsonResponse $search_parameters ); - $pagination = UtilityPagination::init( - request()->path(), - $total, - 10, - $this->allow_entire_collection - )->setSearchParameters($search_parameters)->setSortParameters($sort_parameters)->paging(); + $pagination = new UtilityPagination(request()->path(), $total); + $pagination_parameters = $pagination->allowPaginationOverride($this->allow_entire_collection)-> + setSearchParameters($search_parameters)-> + setSortParameters($sort_parameters)-> + parameters(); $permitted_users = (new PermittedUser())->paginatedCollection( $resource_type_id, - $pagination['offset'], - $pagination['limit'], + $pagination_parameters['offset'], + $pagination_parameters['limit'], $search_parameters, $sort_parameters ); @@ -83,13 +82,13 @@ static function ($permitted_user) { ); $headers = new Headers(); - $headers->collection($pagination, count($permitted_users), $total)-> + $headers->collection($pagination_parameters, count($permitted_users), $total)-> addCacheControl($cache_control->visibility(), $cache_control->ttl())-> addETag($collection)-> addSearch(Parameter\Search::xHeader())-> addSort(Parameter\Sort::xHeader()); - $cache_collection->create($total, $collection, $pagination, $headers->headers()); + $cache_collection->create($total, $collection, $pagination_parameters, $headers->headers()); $cache_control->put(request()->getRequestUri(), $cache_collection->content()); } diff --git a/app/Http/Controllers/RequestController.php b/app/Http/Controllers/RequestController.php index a1acafc4..a256908b 100644 --- a/app/Http/Controllers/RequestController.php +++ b/app/Http/Controllers/RequestController.php @@ -37,26 +37,26 @@ public function errorLog(): JsonResponse { $total = (new RequestErrorLog())->totalCount(); - $pagination = UtilityPagination::init(request()->path(), $total, 50) - ->paging(); + $pagination = new UtilityPagination(request()->path(), $total, 50); + $pagination_parameters = $pagination->parameters(); $logs = (new RequestErrorLog())->paginatedCollection( - $pagination['offset'], - $pagination['limit'] + $pagination_parameters['offset'], + $pagination_parameters['limit'] ); $headers = [ 'X-Count' => count($logs), 'X-Total-Count' => $total, - 'X-Offset' => $pagination['offset'], - 'X-Limit' => $pagination['limit'], - 'X-Link-Previous' => $pagination['links']['previous'], - 'X-Link-Next' => $pagination['links']['next'], + 'X-Offset' => $pagination_parameters['offset'], + 'X-Limit' => $pagination_parameters['limit'], + 'X-Link-Previous' => $pagination_parameters['links']['previous'], + 'X-Link-Next' => $pagination_parameters['links']['next'], ]; return response()->json( array_map( - function($log) { + static function($log) { return (new RequestErrorLogTransformer($log))->asArray(); }, $logs @@ -79,16 +79,18 @@ public function accessLog(): JsonResponse array_keys(Config::get('api.request-access-log.parameters.collection')) ); - $pagination = UtilityPagination::init(request()->path(), $total, 25)->paging(); + $pagination = new UtilityPagination(request()->path(), $total, 25); + $pagination_parameters = $pagination->setParameters($this->collection_parameters)-> + parameters(); $log = (new RequestLog())->paginatedCollection( - $pagination['offset'], - $pagination['limit'], + $pagination_parameters['offset'], + $pagination_parameters['limit'], $this->collection_parameters ); $headers = new Header(); - $headers->collection($pagination, count($log), $total); + $headers->collection($pagination_parameters, count($log), $total); $parameters_header = Parameter\Request::xHeader(); if ($parameters_header !== null) { diff --git a/app/Http/Controllers/ResourceController.php b/app/Http/Controllers/ResourceController.php index b499f070..63402e6b 100644 --- a/app/Http/Controllers/ResourceController.php +++ b/app/Http/Controllers/ResourceController.php @@ -69,20 +69,16 @@ public function index(string $resource_type_id): JsonResponse $search_parameters ); - $pagination = UtilityPagination::init( - request()->path(), - $total, - 10, - $this->allow_entire_collection - )-> + $pagination = new UtilityPagination(request()->path(), $total); + $pagination_parameters = $pagination->allowPaginationOverride($this->allow_entire_collection)-> setSearchParameters($search_parameters)-> setSortParameters($sort_parameters)-> - paging(); + parameters(); $resources = (new Resource)->paginatedCollection( $resource_type_id, - $pagination['offset'], - $pagination['limit'], + $pagination_parameters['offset'], + $pagination_parameters['limit'], $search_parameters, $sort_parameters ); @@ -95,13 +91,13 @@ static function ($resource) { ); $headers = new Headers(); - $headers->collection($pagination, count($resources), $total)-> + $headers->collection($pagination_parameters, count($resources), $total)-> addCacheControl($cache_control->visibility(), $cache_control->ttl())-> addETag($collection)-> addSearch(Parameter\Search::xHeader())-> addSort(Parameter\Sort::xHeader()); - $cache_collection->create($total, $collection, $pagination, $headers->headers()); + $cache_collection->create($total, $collection, $pagination_parameters, $headers->headers()); $cache_control->put(request()->getRequestUri(), $cache_collection->content()); } diff --git a/app/Http/Controllers/SubcategoryController.php b/app/Http/Controllers/SubcategoryController.php index da347d36..8395f98a 100644 --- a/app/Http/Controllers/SubcategoryController.php +++ b/app/Http/Controllers/SubcategoryController.php @@ -70,21 +70,17 @@ public function index($resource_type_id, $category_id): JsonResponse $search_parameters ); - $pagination = UtilityPagination::init( - request()->path(), - $total, - 10, - $this->allow_entire_collection - )-> + $pagination = new UtilityPagination(request()->path(), $total); + $pagination_parameters = $pagination->allowPaginationOverride($this->allow_entire_collection)-> setSearchParameters($search_parameters)-> setSortParameters($sort_parameters)-> - paging(); + parameters(); $subcategories = (new Subcategory())->paginatedCollection( (int)$resource_type_id, (int)$category_id, - $pagination['offset'], - $pagination['limit'], + $pagination_parameters['offset'], + $pagination_parameters['limit'], $search_parameters, $sort_parameters ); @@ -97,13 +93,13 @@ static function ($subcategory) { ); $headers = new Headers(); - $headers->collection($pagination, count($subcategories), $total)-> + $headers->collection($pagination_parameters, count($subcategories), $total)-> addCacheControl($cache_control->visibility(), $cache_control->ttl())-> addETag($collection)-> addSearch(Parameter\Search::xHeader())-> addSort(Parameter\Sort::xHeader()); - $cache_collection->create($total, $collection, $pagination, $headers->headers()); + $cache_collection->create($total, $collection, $pagination_parameters, $headers->headers()); $cache_control->put(request()->getRequestUri(), $cache_collection->content()); } diff --git a/app/Http/Controllers/Summary/RequestController.php b/app/Http/Controllers/Summary/RequestController.php index 4a935bac..57556138 100644 --- a/app/Http/Controllers/Summary/RequestController.php +++ b/app/Http/Controllers/Summary/RequestController.php @@ -5,7 +5,6 @@ use App\Http\Controllers\Controller; use App\Option\Get; use App\Response\Cache; -use App\Response\Header\Header; use App\Request\Parameter; use App\Models\Summary\RequestLog; use App\Response\Header\Headers; diff --git a/app/Http/Controllers/Summary/ResourceController.php b/app/Http/Controllers/Summary/ResourceController.php index 634e0eed..3bf71f25 100644 --- a/app/Http/Controllers/Summary/ResourceController.php +++ b/app/Http/Controllers/Summary/ResourceController.php @@ -5,7 +5,6 @@ use App\Http\Controllers\Controller; use App\Option\Get; use App\Response\Cache; -use App\Response\Header\Header; use App\Request\Parameter; use App\Request\Route; use App\Models\Summary\Resource; diff --git a/app/Http/Controllers/Summary/ResourceTypeController.php b/app/Http/Controllers/Summary/ResourceTypeController.php index 38122f3b..703792f6 100644 --- a/app/Http/Controllers/Summary/ResourceTypeController.php +++ b/app/Http/Controllers/Summary/ResourceTypeController.php @@ -6,7 +6,6 @@ use App\Models\Summary\ResourceType; use App\Option\Get; use App\Response\Cache; -use App\Response\Header\Header; use App\Request\Parameter; use App\Response\Header\Headers; use Illuminate\Http\JsonResponse; diff --git a/app/Response/Pagination.php b/app/Response/Pagination.php index 8b7154a0..e735314b 100644 --- a/app/Response/Pagination.php +++ b/app/Response/Pagination.php @@ -46,6 +46,7 @@ public function __construct( $this->parameters = []; $this->sort_parameters = []; $this->search_parameters = []; + $this->filtering_parameters = []; $this->limit = $limit; $this->total = $total; From 73e84668a35a5326c06889010e470c7b6601cd99 Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Fri, 26 Jun 2020 00:35:01 +0100 Subject: [PATCH 11/24] Fix comment - Fix a comment --- app/Response/Pagination.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/Response/Pagination.php b/app/Response/Pagination.php index e735314b..9e95ea48 100644 --- a/app/Response/Pagination.php +++ b/app/Response/Pagination.php @@ -9,7 +9,7 @@ use Illuminate\Support\Facades\Config; /** - * Generate the pagination URIs based on th request + * Generate the pagination URIs based on all the request parameters * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 From 1009f3c32a57e3370f1b37a569b9f991b5071b33 Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Fri, 26 Jun 2020 00:42:04 +0100 Subject: [PATCH 12/24] Fixes - Minor fixes --- app/Rules/ResourceTypeName.php | 2 +- app/Utilities/Hash.php | 4 +--- app/Utilities/Model.php | 2 +- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/app/Rules/ResourceTypeName.php b/app/Rules/ResourceTypeName.php index 77992679..9ecb2c9f 100644 --- a/app/Rules/ResourceTypeName.php +++ b/app/Rules/ResourceTypeName.php @@ -59,7 +59,7 @@ public function passes($attribute, $value): bool * * @return string */ - public function message() + public function message(): string { return trans(Config::get('api.resource-type.validation.POST.messages')['name.unique']); } diff --git a/app/Utilities/Hash.php b/app/Utilities/Hash.php index 204462fc..17c85672 100644 --- a/app/Utilities/Hash.php +++ b/app/Utilities/Hash.php @@ -26,11 +26,9 @@ public function __construct() $this->hashers = []; $this->setUp(); - - return $this; } - private function setUp() + private function setUp(): void { $config = Config::get('api.app.hashids'); diff --git a/app/Utilities/Model.php b/app/Utilities/Model.php index 90ca25d1..a98cab20 100644 --- a/app/Utilities/Model.php +++ b/app/Utilities/Model.php @@ -57,7 +57,7 @@ public static function applyResourceTypeCollectionCondition( ) { if ($include_public === true) { - $collection->where(function ($collection) use ($permitted_resource_types, $include_public) { + $collection->where(static function ($collection) use ($permitted_resource_types, $include_public) { $collection->where('resource_type.public', '=', (int) $include_public)-> orWhereIn('resource_type.id', $permitted_resource_types); }); From 10fcaf1f0119193be0ed27ce4149367c0005448b Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Fri, 26 Jun 2020 23:17:15 +0100 Subject: [PATCH 13/24] Refactoring - Moved class --- app/Http/Controllers/Controller.php | 2 +- app/Models/Transformers/Transformer.php | 2 +- app/{Utilities => Request}/Hash.php | 5 ++++- app/Request/Validate/Validator.php | 2 +- app/Response/Cache/Key.php | 2 +- app/Response/Pagination.php | 2 +- 6 files changed, 9 insertions(+), 6 deletions(-) rename app/{Utilities => Request}/Hash.php (98%) diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.php index 3c372104..61098c31 100644 --- a/app/Http/Controllers/Controller.php +++ b/app/Http/Controllers/Controller.php @@ -4,7 +4,7 @@ use App\Models\ResourceType; use App\Models\ResourceTypeAccess; -use App\Utilities\Hash; +use App\Request\Hash; use Illuminate\Http\JsonResponse; use Illuminate\Routing\Controller as BaseController; diff --git a/app/Models/Transformers/Transformer.php b/app/Models/Transformers/Transformer.php index dee45ffa..fd664b83 100644 --- a/app/Models/Transformers/Transformer.php +++ b/app/Models/Transformers/Transformer.php @@ -3,7 +3,7 @@ namespace App\Models\Transformers; -use App\Utilities\Hash; +use App\Request\Hash; /** * Our base transformer class, used to convert the results of our queries into diff --git a/app/Utilities/Hash.php b/app/Request/Hash.php similarity index 98% rename from app/Utilities/Hash.php rename to app/Request/Hash.php index 17c85672..4501804e 100644 --- a/app/Utilities/Hash.php +++ b/app/Request/Hash.php @@ -1,7 +1,7 @@ Date: Fri, 26 Jun 2020 23:38:56 +0100 Subject: [PATCH 14/24] Refactoring - Moved model utility class. --- app/Models/Category.php | 9 ++++----- app/{Utilities/Model.php => Models/Clause.php} | 4 ++-- app/Models/ErrorLog.php | 1 - app/Models/Item/AllocatedExpense.php | 10 +++++----- app/Models/Item/SimpleExpense.php | 10 +++++----- app/Models/Item/SimpleItem.php | 15 +++++++-------- app/Models/Item/Summary/AllocatedExpense.php | 6 +++--- app/Models/Item/Summary/SimpleExpense.php | 6 +++--- app/Models/Item/Summary/SimpleItem.php | 6 +++--- app/Models/ItemPartialTransfer.php | 5 ++--- app/Models/ItemTransfer.php | 6 ++---- app/Models/ItemType.php | 5 ++--- app/Models/PermittedUser.php | 5 ++--- app/Models/Resource.php | 7 +++---- app/Models/ResourceType.php | 11 +++++------ app/Models/ResourceTypeAccess.php | 15 +++++++-------- app/Models/ResourceTypeItem/AllocatedExpense.php | 10 +++++----- app/Models/ResourceTypeItem/SimpleExpense.php | 10 +++++----- app/Models/ResourceTypeItem/SimpleItem.php | 10 +++++----- .../ResourceTypeItem/Summary/AllocatedExpense.php | 6 +++--- app/Models/Subcategory.php | 5 ++--- app/Models/Summary/Category.php | 6 +++--- app/Models/Summary/Resource.php | 6 +++--- app/Models/Summary/ResourceType.php | 6 +++--- app/Models/Summary/Subcategory.php | 4 ++-- 25 files changed, 86 insertions(+), 98 deletions(-) rename app/{Utilities/Model.php => Models/Clause.php} (98%) diff --git a/app/Models/Category.php b/app/Models/Category.php index a695a533..6c9f4c34 100644 --- a/app/Models/Category.php +++ b/app/Models/Category.php @@ -3,7 +3,6 @@ namespace App\Models; -use App\Utilities\Model as ModelUtility; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Config; @@ -59,13 +58,13 @@ public function total( join("resource_type", "category.resource_type_id", "resource_type.id")-> where('category.resource_type_id', '=', $resource_type_id); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, $include_public ); - $collection = ModelUtility::applySearch($collection, $this->table, $search_parameters); + $collection = Clause::applySearch($collection, $this->table, $search_parameters); return $collection->count(); } @@ -115,13 +114,13 @@ public function paginatedCollection( join("resource_type", "category.resource_type_id", "resource_type.id")-> where('category.resource_type_id', '=', $resource_type_id); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, $include_public ); - $collection = ModelUtility::applySearch($collection, $this->table, $search_parameters); + $collection = Clause::applySearch($collection, $this->table, $search_parameters); if (count($sort_parameters) > 0) { foreach ($sort_parameters as $field => $direction) { diff --git a/app/Utilities/Model.php b/app/Models/Clause.php similarity index 98% rename from app/Utilities/Model.php rename to app/Models/Clause.php index a98cab20..acd6e573 100644 --- a/app/Utilities/Model.php +++ b/app/Models/Clause.php @@ -1,7 +1,7 @@ where('item_sub_category.sub_category_id', '=', $parameters['subcategory']); } - $collection = ModelUtility::applySearch( + $collection = Clause::applySearch( $collection, $this->table, $search_parameters ); - $collection = ModelUtility::applyFiltering( + $collection = Clause::applyFiltering( $collection, $this->table, $filter_parameters @@ -376,8 +376,8 @@ public function paginatedCollection( $collection->where('item_sub_category.sub_category_id', '=', $parameters['subcategory']); } - $collection = ModelUtility::applySearch($collection, 'item_type_allocated_expense', $search_parameters); - $collection = ModelUtility::applyFiltering($collection, 'item_type_allocated_expense', $filter_parameters); + $collection = Clause::applySearch($collection, 'item_type_allocated_expense', $search_parameters); + $collection = Clause::applyFiltering($collection, 'item_type_allocated_expense', $filter_parameters); if ( array_key_exists('include-unpublished', $parameters) === false || diff --git a/app/Models/Item/SimpleExpense.php b/app/Models/Item/SimpleExpense.php index 82b1aff6..8d454ce3 100644 --- a/app/Models/Item/SimpleExpense.php +++ b/app/Models/Item/SimpleExpense.php @@ -5,7 +5,7 @@ use App\Interfaces\Item\IModel; use App\Request\Validate\Boolean; -use App\Utilities\Model as ModelUtility; +use App\Models\Clause; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Database\Eloquent\Model; @@ -163,12 +163,12 @@ public function totalCount( $collection->where('item_sub_category.sub_category_id', '=', $parameters['subcategory']); } - $collection = ModelUtility::applySearch( + $collection = Clause::applySearch( $collection, $this->table, $search_parameters ); - $collection = ModelUtility::applyFiltering( + $collection = Clause::applyFiltering( $collection, $this->table, $filter_parameters @@ -280,12 +280,12 @@ public function paginatedCollection( $collection->where('item_sub_category.sub_category_id', '=', $parameters['subcategory']); } - $collection = ModelUtility::applySearch( + $collection = Clause::applySearch( $collection, $this->table, $search_parameters ); - $collection = ModelUtility::applyFiltering( + $collection = Clause::applyFiltering( $collection, $this->table, $filter_parameters diff --git a/app/Models/Item/SimpleItem.php b/app/Models/Item/SimpleItem.php index 91d21bd9..f60276a1 100644 --- a/app/Models/Item/SimpleItem.php +++ b/app/Models/Item/SimpleItem.php @@ -4,8 +4,7 @@ namespace App\Models\Item; use App\Interfaces\Item\IModel; -use App\Utilities\General; -use App\Utilities\Model as ModelUtility; +use App\Models\Clause; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Database\Eloquent\Model; @@ -88,9 +87,9 @@ public function single( if ($item !== null) { return $item->toArray(); - } else { - return null; } + + return null; } /** @@ -119,12 +118,12 @@ public function totalCount( where('resource_id', '=', $resource_id)-> where('resource.resource_type_id', '=', $resource_type_id); - $collection = ModelUtility::applySearch( + $collection = Clause::applySearch( $collection, $this->table, $search_parameters ); - $collection = ModelUtility::applyFiltering( + $collection = Clause::applyFiltering( $collection, $this->table, $filter_parameters @@ -173,12 +172,12 @@ public function paginatedCollection( where('resource_id', '=', $resource_id)-> where('resource.resource_type_id', '=', $resource_type_id); - $collection = ModelUtility::applySearch( + $collection = Clause::applySearch( $collection, $this->table, $search_parameters ); - $collection = ModelUtility::applyFiltering( + $collection = Clause::applyFiltering( $collection, $this->table, $filter_parameters diff --git a/app/Models/Item/Summary/AllocatedExpense.php b/app/Models/Item/Summary/AllocatedExpense.php index e434805b..55ae2cba 100644 --- a/app/Models/Item/Summary/AllocatedExpense.php +++ b/app/Models/Item/Summary/AllocatedExpense.php @@ -5,7 +5,7 @@ use App\Interfaces\Item\ISummaryModelCategories; use App\Interfaces\Item\ISummaryModel; -use App\Utilities\Model as ModelUtility; +use App\Models\Clause; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder as QueryBuilder; @@ -164,13 +164,13 @@ public function filteredSummary( $collection->whereRaw(DB::raw("MONTH({$this->sub_table}.effective_date) = {$month}")); } - $collection = ModelUtility::applySearch( + $collection = Clause::applySearch( $collection, $this->sub_table, $search_parameters ); - $collection = ModelUtility::applyFiltering( + $collection = Clause::applyFiltering( $collection, $this->sub_table, $filter_parameters diff --git a/app/Models/Item/Summary/SimpleExpense.php b/app/Models/Item/Summary/SimpleExpense.php index 8d472fc2..cc3f3520 100644 --- a/app/Models/Item/Summary/SimpleExpense.php +++ b/app/Models/Item/Summary/SimpleExpense.php @@ -5,7 +5,7 @@ use App\Interfaces\Item\ISummaryModelCategories; use App\Interfaces\Item\ISummaryModel; -use App\Utilities\Model as ModelUtility; +use App\Models\Clause; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder as QueryBuilder; @@ -151,12 +151,12 @@ public function filteredSummary( $collection->where("sub_category.id", "=", $subcategory_id); } - $collection = ModelUtility::applySearch( + $collection = Clause::applySearch( $collection, $this->sub_table, $search_parameters ); - $collection = ModelUtility::applyFiltering( + $collection = Clause::applyFiltering( $collection, $this->sub_table, $filter_parameters diff --git a/app/Models/Item/Summary/SimpleItem.php b/app/Models/Item/Summary/SimpleItem.php index 590acbf5..16ddd8ad 100644 --- a/app/Models/Item/Summary/SimpleItem.php +++ b/app/Models/Item/Summary/SimpleItem.php @@ -4,7 +4,7 @@ namespace App\Models\Item\Summary; use App\Interfaces\Item\ISummaryModel; -use App\Utilities\Model as ModelUtility; +use App\Models\Clause; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder as QueryBuilder; @@ -59,12 +59,12 @@ public function filteredSummary( where("resource_type.id", "=", $resource_type_id)-> where("resource.id", "=", $resource_id); - $collection = ModelUtility::applySearch( + $collection = Clause::applySearch( $collection, $this->sub_table, $search_parameters ); - $collection = ModelUtility::applyFiltering( + $collection = Clause::applyFiltering( $collection, $this->sub_table, $filter_parameters diff --git a/app/Models/ItemPartialTransfer.php b/app/Models/ItemPartialTransfer.php index 08ef37a6..4f621100 100644 --- a/app/Models/ItemPartialTransfer.php +++ b/app/Models/ItemPartialTransfer.php @@ -3,7 +3,6 @@ namespace App\Models; -use App\Utilities\Model as ModelUtility; use Illuminate\Database\Eloquent\Builder as QueryBuilder; use Illuminate\Database\Eloquent\Model; @@ -65,7 +64,7 @@ public function paginatedCollection( $collection->where($this->table .'.item_id', '=', $parameters['item']); } - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, $include_public @@ -146,7 +145,7 @@ public function total( $collection->where($this->table .'.item_id', '=', $parameters['item']); } - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, $include_public diff --git a/app/Models/ItemTransfer.php b/app/Models/ItemTransfer.php index 4916b4e4..d22083bc 100644 --- a/app/Models/ItemTransfer.php +++ b/app/Models/ItemTransfer.php @@ -3,8 +3,6 @@ namespace App\Models; -use App\Utilities\General; -use App\Utilities\Model as ModelUtility; use Illuminate\Database\Eloquent\Builder as QueryBuilder; use Illuminate\Database\Eloquent\Model; @@ -65,7 +63,7 @@ public function paginatedCollection( $collection->where($this->table .'.item_id', '=', $parameters['item']); } - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, $include_public @@ -145,7 +143,7 @@ public function total( $collection->where($this->table .'.item_id', '=', $parameters['item']); } - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, $include_public diff --git a/app/Models/ItemType.php b/app/Models/ItemType.php index 4035e302..3b3664e3 100644 --- a/app/Models/ItemType.php +++ b/app/Models/ItemType.php @@ -3,7 +3,6 @@ namespace App\Models; -use App\Utilities\Model as ModelUtility; use Illuminate\Database\Eloquent\Builder as QueryBuilder; use Illuminate\Database\Eloquent\Model; @@ -63,7 +62,7 @@ public function paginatedCollection( 'item_type.created_at AS item_type_created_at' ); - $collection = ModelUtility::applySearch($collection, $this->table, $search_parameters); + $collection = Clause::applySearch($collection, $this->table, $search_parameters); if (count($sort_parameters) > 0) { foreach ($sort_parameters as $field => $direction) { @@ -120,7 +119,7 @@ public function totalCount(array $search_parameters = []): int { $collection = $this->select("item_type.id"); - $collection = ModelUtility::applySearch($collection, $this->table, $search_parameters); + $collection = Clause::applySearch($collection, $this->table, $search_parameters); return $collection->count(); } diff --git a/app/Models/PermittedUser.php b/app/Models/PermittedUser.php index 520b333b..00c8665c 100644 --- a/app/Models/PermittedUser.php +++ b/app/Models/PermittedUser.php @@ -3,7 +3,6 @@ namespace App\Models; -use App\Utilities\Model as ModelUtility; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder as QueryBuilder; @@ -53,7 +52,7 @@ public function totalCount( join('users', 'permitted_user.user_id', 'users.id')-> where('permitted_user.resource_type_id', '=', $resource_type_id); - $collection = ModelUtility::applySearch($collection, 'users', $search_parameters); + $collection = Clause::applySearch($collection, 'users', $search_parameters); return $collection->count('permitted_user.id'); } @@ -86,7 +85,7 @@ public function paginatedCollection( join('users', 'permitted_user.user_id', 'users.id')-> where('permitted_user.resource_type_id', '=', $resource_type_id); - $collection = ModelUtility::applySearch($collection, 'users', $search_parameters); + $collection = Clause::applySearch($collection, 'users', $search_parameters); if (count($sort_parameters) > 0) { foreach ($sort_parameters as $field => $direction) { diff --git a/app/Models/Resource.php b/app/Models/Resource.php index 9e689290..3300abb9 100644 --- a/app/Models/Resource.php +++ b/app/Models/Resource.php @@ -3,7 +3,6 @@ namespace App\Models; -use App\Utilities\Model as ModelUtility; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Support\Facades\Config; @@ -53,13 +52,13 @@ public function totalCount( join('resource_type', 'resource.resource_type_id', 'resource_type.id')-> where('resource_type.id', '=', $resource_type_id); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, $include_public ); - $collection = ModelUtility::applySearch($collection, $this->table, $search_parameters); + $collection = Clause::applySearch($collection, $this->table, $search_parameters); return $collection->count(); } @@ -91,7 +90,7 @@ public function paginatedCollection( )-> where('resource_type_id', '=', $resource_type_id); - $collection = ModelUtility::applySearch($collection, $this->table, $search_parameters); + $collection = Clause::applySearch($collection, $this->table, $search_parameters); if (count($sort_parameters) > 0) { foreach ($sort_parameters as $field => $direction) { diff --git a/app/Models/ResourceType.php b/app/Models/ResourceType.php index cef4ed77..7ca0836e 100644 --- a/app/Models/ResourceType.php +++ b/app/Models/ResourceType.php @@ -3,7 +3,6 @@ namespace App\Models; -use App\Utilities\Model as ModelUtility; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Support\Facades\Config; @@ -70,13 +69,13 @@ public function totalCount( { $collection = $this->select("resource_type.id"); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, $include_public ); - $collection = ModelUtility::applySearch($collection, $this->table, $search_parameters); + $collection = Clause::applySearch($collection, $this->table, $search_parameters); return $collection->count(); } @@ -130,13 +129,13 @@ public function paginatedCollection( join('item_type', 'resource_type_item_type.item_type_id', 'item_type.id')-> leftJoin("resource", "resource_type.id", "resource.id"); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, $include_public ); - $collection = ModelUtility::applySearch($collection, $this->table, $search_parameters); + $collection = Clause::applySearch($collection, $this->table, $search_parameters); if (count($sort_parameters) > 0) { foreach ($sort_parameters as $field => $direction) { @@ -227,7 +226,7 @@ public function minimisedCollection( 'resource_type.description AS resource_type_description' ); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, $include_public diff --git a/app/Models/ResourceTypeAccess.php b/app/Models/ResourceTypeAccess.php index 8b2607f2..c5552371 100644 --- a/app/Models/ResourceTypeAccess.php +++ b/app/Models/ResourceTypeAccess.php @@ -3,7 +3,6 @@ namespace App\Models; -use App\Utilities\Model as ModelUtility; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder as QueryBuilder; @@ -60,7 +59,7 @@ public function categoryExistsToUser( join('resource_type', 'category.resource_type_id', 'resource_type.id')-> where('category.resource_type_id', '=', $resource_type_id); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, ($manage === true) ? false : true @@ -101,7 +100,7 @@ public function itemCategoryExistsToUser( where('item.id', '=', $item_id)-> where('item_category.id', '=', $item_category_id); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, ($manage === true) ? false : true @@ -138,7 +137,7 @@ public function itemExistsToUser( where('resource.id', '=', $resource_id)-> where('item.id', '=', $item_id); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, ($manage === true) ? false : true @@ -183,7 +182,7 @@ public function itemSubcategoryExistsToUser( where('item_category.id', '=', $item_category_id)-> where('item_sub_category.id', '=', $item_subcategory_id); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, ($manage === true) ? false : true @@ -254,7 +253,7 @@ public function resourceExistsToUser( where('resource.resource_type_id', '=', $resource_type_id)-> where('resource.id', '=', $resource_id); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, ($manage === true) ? false : true @@ -283,7 +282,7 @@ public function resourceTypeExistsToUser( $collection = $this->from('resource_type')-> where('resource_type.id', '=', $id); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, ($manage === true) ? false : true @@ -320,7 +319,7 @@ public function subcategoryExistsToUser( where('sub_category.category_id', '=', $category_id)-> where('category.resource_type_id', '=', $resource_type_id); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, ($manage === true) ? false : true diff --git a/app/Models/ResourceTypeItem/AllocatedExpense.php b/app/Models/ResourceTypeItem/AllocatedExpense.php index 76857b9d..598db9c5 100644 --- a/app/Models/ResourceTypeItem/AllocatedExpense.php +++ b/app/Models/ResourceTypeItem/AllocatedExpense.php @@ -5,7 +5,7 @@ use App\Interfaces\ResourceTypeItem\IModel; use App\Request\Validate\Boolean; -use App\Utilities\Model as ModelUtility; +use App\Models\Clause; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder as QueryBuilder; @@ -74,13 +74,13 @@ public function totalCount( } } - $collection = ModelUtility::applySearch( + $collection = Clause::applySearch( $collection, $this->item_table, $search_parameters ); - $collection = ModelUtility::applyFiltering( + $collection = Clause::applyFiltering( $collection, $this->item_table, $filter_parameters @@ -214,13 +214,13 @@ public function paginatedCollection( } } - $collection = ModelUtility::applySearch( + $collection = Clause::applySearch( $collection, $this->item_table, $search_parameters ); - $collection = ModelUtility::applyFiltering( + $collection = Clause::applyFiltering( $collection, $this->item_table, $filter_parameters diff --git a/app/Models/ResourceTypeItem/SimpleExpense.php b/app/Models/ResourceTypeItem/SimpleExpense.php index 28c0aade..952413de 100644 --- a/app/Models/ResourceTypeItem/SimpleExpense.php +++ b/app/Models/ResourceTypeItem/SimpleExpense.php @@ -5,7 +5,7 @@ use App\Interfaces\ResourceTypeItem\IModel; use App\Request\Validate\Boolean; -use App\Utilities\Model as ModelUtility; +use App\Models\Clause; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder as QueryBuilder; @@ -62,13 +62,13 @@ public function totalCount( } } - $collection = ModelUtility::applySearch( + $collection = Clause::applySearch( $collection, $this->item_table, $search_parameters ); - $collection = ModelUtility::applyFiltering( + $collection = Clause::applyFiltering( $collection, $this->item_table, $filter_parameters @@ -179,13 +179,13 @@ public function paginatedCollection( } } - $collection = ModelUtility::applySearch( + $collection = Clause::applySearch( $collection, $this->item_table, $search_parameters ); - $collection = ModelUtility::applyFiltering( + $collection = Clause::applyFiltering( $collection, $this->item_table, $filter_parameters diff --git a/app/Models/ResourceTypeItem/SimpleItem.php b/app/Models/ResourceTypeItem/SimpleItem.php index 898a9b54..0db65f8b 100644 --- a/app/Models/ResourceTypeItem/SimpleItem.php +++ b/app/Models/ResourceTypeItem/SimpleItem.php @@ -4,7 +4,7 @@ namespace App\Models\ResourceTypeItem; use App\Interfaces\ResourceTypeItem\IModel; -use App\Utilities\Model as ModelUtility; +use App\Models\Clause; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder as QueryBuilder; @@ -46,13 +46,13 @@ public function totalCount( join('resource_type', 'resource.resource_type_id', 'resource_type.id')-> where('resource_type.id', '=', $resource_type_id); - $collection = ModelUtility::applySearch( + $collection = Clause::applySearch( $collection, $this->item_table, $search_parameters ); - $collection = ModelUtility::applyFiltering( + $collection = Clause::applyFiltering( $collection, $this->item_table, $filter_parameters @@ -102,13 +102,13 @@ public function paginatedCollection( join('resource_type', 'resource.resource_type_id', 'resource_type.id')-> where('resource_type.id', '=', $resource_type_id); - $collection = ModelUtility::applySearch( + $collection = Clause::applySearch( $collection, $this->item_table, $search_parameters ); - $collection = ModelUtility::applyFiltering( + $collection = Clause::applyFiltering( $collection, $this->item_table, $filter_parameters diff --git a/app/Models/ResourceTypeItem/Summary/AllocatedExpense.php b/app/Models/ResourceTypeItem/Summary/AllocatedExpense.php index 6531536a..9031732e 100644 --- a/app/Models/ResourceTypeItem/Summary/AllocatedExpense.php +++ b/app/Models/ResourceTypeItem/Summary/AllocatedExpense.php @@ -5,7 +5,7 @@ use App\Interfaces\ResourceTypeItem\ISummaryModelCategories; use App\Interfaces\ResourceTypeItem\ISummaryModel; -use App\Utilities\Model as ModelUtility; +use App\Models\Clause; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder as QueryBuilder; @@ -359,13 +359,13 @@ public function filteredSummary( $collection->whereRaw(DB::raw("MONTH({$this->sub_table}.effective_date) = {$month}")); } - $collection = ModelUtility::applySearch( + $collection = Clause::applySearch( $collection, $this->sub_table, $search_parameters ); - $collection = ModelUtility::applyFiltering( + $collection = Clause::applyFiltering( $collection, $this->sub_table, $filter_parameters diff --git a/app/Models/Subcategory.php b/app/Models/Subcategory.php index ca2b4692..e2442f24 100644 --- a/app/Models/Subcategory.php +++ b/app/Models/Subcategory.php @@ -3,7 +3,6 @@ namespace App\Models; -use App\Utilities\Model as ModelUtility; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Config; @@ -54,7 +53,7 @@ public function totalCount( where('sub_category.category_id', '=', $category_id)-> where('category.resource_type_id', '=', $resource_type_id); - $collection = ModelUtility::applySearch($collection, $this->table, $search_parameters); + $collection = Clause::applySearch($collection, $this->table, $search_parameters); return $collection->count(); } @@ -88,7 +87,7 @@ public function paginatedCollection( where('sub_category.category_id', '=', $category_id)-> where('category.resource_type_id', '=', $resource_type_id); - $collection = ModelUtility::applySearch($collection, $this->table, $search_parameters); + $collection = Clause::applySearch($collection, $this->table, $search_parameters); if (count($sort_parameters) > 0) { foreach ($sort_parameters as $field => $direction) { diff --git a/app/Models/Summary/Category.php b/app/Models/Summary/Category.php index 83b4fd62..f250dd8e 100644 --- a/app/Models/Summary/Category.php +++ b/app/Models/Summary/Category.php @@ -3,7 +3,7 @@ namespace App\Models\Summary; -use App\Utilities\Model as ModelUtility; +use App\Models\Clause; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Database\Eloquent\Model; @@ -38,13 +38,13 @@ public function total( join("resource_type", "category.resource_type_id", "resource_type.id")-> where('category.resource_type_id', '=', $resource_type_id); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, $include_public ); - $collection = ModelUtility::applySearch($collection, $this->table, $search_parameters); + $collection = Clause::applySearch($collection, $this->table, $search_parameters); return $collection->count(); } diff --git a/app/Models/Summary/Resource.php b/app/Models/Summary/Resource.php index cac45e54..c75eab6d 100644 --- a/app/Models/Summary/Resource.php +++ b/app/Models/Summary/Resource.php @@ -3,7 +3,7 @@ namespace App\Models\Summary; -use App\Utilities\Model as ModelUtility; +use App\Models\Clause; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder as QueryBuilder; @@ -40,13 +40,13 @@ public function totalCount( join('resource_type', 'resource.resource_type_id', 'resource_type.id')-> where('resource_type.id', '=', $resource_type_id); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, $include_public ); - $collection = ModelUtility::applySearch($collection, $this->table, $search_parameters); + $collection = Clause::applySearch($collection, $this->table, $search_parameters); return $collection->count(); } diff --git a/app/Models/Summary/ResourceType.php b/app/Models/Summary/ResourceType.php index cd375df5..4cca47d1 100644 --- a/app/Models/Summary/ResourceType.php +++ b/app/Models/Summary/ResourceType.php @@ -3,7 +3,7 @@ namespace App\Models\Summary; -use App\Utilities\Model as ModelUtility; +use App\Models\Clause; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Query\Builder as QueryBuilder; @@ -36,13 +36,13 @@ public function totalCount( { $collection = $this->select("resource_type.id"); - $collection = ModelUtility::applyResourceTypeCollectionCondition( + $collection = Clause::applyResourceTypeCollectionCondition( $collection, $permitted_resource_types, $include_public ); - $collection = ModelUtility::applySearch($collection, $this->table, $search_parameters); + $collection = Clause::applySearch($collection, $this->table, $search_parameters); return $collection->count(); } diff --git a/app/Models/Summary/Subcategory.php b/app/Models/Summary/Subcategory.php index 1fd5fc7c..b203ae9c 100644 --- a/app/Models/Summary/Subcategory.php +++ b/app/Models/Summary/Subcategory.php @@ -3,7 +3,7 @@ namespace App\Models\Summary; -use App\Utilities\Model as ModelUtility; +use App\Models\Clause; use Illuminate\Database\Query\Builder as QueryBuilder; use Illuminate\Database\Eloquent\Model; @@ -36,7 +36,7 @@ public function totalCount( where('sub_category.category_id', '=', $category_id)-> where('category.resource_type_id', '=', $resource_type_id); - $collection = ModelUtility::applySearch($collection, $this->table, $search_parameters); + $collection = Clause::applySearch($collection, $this->table, $search_parameters); return $collection->count(); } From daaaa04bdf826deffa40222fdc007a3f4f24d1d2 Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Sat, 27 Jun 2020 15:19:09 +0100 Subject: [PATCH 15/24] Splitting controllers - Splitting controllers, view and manage --- app/Http/Controllers/CategoryManage.php | 180 ++++++++++++++++++ ...ategoryController.php => CategoryView.php} | 165 +--------------- routes/api/private-routes.php | 6 +- routes/api/public-routes.php | 8 +- 4 files changed, 188 insertions(+), 171 deletions(-) create mode 100644 app/Http/Controllers/CategoryManage.php rename app/Http/Controllers/{CategoryController.php => CategoryView.php} (60%) diff --git a/app/Http/Controllers/CategoryManage.php b/app/Http/Controllers/CategoryManage.php new file mode 100644 index 00000000..2f716719 --- /dev/null +++ b/app/Http/Controllers/CategoryManage.php @@ -0,0 +1,180 @@ + + * @copyright Dean Blackborough 2018-2020 + * @license https://github.com/costs-to-expect/api/blob/master/LICENSE + */ +class CategoryManage extends Controller +{ + /** + * Create a new category + * + * @param $resource_type_id + * + * @return JsonResponse + */ + public function create($resource_type_id): JsonResponse + { + Route\Validate::resourceType( + (int) $resource_type_id, + $this->permitted_resource_types + ); + + $cache_control = new Cache\Control(Auth::user()->id); + $cache_key = new Cache\Key(); + + $validator = (new CategoryValidator)->create([ + 'resource_type_id' => $resource_type_id + ]); + \App\Request\BodyValidation::validateAndReturnErrors($validator); + + try { + $category = new Category([ + 'name' => request()->input('name'), + 'description' => request()->input('description'), + 'resource_type_id' => $resource_type_id + ]); + $category->save(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->categories($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->categories($resource_type_id) + ]); + } + } catch (Exception $e) { + \App\Response\Responses::failedToSaveModelForCreate(); + } + + return response()->json( + (new CategoryTransformer((new Category)->instanceToArray($category)))->asArray(), + 201 + ); + } + + /** + * Delete the requested category + * + * @param $resource_type_id + * @param $category_id + * + * @return JsonResponse + */ + public function delete( + $resource_type_id, + $category_id + ): JsonResponse + { + Route\Validate::category( + (int) $resource_type_id, + (int) $category_id, + $this->permitted_resource_types, + true + ); + + $cache_control = new Cache\Control(Auth::user()->id); + $cache_key = new Cache\Key(); + + try { + (new Category())->find($category_id)->delete(); + $cache_control->clearPrivateCacheKeys([ + $cache_key->categories($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->categories($resource_type_id) + ]); + } + + \App\Response\Responses::successNoContent(); + } catch (QueryException $e) { + \App\Response\Responses::foreignKeyConstraintError(); + } catch (Exception $e) { + \App\Response\Responses::notFound(trans('entities.category'), $e); + } + } + + /** + * Update the selected category + * + * @param $resource_type_id + * @param $category_id + * + * @return JsonResponse + */ + public function update($resource_type_id, $category_id): JsonResponse + { + Route\Validate::category( + (int) $resource_type_id, + (int) $category_id, + $this->permitted_resource_types, + true + ); + + $cache_control = new Cache\Control(Auth::user()->id); + $cache_key = new Cache\Key(); + + $category = (new Category())->instance($category_id); + + if ($category === null) { + \App\Response\Responses::failedToSelectModelForUpdateOrDelete(); + } + + \App\Request\BodyValidation::checkForEmptyPatch(); + + $validator = (new CategoryValidator)->update([ + 'resource_type_id' => (int)$category->resource_type_id, + 'category_id' => (int)$category_id + ]); + \App\Request\BodyValidation::validateAndReturnErrors($validator); + + \App\Request\BodyValidation::checkForInvalidFields( + array_merge( + (new Category())->patchableFields(), + (new CategoryValidator)->dynamicDefinedFields() + ) + ); + + foreach (request()->all() as $key => $value) { + $category->$key = $value; + } + + try { + $category->save(); + + $cache_control->clearPrivateCacheKeys([ + // We need to clear categories, resource type items + // and items due to includes so simpler to clear the entire + // resource type + $cache_key->resourceType($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->resourceType($resource_type_id) + ]); + } + } catch (Exception $e) { + \App\Response\Responses::failedToSaveModelForUpdate(); + } + + \App\Response\Responses::successNoContent(); + } +} diff --git a/app/Http/Controllers/CategoryController.php b/app/Http/Controllers/CategoryView.php similarity index 60% rename from app/Http/Controllers/CategoryController.php rename to app/Http/Controllers/CategoryView.php index f86e479b..510ab5bd 100644 --- a/app/Http/Controllers/CategoryController.php +++ b/app/Http/Controllers/CategoryView.php @@ -15,11 +15,7 @@ use App\Response\Pagination as UtilityPagination; use App\Models\Category; use App\Models\Transformers\Category as CategoryTransformer; -use App\Request\Validate\Category as CategoryValidator; -use Exception; -use Illuminate\Database\QueryException; use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Config; /** @@ -27,7 +23,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class CategoryController extends Controller +class CategoryView extends Controller { protected bool $allow_entire_collection = true; @@ -247,163 +243,4 @@ public function optionsShow($resource_type_id, $category_id): JsonResponse 200 ); } - - /** - * Create a new category - * - * @param $resource_type_id - * - * @return JsonResponse - */ - public function create($resource_type_id): JsonResponse - { - Route\Validate::resourceType( - (int) $resource_type_id, - $this->permitted_resource_types - ); - - $cache_control = new Cache\Control(Auth::user()->id); - $cache_key = new Cache\Key(); - - $validator = (new CategoryValidator)->create([ - 'resource_type_id' => $resource_type_id - ]); - \App\Request\BodyValidation::validateAndReturnErrors($validator); - - try { - $category = new Category([ - 'name' => request()->input('name'), - 'description' => request()->input('description'), - 'resource_type_id' => $resource_type_id - ]); - $category->save(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->categories($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->categories($resource_type_id) - ]); - } - } catch (Exception $e) { - \App\Response\Responses::failedToSaveModelForCreate(); - } - - return response()->json( - (new CategoryTransformer((new Category)->instanceToArray($category)))->asArray(), - 201 - ); - } - - /** - * Delete the requested category - * - * @param $resource_type_id - * @param $category_id - * - * @return JsonResponse - */ - public function delete( - $resource_type_id, - $category_id - ): JsonResponse - { - Route\Validate::category( - (int) $resource_type_id, - (int) $category_id, - $this->permitted_resource_types, - true - ); - - $cache_control = new Cache\Control(Auth::user()->id); - $cache_key = new Cache\Key(); - - try { - (new Category())->find($category_id)->delete(); - $cache_control->clearPrivateCacheKeys([ - $cache_key->categories($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->categories($resource_type_id) - ]); - } - - \App\Response\Responses::successNoContent(); - } catch (QueryException $e) { - \App\Response\Responses::foreignKeyConstraintError(); - } catch (Exception $e) { - \App\Response\Responses::notFound(trans('entities.category'), $e); - } - } - - /** - * Update the selected category - * - * @param $resource_type_id - * @param $category_id - * - * @return JsonResponse - */ - public function update($resource_type_id, $category_id): JsonResponse - { - Route\Validate::category( - (int) $resource_type_id, - (int) $category_id, - $this->permitted_resource_types, - true - ); - - $cache_control = new Cache\Control(Auth::user()->id); - $cache_key = new Cache\Key(); - - $category = (new Category())->instance($category_id); - - if ($category === null) { - \App\Response\Responses::failedToSelectModelForUpdateOrDelete(); - } - - \App\Request\BodyValidation::checkForEmptyPatch(); - - $validator = (new CategoryValidator)->update([ - 'resource_type_id' => (int)$category->resource_type_id, - 'category_id' => (int)$category_id - ]); - \App\Request\BodyValidation::validateAndReturnErrors($validator); - - \App\Request\BodyValidation::checkForInvalidFields( - array_merge( - (new Category())->patchableFields(), - (new CategoryValidator)->dynamicDefinedFields() - ) - ); - - foreach (request()->all() as $key => $value) { - $category->$key = $value; - } - - try { - $category->save(); - - $cache_control->clearPrivateCacheKeys([ - // We need to clear categories, resource type items - // and items due to includes so simpler to clear the entire - // resource type - $cache_key->resourceType($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->resourceType($resource_type_id) - ]); - } - } catch (Exception $e) { - \App\Response\Responses::failedToSaveModelForUpdate(); - } - - \App\Response\Responses::successNoContent(); - } } diff --git a/routes/api/private-routes.php b/routes/api/private-routes.php index 56757dc4..fb690f54 100644 --- a/routes/api/private-routes.php +++ b/routes/api/private-routes.php @@ -24,7 +24,7 @@ function () { Route::post( 'resource-types/{resource_type_id}/categories', - 'CategoryController@create' + 'CategoryManage@create' ); Route::post( @@ -69,7 +69,7 @@ function () { Route::delete( 'resource-types/{resource_type_id}/categories/{category_id}', - 'CategoryController@delete' + 'CategoryManage@delete' ); Route::delete( @@ -109,7 +109,7 @@ function () { Route::patch( 'resource-types/{resource_type_id}/categories/{category_id}', - 'CategoryController@update' + 'CategoryManage@update' ); Route::patch( diff --git a/routes/api/public-routes.php b/routes/api/public-routes.php index c1171088..a51e25de 100644 --- a/routes/api/public-routes.php +++ b/routes/api/public-routes.php @@ -76,22 +76,22 @@ function () { Route::get( 'resource-types/{resource_type_id}/categories', - 'CategoryController@index' + 'CategoryView@index' ); Route::options( 'resource-types/{resource_type_id}/categories', - 'CategoryController@optionsIndex' + 'CategoryView@optionsIndex' ); Route::get( 'resource-types/{resource_type_id}/categories/{category_id}', - 'CategoryController@show' + 'CategoryView@show' ); Route::options( 'resource-types/{resource_type_id}/categories/{category_id}', - 'CategoryController@optionsShow' + 'CategoryView@optionsShow' ); Route::get( From b114b102a69a4567b6302e47b83930500a6da628 Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Sat, 27 Jun 2020 15:54:03 +0100 Subject: [PATCH 16/24] *** Interim commit *** - Working on splitting controllers --- .../{IndexController.php => IndexView.php} | 4 +- app/Http/Controllers/ItemCategoryManage.php | 187 ++++++++++++++++++ ...oryController.php => ItemCategoryView.php} | 131 +----------- routes/api/public-routes.php | 8 +- 4 files changed, 193 insertions(+), 137 deletions(-) rename app/Http/Controllers/{IndexController.php => IndexView.php} (98%) create mode 100644 app/Http/Controllers/ItemCategoryManage.php rename app/Http/Controllers/{ItemCategoryController.php => ItemCategoryView.php} (66%) diff --git a/app/Http/Controllers/IndexController.php b/app/Http/Controllers/IndexView.php similarity index 98% rename from app/Http/Controllers/IndexController.php rename to app/Http/Controllers/IndexView.php index 244f8989..a335f5d1 100644 --- a/app/Http/Controllers/IndexController.php +++ b/app/Http/Controllers/IndexView.php @@ -9,13 +9,11 @@ use SplFileObject; /** - * Manage items - * * @author Dean Blackborough * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class IndexController extends Controller +class IndexView extends Controller { /** * Return all routes diff --git a/app/Http/Controllers/ItemCategoryManage.php b/app/Http/Controllers/ItemCategoryManage.php new file mode 100644 index 00000000..1b278192 --- /dev/null +++ b/app/Http/Controllers/ItemCategoryManage.php @@ -0,0 +1,187 @@ + + * @copyright Dean Blackborough 2018-2020 + * @license https://github.com/costs-to-expect/api/blob/master/LICENSE + */ +class ItemCategoryManage extends Controller +{ + /** + * Assign the category + * + * @param string $resource_type_id + * @param string $resource_id + * @param string $item_id + * + * @return JsonResponse + */ + public function create( + string $resource_type_id, + string $resource_id, + string $item_id + ): JsonResponse + { + Route\Validate::item( + $resource_type_id, + $resource_id, + $item_id, + $this->permitted_resource_types, + true + ); + + $cache_control = new Cache\Control(Auth::user()->id); + $cache_key = new Cache\Key(); + + $validator = (new ItemCategoryValidator)->create(); + \App\Request\BodyValidation::validateAndReturnErrors( + $validator, + $this->fieldsData($resource_type_id) + ); + + try { + $category_id = $this->hash->decode('category', request()->input('category_id')); + + if ($category_id === false) { + \App\Response\Responses::unableToDecode(); + } + + $item_category = new ItemCategory([ + 'item_id' => $item_id, + 'category_id' => $category_id + ]); + $item_category->save(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->items($resource_type_id, $resource_id), + $cache_key->resourceTypeItems($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->items($resource_type_id, $resource_id), + $cache_key->resourceTypeItems($resource_type_id) + ]); + } + } catch (Exception $e) { + \App\Response\Responses::failedToSaveModelForCreate(); + } + + return response()->json( + (new ItemCategoryTransformer((new ItemCategory())->instanceToArray($item_category)))->asArray(), + 201 + ); + } + + /** + * Generate any conditional POST parameters, will be merged with the relevant + * config/api/[type]/fields.php data array + * + * @param integer $resource_type_id + * + * @return array + */ + private function fieldsData($resource_type_id): array + { + $categories = (new Category())->categoriesByResourceType($resource_type_id); + + $conditional_post_parameters = ['category_id' => []]; + foreach ($categories as $category) { + $id = $this->hash->encode('category', $category['category_id']); + + if ($id === false) { + \App\Response\Responses::unableToDecode(); + } + + $conditional_post_parameters['category_id']['allowed_values'][$id] = [ + 'value' => $id, + 'name' => $category['category_name'], + 'description' => $category['category_description'] + ]; + } + + return $conditional_post_parameters; + } + + /** + * Delete the assigned category + * + * @param string $resource_type_id, + * @param string $resource_id, + * @param string $item_id, + * @param string $item_category_id + * + * @return JsonResponse + */ + public function delete( + string $resource_type_id, + string $resource_id, + string $item_id, + string $item_category_id + ): JsonResponse + { + Route\Validate::itemCategory( + $resource_type_id, + $resource_id, + $item_id, + $item_category_id, + $this->permitted_resource_types, + true + ); + + $cache_control = new Cache\Control(Auth::user()->id); + $cache_key = new Cache\Key(); + + $item_category = (new ItemCategory())->instance( + $resource_type_id, + $resource_id, + $item_id, + $item_category_id + ); + + if ($item_category === null) { + \App\Response\Responses::notFound(trans('entities.item-category')); + } + + try { + (new ItemCategory())->find($item_category_id)->delete(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->items($resource_type_id, $resource_id), + $cache_key->resourceTypeItems($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->items($resource_type_id, $resource_id), + $cache_key->resourceTypeItems($resource_type_id) + ]); + } + + \App\Response\Responses::successNoContent(); + } catch (QueryException $e) { + \App\Response\Responses::foreignKeyConstraintError(); + } catch (Exception $e) { + \App\Response\Responses::notFound(trans('entities.item-category'), $e); + } + } +} diff --git a/app/Http/Controllers/ItemCategoryController.php b/app/Http/Controllers/ItemCategoryView.php similarity index 66% rename from app/Http/Controllers/ItemCategoryController.php rename to app/Http/Controllers/ItemCategoryView.php index 19240dfb..4c4253b7 100644 --- a/app/Http/Controllers/ItemCategoryController.php +++ b/app/Http/Controllers/ItemCategoryView.php @@ -24,7 +24,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class ItemCategoryController extends Controller +class ItemCategoryManage extends Controller { /** * Return the category assigned to an item @@ -234,72 +234,6 @@ public function optionsShow( ); } - /** - * Assign the category - * - * @param string $resource_type_id - * @param string $resource_id - * @param string $item_id - * - * @return JsonResponse - */ - public function create( - string $resource_type_id, - string $resource_id, - string $item_id - ): JsonResponse - { - Route\Validate::item( - $resource_type_id, - $resource_id, - $item_id, - $this->permitted_resource_types, - true - ); - - $cache_control = new Cache\Control(Auth::user()->id); - $cache_key = new Cache\Key(); - - $validator = (new ItemCategoryValidator)->create(); - \App\Request\BodyValidation::validateAndReturnErrors( - $validator, - $this->fieldsData($resource_type_id) - ); - - try { - $category_id = $this->hash->decode('category', request()->input('category_id')); - - if ($category_id === false) { - \App\Response\Responses::unableToDecode(); - } - - $item_category = new ItemCategory([ - 'item_id' => $item_id, - 'category_id' => $category_id - ]); - $item_category->save(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->items($resource_type_id, $resource_id), - $cache_key->resourceTypeItems($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->items($resource_type_id, $resource_id), - $cache_key->resourceTypeItems($resource_type_id) - ]); - } - } catch (Exception $e) { - \App\Response\Responses::failedToSaveModelForCreate(); - } - - return response()->json( - (new ItemCategoryTransformer((new ItemCategory())->instanceToArray($item_category)))->asArray(), - 201 - ); - } - /** * Generate any conditional POST parameters, will be merged with the relevant * config/api/[type]/fields.php data array @@ -329,67 +263,4 @@ private function fieldsData($resource_type_id): array return $conditional_post_parameters; } - - /** - * Delete the assigned category - * - * @param string $resource_type_id, - * @param string $resource_id, - * @param string $item_id, - * @param string $item_category_id - * - * @return JsonResponse - */ - public function delete( - string $resource_type_id, - string $resource_id, - string $item_id, - string $item_category_id - ): JsonResponse - { - Route\Validate::itemCategory( - $resource_type_id, - $resource_id, - $item_id, - $item_category_id, - $this->permitted_resource_types, - true - ); - - $cache_control = new Cache\Control(Auth::user()->id); - $cache_key = new Cache\Key(); - - $item_category = (new ItemCategory())->instance( - $resource_type_id, - $resource_id, - $item_id, - $item_category_id - ); - - if ($item_category === null) { - \App\Response\Responses::notFound(trans('entities.item-category')); - } - - try { - (new ItemCategory())->find($item_category_id)->delete(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->items($resource_type_id, $resource_id), - $cache_key->resourceTypeItems($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->items($resource_type_id, $resource_id), - $cache_key->resourceTypeItems($resource_type_id) - ]); - } - - \App\Response\Responses::successNoContent(); - } catch (QueryException $e) { - \App\Response\Responses::foreignKeyConstraintError(); - } catch (Exception $e) { - \App\Response\Responses::notFound(trans('entities.item-category'), $e); - } - } } diff --git a/routes/api/public-routes.php b/routes/api/public-routes.php index a51e25de..6dfb2371 100644 --- a/routes/api/public-routes.php +++ b/routes/api/public-routes.php @@ -16,22 +16,22 @@ function () { // Root of the API and CHANGELOG Route::get( '', - 'IndexController@index' + 'IndexView@index' ); Route::options( '', - 'IndexController@optionsIndex' + 'IndexView@optionsIndex' ); Route::get( 'changelog', - 'IndexController@changeLog' + 'IndexView@changeLog' ); Route::options( 'changelog', - 'IndexController@optionsChangeLog' + 'IndexView@optionsChangeLog' ); Route::get( From 26da09d3987bf2b8edba878bbe5ea13d3e7b54b7 Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Tue, 30 Jun 2020 23:24:41 +0100 Subject: [PATCH 17/24] Refactoring - Split item caegory controller --- app/Http/Controllers/ItemCategoryManage.php | 4 ---- app/Http/Controllers/ItemCategoryView.php | 6 +----- routes/api/private-routes.php | 4 ++-- routes/api/public-routes.php | 8 ++++---- 4 files changed, 7 insertions(+), 15 deletions(-) diff --git a/app/Http/Controllers/ItemCategoryManage.php b/app/Http/Controllers/ItemCategoryManage.php index 1b278192..0b13d5b2 100644 --- a/app/Http/Controllers/ItemCategoryManage.php +++ b/app/Http/Controllers/ItemCategoryManage.php @@ -2,11 +2,7 @@ namespace App\Http\Controllers; -use App\Option\Delete; -use App\Option\Get; -use App\Option\Post; use App\Response\Cache; -use App\Response\Header\Header; use App\Request\Route; use App\Models\Category; use App\Models\ItemCategory; diff --git a/app/Http/Controllers/ItemCategoryView.php b/app/Http/Controllers/ItemCategoryView.php index 4c4253b7..389dd54b 100644 --- a/app/Http/Controllers/ItemCategoryView.php +++ b/app/Http/Controllers/ItemCategoryView.php @@ -11,11 +11,7 @@ use App\Models\Category; use App\Models\ItemCategory; use App\Models\Transformers\ItemCategory as ItemCategoryTransformer; -use App\Request\Validate\ItemCategory as ItemCategoryValidator; -use Exception; -use Illuminate\Database\QueryException; use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\Auth; /** * Manage the category for an item row @@ -24,7 +20,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class ItemCategoryManage extends Controller +class ItemCategoryView extends Controller { /** * Return the category assigned to an item diff --git a/routes/api/private-routes.php b/routes/api/private-routes.php index fb690f54..9f06813b 100644 --- a/routes/api/private-routes.php +++ b/routes/api/private-routes.php @@ -44,7 +44,7 @@ function () { Route::post( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/categories', - 'ItemCategoryController@create' + 'ItemCategoryManage@create' ); Route::post( @@ -94,7 +94,7 @@ function () { Route::delete( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/categories/{item_category_id}', - 'ItemCategoryController@delete' + 'ItemCategoryManage@delete' ); Route::delete( diff --git a/routes/api/public-routes.php b/routes/api/public-routes.php index 6dfb2371..65ca029b 100644 --- a/routes/api/public-routes.php +++ b/routes/api/public-routes.php @@ -207,25 +207,25 @@ function () { /*This route needs to be removed*/ Route::get( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/categories', - 'ItemCategoryController@index' + 'ItemCategoryView@index' ); /*This route needs to be removed*/ Route::options( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/categories', - 'ItemCategoryController@optionsIndex' + 'ItemCategoryView@optionsIndex' ); /*This route needs to be removed*/ Route::get( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/categories/{item_category_id}', - 'ItemCategoryController@show' + 'ItemCategoryView@show' ); /*This route needs to be removed*/ Route::options( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/categories/{item_category_id}', - 'ItemCategoryController@optionsShow' + 'ItemCategoryView@optionsShow' ); /*This route needs to be removed*/ From a2d2abeaf66b88bbd48c36e6426a0c9debdd4577 Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Tue, 30 Jun 2020 23:33:15 +0100 Subject: [PATCH 18/24] Refactoring - Split item partial transfer controller and item controller --- app/Http/Controllers/ItemManage.php | 223 ++++++++++++++++++ .../Controllers/ItemPartialTransferManage.php | 156 ++++++++++++ ...roller.php => ItemPartialTransferView.php} | 127 +--------- .../{ItemController.php => ItemView.php} | 207 +--------------- routes/api/private-routes.php | 10 +- routes/api/public-routes.php | 18 +- 6 files changed, 395 insertions(+), 346 deletions(-) create mode 100644 app/Http/Controllers/ItemManage.php create mode 100644 app/Http/Controllers/ItemPartialTransferManage.php rename app/Http/Controllers/{ItemPartialTransferController.php => ItemPartialTransferView.php} (67%) rename app/Http/Controllers/{ItemController.php => ItemView.php} (68%) diff --git a/app/Http/Controllers/ItemManage.php b/app/Http/Controllers/ItemManage.php new file mode 100644 index 00000000..248f38aa --- /dev/null +++ b/app/Http/Controllers/ItemManage.php @@ -0,0 +1,223 @@ + + * @copyright Dean Blackborough 2018-2020 + * @license https://github.com/costs-to-expect/api/blob/master/LICENSE + */ +class ItemManage extends Controller +{ + /** + * Create a new item + * + * @param string $resource_type_id + * @param string $resource_id + * + * @return JsonResponse + */ + public function create( + string $resource_type_id, + string $resource_id + ): JsonResponse + { + Route\Validate::resource( + $resource_type_id, + $resource_id, + $this->permitted_resource_types, + true + ); + + $user_id = Auth::user()->id; + + $cache_control = new Cache\Control($user_id); + $cache_key = new Cache\Key(); + + $item_interface = Factory::item($resource_type_id); + + $validator_factory = $item_interface->validator(); + $validator = $validator_factory->create(); + \App\Request\BodyValidation::validateAndReturnErrors($validator); + + $model = $item_interface->model(); + + try { + $item = new Item([ + 'resource_id' => $resource_id, + 'created_by' => $user_id + ]); + $item->save(); + + $item_type = $item_interface->create((int) $item->id); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->resourceTypeItems($resource_type_id), + $cache_key->items($resource_type_id, $resource_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->resourceTypeItems($resource_type_id), + $cache_key->items($resource_type_id, $resource_id) + ]); + } + + } catch (Exception $e) { + \App\Response\Responses::failedToSaveModelForCreate(); + } + + return response()->json( + $item_interface->transformer($model->instanceToArray($item, $item_type))->asArray(), + 201 + ); + } + + /** + * Update the selected item + * + * @param string $resource_type_id + * @param string $resource_id + * @param string $item_id + * + * @return JsonResponse + */ + public function update( + string $resource_type_id, + string $resource_id, + string $item_id + ): JsonResponse + { + Route\Validate::item( + $resource_type_id, + $resource_id, + $item_id, + $this->permitted_resource_types, + true + ); + + $user_id = Auth::user()->id; + + $cache_control = new Cache\Control($user_id); + $cache_key = new Cache\Key(); + + $item_interface = Factory::item($resource_type_id); + + \App\Request\BodyValidation::checkForEmptyPatch(); + + \App\Request\BodyValidation::checkForInvalidFields($item_interface->validationPatchableFieldNames()); + + $validator_factory = $item_interface->validator(); + $validator = $validator_factory->update(); + \App\Request\BodyValidation::validateAndReturnErrors($validator); + + $item = (new Item())->instance($resource_type_id, $resource_id, $item_id); + $item_type = $item_interface->instance((int) $item_id); + + if ($item === null || $item_type === null) { + \App\Response\Responses::failedToSelectModelForUpdateOrDelete(); + } + + try { + $item->updated_by = $user_id; + + if ($item->save() === true) { + $item_interface->update(request()->all(), $item_type); + } + + $cache_control->clearPrivateCacheKeys([ + $cache_key->resourceTypeItems($resource_type_id), + $cache_key->items($resource_type_id, $resource_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->resourceTypeItems($resource_type_id), + $cache_key->items($resource_type_id, $resource_id) + ]); + } + } catch (Exception $e) { + \App\Response\Responses::failedToSaveModelForUpdate(); + } + + return \App\Response\Responses::successNoContent(); + } + + /** + * Delete the assigned item + * + * @param string $resource_type_id, + * @param string $resource_id, + * @param string $item_id + * + * @return JsonResponse + */ + public function delete( + string $resource_type_id, + string $resource_id, + string $item_id + ): JsonResponse + { + Route\Validate::resource( + $resource_type_id, + $resource_id, + $this->permitted_resource_types, + true + ); + + $cache_control = new Cache\Control(Auth::user()->id); + $cache_key = new Cache\Key(); + + $item_interface = Factory::item($resource_type_id); + + $item_model = $item_interface->model(); + + $item_type = $item_model->instance($item_id); + $item = (new Item())->instance($resource_type_id, $resource_id, $item_id); + + if ($item === null || $item_type === null) { + \App\Response\Responses::notFound(trans('entities.item')); + } + + if (in_array($item_interface->type(), ['allocated-expense', 'simple-expense']) && + $item_model->hasCategoryAssignments($item_id) === true) { + \App\Response\Responses::foreignKeyConstraintError(); + } + + try { + (new ItemTransfer())->deleteTransfers($item_id); + $item_type->delete(); + $item->delete(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->resourceTypeItems($resource_type_id), + $cache_key->items($resource_type_id, $resource_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->resourceTypeItems($resource_type_id), + $cache_key->items($resource_type_id, $resource_id) + ]); + } + + \App\Response\Responses::successNoContent(); + } catch (QueryException $e) { + \App\Response\Responses::foreignKeyConstraintError(); + } catch (Exception $e) { + \App\Response\Responses::notFound(trans('entities.item'), $e); + } + } +} diff --git a/app/Http/Controllers/ItemPartialTransferManage.php b/app/Http/Controllers/ItemPartialTransferManage.php new file mode 100644 index 00000000..9a9111bb --- /dev/null +++ b/app/Http/Controllers/ItemPartialTransferManage.php @@ -0,0 +1,156 @@ + + * @copyright Dean Blackborough 2018-2020 + * @license https://github.com/costs-to-expect/api/blob/master/LICENSE + */ +class ItemPartialTransferManage extends Controller +{ + /** + * Delete the requested partial transfer + * + * @param $resource_type_id + * @param $item_partial_transfer_id + * + * @return JsonResponse + */ + public function delete( + $resource_type_id, + $item_partial_transfer_id + ): JsonResponse + { + Route\Validate::resourceType( + (int) $resource_type_id, + $this->permitted_resource_types, + true + ); + + $user_id = Auth::user()->id; + + $cache_control = new Cache\Control($user_id); + $cache_key = new Cache\Key(); + + try { + $partial_transfer = (new ItemPartialTransfer())->find($item_partial_transfer_id); + + if ($partial_transfer !== null) { + $partial_transfer->delete(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->partialTransfers($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->partialTransfers($resource_type_id) + ]); + } + + return \App\Response\Responses::successNoContent(); + } + + return \App\Response\Responses::failedToSelectModelForUpdateOrDelete(); + } catch (QueryException $e) { + return \App\Response\Responses::foreignKeyConstraintError(); + } catch (Exception $e) { + return \App\Response\Responses::notFound(trans('entities.item-partial-transfer'), $e); + } + } + + public function transfer( + string $resource_type_id, + string $resource_id, + string $item_id + ): JsonResponse + { + Route\Validate::item( + $resource_type_id, + $resource_id, + $item_id, + $this->permitted_resource_types, + true + ); + + $user_id = Auth::user()->id; + + $cache_control = new Cache\Control($user_id); + $cache_key = new Cache\Key(); + + $validator = (new ItemPartialTransferValidator)->create( + [ + 'resource_type_id' => $resource_type_id, + 'existing_resource_id' => $resource_id + ] + ); + \App\Request\BodyValidation::validateAndReturnErrors($validator); + + $new_resource_id = $this->hash->decode('resource', request()->input('resource_id')); + + if ($new_resource_id === false) { + \App\Response\Responses::unableToDecode(); + } + + try { + $partial_transfer = new ItemPartialTransfer([ + 'resource_type_id' => $resource_type_id, + 'from' => (int) $resource_id, + 'to' => $new_resource_id, + 'item_id' => $item_id, + 'percentage' => request()->input('percentage'), + 'transferred_by' => $user_id + ]); + $partial_transfer->save(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->partialTransfers($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->partialTransfers($resource_type_id) + ]); + } + } catch (QueryException $e) { + return \App\Response\Responses::foreignKeyConstraintError(); + } catch (Exception $e) { + return \App\Response\Responses::failedToSaveModelForCreate(); + } + + $item_partial_transfer = (new ItemPartialTransfer())->single( + (int) $resource_type_id, + (int) $partial_transfer->id + ); + + if ($item_partial_transfer === null) { + return \App\Response\Responses::notFound(trans('entities.item_partial_transfer')); + } + + return response()->json( + (new ItemPartialTransferTransformer($item_partial_transfer))->asArray(), + 201 + ); + } +} diff --git a/app/Http/Controllers/ItemPartialTransferController.php b/app/Http/Controllers/ItemPartialTransferView.php similarity index 67% rename from app/Http/Controllers/ItemPartialTransferController.php rename to app/Http/Controllers/ItemPartialTransferView.php index 60b44d09..e9480a7d 100644 --- a/app/Http/Controllers/ItemPartialTransferController.php +++ b/app/Http/Controllers/ItemPartialTransferView.php @@ -27,7 +27,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class ItemPartialTransferController extends Controller +class ItemPartialTransferView extends Controller { /** * Return the categories collection @@ -95,57 +95,6 @@ static function ($transfer) { return response()->json($cache_collection->collection(), 200, $cache_collection->headers()); } - /** - * Delete the requested partial transfer - * - * @param $resource_type_id - * @param $item_partial_transfer_id - * - * @return JsonResponse - */ - public function delete( - $resource_type_id, - $item_partial_transfer_id - ): JsonResponse - { - Route\Validate::resourceType( - (int) $resource_type_id, - $this->permitted_resource_types, - true - ); - - $user_id = Auth::user()->id; - - $cache_control = new Cache\Control($user_id); - $cache_key = new Cache\Key(); - - try { - $partial_transfer = (new ItemPartialTransfer())->find($item_partial_transfer_id); - - if ($partial_transfer !== null) { - $partial_transfer->delete(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->partialTransfers($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->partialTransfers($resource_type_id) - ]); - } - - return \App\Response\Responses::successNoContent(); - } - - return \App\Response\Responses::failedToSelectModelForUpdateOrDelete(); - } catch (QueryException $e) { - return \App\Response\Responses::foreignKeyConstraintError(); - } catch (Exception $e) { - return \App\Response\Responses::notFound(trans('entities.item-partial-transfer'), $e); - } - } - /** * Return a single item partial transfer * @@ -183,80 +132,6 @@ public function show( ); } - public function transfer( - string $resource_type_id, - string $resource_id, - string $item_id - ): JsonResponse - { - Route\Validate::item( - $resource_type_id, - $resource_id, - $item_id, - $this->permitted_resource_types, - true - ); - - $user_id = Auth::user()->id; - - $cache_control = new Cache\Control($user_id); - $cache_key = new Cache\Key(); - - $validator = (new ItemPartialTransferValidator)->create( - [ - 'resource_type_id' => $resource_type_id, - 'existing_resource_id' => $resource_id - ] - ); - \App\Request\BodyValidation::validateAndReturnErrors($validator); - - $new_resource_id = $this->hash->decode('resource', request()->input('resource_id')); - - if ($new_resource_id === false) { - \App\Response\Responses::unableToDecode(); - } - - try { - $partial_transfer = new ItemPartialTransfer([ - 'resource_type_id' => $resource_type_id, - 'from' => (int) $resource_id, - 'to' => $new_resource_id, - 'item_id' => $item_id, - 'percentage' => request()->input('percentage'), - 'transferred_by' => $user_id - ]); - $partial_transfer->save(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->partialTransfers($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->partialTransfers($resource_type_id) - ]); - } - } catch (QueryException $e) { - return \App\Response\Responses::foreignKeyConstraintError(); - } catch (Exception $e) { - return \App\Response\Responses::failedToSaveModelForCreate(); - } - - $item_partial_transfer = (new ItemPartialTransfer())->single( - (int) $resource_type_id, - (int) $partial_transfer->id - ); - - if ($item_partial_transfer === null) { - return \App\Response\Responses::notFound(trans('entities.item_partial_transfer')); - } - - return response()->json( - (new ItemPartialTransferTransformer($item_partial_transfer))->asArray(), - 201 - ); - } - /** * Generate the OPTIONS request for the partial transfers collection * diff --git a/app/Http/Controllers/ItemController.php b/app/Http/Controllers/ItemView.php similarity index 68% rename from app/Http/Controllers/ItemController.php rename to app/Http/Controllers/ItemView.php index 67d4fa98..86da13a9 100644 --- a/app/Http/Controllers/ItemController.php +++ b/app/Http/Controllers/ItemView.php @@ -3,7 +3,6 @@ namespace App\Http\Controllers; use App\Item\Factory; -use App\Models\ItemTransfer; use App\Option\Delete; use App\Option\Get; use App\Option\Patch; @@ -13,14 +12,10 @@ use App\Request\Parameter; use App\Request\Route; use App\Models\Category; -use App\Models\Item; use App\Models\Subcategory; use App\Response\Header\Headers; use App\Response\Pagination as UtilityPagination; -use Exception; -use Illuminate\Database\QueryException; use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\Auth; /** * Manage items @@ -29,7 +24,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class ItemController extends Controller +class ItemView extends Controller { /** * Return all the items for the resource type and resource applying @@ -313,206 +308,6 @@ public function optionsShow( ); } - /** - * Create a new item - * - * @param string $resource_type_id - * @param string $resource_id - * - * @return JsonResponse - */ - public function create( - string $resource_type_id, - string $resource_id - ): JsonResponse - { - Route\Validate::resource( - $resource_type_id, - $resource_id, - $this->permitted_resource_types, - true - ); - - $user_id = Auth::user()->id; - - $cache_control = new Cache\Control($user_id); - $cache_key = new Cache\Key(); - - $item_interface = Factory::item($resource_type_id); - - $validator_factory = $item_interface->validator(); - $validator = $validator_factory->create(); - \App\Request\BodyValidation::validateAndReturnErrors($validator); - - $model = $item_interface->model(); - - try { - $item = new Item([ - 'resource_id' => $resource_id, - 'created_by' => $user_id - ]); - $item->save(); - - $item_type = $item_interface->create((int) $item->id); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->resourceTypeItems($resource_type_id), - $cache_key->items($resource_type_id, $resource_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->resourceTypeItems($resource_type_id), - $cache_key->items($resource_type_id, $resource_id) - ]); - } - - } catch (Exception $e) { - \App\Response\Responses::failedToSaveModelForCreate(); - } - - return response()->json( - $item_interface->transformer($model->instanceToArray($item, $item_type))->asArray(), - 201 - ); - } - - /** - * Update the selected item - * - * @param string $resource_type_id - * @param string $resource_id - * @param string $item_id - * - * @return JsonResponse - */ - public function update( - string $resource_type_id, - string $resource_id, - string $item_id - ): JsonResponse - { - Route\Validate::item( - $resource_type_id, - $resource_id, - $item_id, - $this->permitted_resource_types, - true - ); - - $user_id = Auth::user()->id; - - $cache_control = new Cache\Control($user_id); - $cache_key = new Cache\Key(); - - $item_interface = Factory::item($resource_type_id); - - \App\Request\BodyValidation::checkForEmptyPatch(); - - \App\Request\BodyValidation::checkForInvalidFields($item_interface->validationPatchableFieldNames()); - - $validator_factory = $item_interface->validator(); - $validator = $validator_factory->update(); - \App\Request\BodyValidation::validateAndReturnErrors($validator); - - $item = (new Item())->instance($resource_type_id, $resource_id, $item_id); - $item_type = $item_interface->instance((int) $item_id); - - if ($item === null || $item_type === null) { - \App\Response\Responses::failedToSelectModelForUpdateOrDelete(); - } - - try { - $item->updated_by = $user_id; - - if ($item->save() === true) { - $item_interface->update(request()->all(), $item_type); - } - - $cache_control->clearPrivateCacheKeys([ - $cache_key->resourceTypeItems($resource_type_id), - $cache_key->items($resource_type_id, $resource_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->resourceTypeItems($resource_type_id), - $cache_key->items($resource_type_id, $resource_id) - ]); - } - } catch (Exception $e) { - \App\Response\Responses::failedToSaveModelForUpdate(); - } - - return \App\Response\Responses::successNoContent(); - } - - /** - * Delete the assigned item - * - * @param string $resource_type_id, - * @param string $resource_id, - * @param string $item_id - * - * @return JsonResponse - */ - public function delete( - string $resource_type_id, - string $resource_id, - string $item_id - ): JsonResponse - { - Route\Validate::resource( - $resource_type_id, - $resource_id, - $this->permitted_resource_types, - true - ); - - $cache_control = new Cache\Control(Auth::user()->id); - $cache_key = new Cache\Key(); - - $item_interface = Factory::item($resource_type_id); - - $item_model = $item_interface->model(); - - $item_type = $item_model->instance($item_id); - $item = (new Item())->instance($resource_type_id, $resource_id, $item_id); - - if ($item === null || $item_type === null) { - \App\Response\Responses::notFound(trans('entities.item')); - } - - if (in_array($item_interface->type(), ['allocated-expense', 'simple-expense']) && - $item_model->hasCategoryAssignments($item_id) === true) { - \App\Response\Responses::foreignKeyConstraintError(); - } - - try { - (new ItemTransfer())->deleteTransfers($item_id); - $item_type->delete(); - $item->delete(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->resourceTypeItems($resource_type_id), - $cache_key->items($resource_type_id, $resource_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->resourceTypeItems($resource_type_id), - $cache_key->items($resource_type_id, $resource_id) - ]); - } - - \App\Response\Responses::successNoContent(); - } catch (QueryException $e) { - \App\Response\Responses::foreignKeyConstraintError(); - } catch (Exception $e) { - \App\Response\Responses::notFound(trans('entities.item'), $e); - } - } - /** * Set the allowed values for any conditional parameters, these will be * merged with the data arrays defined in config/api/[item-type]/parameters.php diff --git a/routes/api/private-routes.php b/routes/api/private-routes.php index 9f06813b..9f703df5 100644 --- a/routes/api/private-routes.php +++ b/routes/api/private-routes.php @@ -39,7 +39,7 @@ function () { Route::post( 'resource-types/{resource_type_id}/resources/{resource_id}/items', - 'ItemController@create' + 'ItemManage@create' ); Route::post( @@ -54,7 +54,7 @@ function () { Route::post( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/partial-transfer', - 'ItemPartialTransferController@transfer' + 'ItemPartialTransferManage@transfer' ); Route::post( @@ -79,7 +79,7 @@ function () { Route::delete( 'resource-types/{resource_type_id}/partial-transfers/{item_partial_transfer_id}', - 'ItemPartialTransferController@delete' + 'ItemPartialTransferManage@delete' ); Route::delete( @@ -89,7 +89,7 @@ function () { Route::delete( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}', - 'ItemController@delete' + 'ItemManage@delete' ); Route::delete( @@ -124,7 +124,7 @@ function () { Route::patch( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}', - 'ItemController@update' + 'ItemManage@update' ); } ); diff --git a/routes/api/public-routes.php b/routes/api/public-routes.php index 65ca029b..c7326bca 100644 --- a/routes/api/public-routes.php +++ b/routes/api/public-routes.php @@ -126,22 +126,22 @@ function () { Route::get( 'resource-types/{resource_type_id}/partial-transfers', - 'ItemPartialTransferController@index' + 'ItemPartialTransferView@index' ); Route::options( 'resource-types/{resource_type_id}/partial-transfers', - 'ItemPartialTransferController@optionsIndex' + 'ItemPartialTransferView@optionsIndex' ); Route::get( 'resource-types/{resource_type_id}/partial-transfers/{item_partial_transfer_id}', - 'ItemPartialTransferController@show' + 'ItemPartialTransferView@show' ); Route::options( 'resource-types/{resource_type_id}/partial-transfers/{item_partial_transfer_id}', - 'ItemPartialTransferController@optionsShow' + 'ItemPartialTransferView@optionsShow' ); Route::get( @@ -176,27 +176,27 @@ function () { Route::get( 'resource-types/{resource_type_id}/resources/{resource_id}/items', - 'ItemController@index' + 'ItemView@index' ); Route::options( 'resource-types/{resource_type_id}/resources/{resource_id}/items', - 'ItemController@optionsIndex' + 'ItemView@optionsIndex' ); Route::get( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}', - 'ItemController@show' + 'ItemView@show' ); Route::options( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}', - 'ItemController@optionsShow' + 'ItemView@optionsShow' ); Route::options( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/partial-transfer', - 'ItemPartialTransferController@optionsTransfer' + 'ItemPartialTransferView@optionsTransfer' ); Route::options( From c07fa1b1481dcd6fe88b9f2f0369eaa172e2213e Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Tue, 30 Jun 2020 23:45:11 +0100 Subject: [PATCH 19/24] Refactoring - Split controllers --- .../Controllers/ItemPartialTransferManage.php | 8 - .../Controllers/ItemPartialTransferView.php | 4 - .../Controllers/ItemSubcategoryManage.php | 205 ++++++++++++++++++ ...Controller.php => ItemSubcategoryView.php} | 152 +------------ app/Http/Controllers/ItemTransferManage.php | 92 ++++++++ ...ferController.php => ItemTransferView.php} | 76 +------ ...temTypeController.php => ItemTypeView.php} | 2 +- ...assportController.php => PassportView.php} | 2 +- routes/api/auth.php | 8 +- routes/api/private-routes.php | 8 +- routes/api/public-routes.php | 26 +-- 11 files changed, 322 insertions(+), 261 deletions(-) create mode 100644 app/Http/Controllers/ItemSubcategoryManage.php rename app/Http/Controllers/{ItemSubcategoryController.php => ItemSubcategoryView.php} (64%) create mode 100644 app/Http/Controllers/ItemTransferManage.php rename app/Http/Controllers/{ItemTransferController.php => ItemTransferView.php} (75%) rename app/Http/Controllers/{ItemTypeController.php => ItemTypeView.php} (99%) rename app/Http/Controllers/{PassportController.php => PassportView.php} (98%) diff --git a/app/Http/Controllers/ItemPartialTransferManage.php b/app/Http/Controllers/ItemPartialTransferManage.php index 9a9111bb..048303ea 100644 --- a/app/Http/Controllers/ItemPartialTransferManage.php +++ b/app/Http/Controllers/ItemPartialTransferManage.php @@ -3,22 +3,14 @@ namespace App\Http\Controllers; use App\Models\ItemPartialTransfer; -use App\Models\Resource; use App\Models\Transformers\ItemPartialTransfer as ItemPartialTransferTransformer; -use App\Option\Delete; -use App\Option\Get; -use App\Option\Post; use App\Response\Cache; -use App\Response\Header\Headers; -use App\Request\Parameter; use App\Request\Route; -use App\Response\Pagination as UtilityPagination; use App\Request\Validate\ItemPartialTransfer as ItemPartialTransferValidator; use Exception; use Illuminate\Database\QueryException; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Auth; -use Illuminate\Support\Facades\Config; /** * Partial transfer of items diff --git a/app/Http/Controllers/ItemPartialTransferView.php b/app/Http/Controllers/ItemPartialTransferView.php index e9480a7d..a20791ad 100644 --- a/app/Http/Controllers/ItemPartialTransferView.php +++ b/app/Http/Controllers/ItemPartialTransferView.php @@ -13,11 +13,7 @@ use App\Request\Parameter; use App\Request\Route; use App\Response\Pagination as UtilityPagination; -use App\Request\Validate\ItemPartialTransfer as ItemPartialTransferValidator; -use Exception; -use Illuminate\Database\QueryException; use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Config; /** diff --git a/app/Http/Controllers/ItemSubcategoryManage.php b/app/Http/Controllers/ItemSubcategoryManage.php new file mode 100644 index 00000000..2bc3005a --- /dev/null +++ b/app/Http/Controllers/ItemSubcategoryManage.php @@ -0,0 +1,205 @@ + + * @copyright Dean Blackborough 2018-2020 + * @license https://github.com/costs-to-expect/api/blob/master/LICENSE + */ +class ItemSubcategoryManage extends Controller +{ + /** + * Assign the sub category + * + * @param string $resource_type_id + * @param string $resource_id + * @param string $item_id + * @param string $item_category_id + * + * @return JsonResponse + */ + public function create( + string $resource_type_id, + string $resource_id, + string $item_id, + string $item_category_id + ): JsonResponse + { + Route\Validate::item( + $resource_type_id, + $resource_id, + $item_id, + $this->permitted_resource_types, + true + ); + + $cache_control = new Cache\Control(Auth::user()->id); + $cache_key = new Cache\Key(); + + if ($item_category_id === 'nill') { + \App\Response\Responses::notFound(trans('entities.item-subcategory')); + } + + $item_category = (new ItemCategory()) + ->where('item_id', '=', $item_id) + ->find($item_category_id); + + $validator = (new ItemSubcategoryValidator)->create(['category_id' => $item_category->category_id]); + \App\Request\BodyValidation::validateAndReturnErrors( + $validator, + $this->fieldsData($item_category_id) + ); + + try { + $subcategory_id = $this->hash->decode('subcategory', request()->input('subcategory_id')); + + if ($subcategory_id === false) { + \App\Response\Responses::unableToDecode(); + } + + $item_sub_category = new ItemSubcategory([ + 'item_category_id' => $item_category_id, + 'sub_category_id' => $subcategory_id + ]); + $item_sub_category->save(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->items($resource_type_id, $resource_id), + $cache_key->resourceTypeItems($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->items($resource_type_id, $resource_id), + $cache_key->resourceTypeItems($resource_type_id) + ]); + } + } catch (Exception $e) { + \App\Response\Responses::failedToSaveModelForCreate(); + } + + return response()->json( + (new ItemSubcategoryTransformer((new ItemSubcategory())->instanceToArray($item_sub_category)))->asArray(), + 201 + ); + } + + /** + * Generate any conditional POST parameters, will be merged with the data + * arrays defined in config/api/[type]/fields.php + * + * @param integer $category_id + * + * @return array + */ + private function fieldsData($category_id): array + { + $sub_categories = (new Subcategory()) + ->select('id', 'name', 'description') + ->where('category_id', '=', $category_id) + ->get(); + + $conditional_post_parameters = ['subcategory_id' => []]; + + foreach ($sub_categories as $sub_category) { + $id = $this->hash->encode('subcategory', $sub_category->id); + + if ($id === false) { + \App\Response\Responses::unableToDecode(); + } + + $conditional_post_parameters['subcategory_id']['allowed_values'][$id] = [ + 'value' => $id, + 'name' => $sub_category->name, + 'description' => $sub_category->description + ]; + } + + return $conditional_post_parameters; + } + + /** + * Delete the assigned sub category + * + * @param string $resource_type_id, + * @param string $resource_id, + * @param string $item_id, + * @param string $item_category_id, + * @param string $item_subcategory_id + * + * @return JsonResponse + */ + public function delete( + string $resource_type_id, + string $resource_id, + string $item_id, + string $item_category_id, + string $item_subcategory_id + ): JsonResponse + { + Route\Validate::item( + $resource_type_id, + $resource_id, + $item_id, + $this->permitted_resource_types, + true + ); + + $cache_control = new Cache\Control(Auth::user()->id); + $cache_key = new Cache\Key(); + + if ($item_category_id === 'nill' || $item_subcategory_id === 'nill') { + \App\Response\Responses::notFound(trans('entities.item-subcategory')); + } + + $item_sub_category = (new ItemSubcategory())->instance( + $resource_type_id, + $resource_id, + $item_id, + $item_category_id, + $item_subcategory_id + ); + + if ($item_sub_category === null) { + \App\Response\Responses::notFound(trans('entities.item-subcategory')); + } + + + try { + (new ItemSubcategory())->find($item_subcategory_id)->delete(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->items($resource_type_id, $resource_id), + $cache_key->resourceTypeItems($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->items($resource_type_id, $resource_id), + $cache_key->resourceTypeItems($resource_type_id) + ]); + } + + \App\Response\Responses::successNoContent(); + } catch (QueryException $e) { + \App\Response\Responses::foreignKeyConstraintError(); + } catch (Exception $e) { + \App\Response\Responses::notFound(trans('entities.item-subcategory'), $e); + } + } +} diff --git a/app/Http/Controllers/ItemSubcategoryController.php b/app/Http/Controllers/ItemSubcategoryView.php similarity index 64% rename from app/Http/Controllers/ItemSubcategoryController.php rename to app/Http/Controllers/ItemSubcategoryView.php index 5c54ccf5..f900361e 100644 --- a/app/Http/Controllers/ItemSubcategoryController.php +++ b/app/Http/Controllers/ItemSubcategoryView.php @@ -12,11 +12,7 @@ use App\Models\ItemSubcategory; use App\Models\Subcategory; use App\Models\Transformers\ItemSubcategory as ItemSubcategoryTransformer; -use App\Request\Validate\ItemSubcategory as ItemSubcategoryValidator; -use Exception; -use Illuminate\Database\QueryException; use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\Auth; /** * Manage the category for an item row @@ -25,7 +21,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class ItemSubcategoryController extends Controller +class ItemSubcategoryView extends Controller { /** * Return the sub category assigned to an item @@ -263,82 +259,6 @@ public function optionsShow( ); } - /** - * Assign the sub category - * - * @param string $resource_type_id - * @param string $resource_id - * @param string $item_id - * @param string $item_category_id - * - * @return JsonResponse - */ - public function create( - string $resource_type_id, - string $resource_id, - string $item_id, - string $item_category_id - ): JsonResponse - { - Route\Validate::item( - $resource_type_id, - $resource_id, - $item_id, - $this->permitted_resource_types, - true - ); - - $cache_control = new Cache\Control(Auth::user()->id); - $cache_key = new Cache\Key(); - - if ($item_category_id === 'nill') { - \App\Response\Responses::notFound(trans('entities.item-subcategory')); - } - - $item_category = (new ItemCategory()) - ->where('item_id', '=', $item_id) - ->find($item_category_id); - - $validator = (new ItemSubcategoryValidator)->create(['category_id' => $item_category->category_id]); - \App\Request\BodyValidation::validateAndReturnErrors( - $validator, - $this->fieldsData($item_category_id) - ); - - try { - $subcategory_id = $this->hash->decode('subcategory', request()->input('subcategory_id')); - - if ($subcategory_id === false) { - \App\Response\Responses::unableToDecode(); - } - - $item_sub_category = new ItemSubcategory([ - 'item_category_id' => $item_category_id, - 'sub_category_id' => $subcategory_id - ]); - $item_sub_category->save(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->items($resource_type_id, $resource_id), - $cache_key->resourceTypeItems($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->items($resource_type_id, $resource_id), - $cache_key->resourceTypeItems($resource_type_id) - ]); - } - } catch (Exception $e) { - \App\Response\Responses::failedToSaveModelForCreate(); - } - - return response()->json( - (new ItemSubcategoryTransformer((new ItemSubcategory())->instanceToArray($item_sub_category)))->asArray(), - 201 - ); - } - /** * Generate any conditional POST parameters, will be merged with the data * arrays defined in config/api/[type]/fields.php @@ -372,74 +292,4 @@ private function fieldsData($category_id): array return $conditional_post_parameters; } - - /** - * Delete the assigned sub category - * - * @param string $resource_type_id, - * @param string $resource_id, - * @param string $item_id, - * @param string $item_category_id, - * @param string $item_subcategory_id - * - * @return JsonResponse - */ - public function delete( - string $resource_type_id, - string $resource_id, - string $item_id, - string $item_category_id, - string $item_subcategory_id - ): JsonResponse - { - Route\Validate::item( - $resource_type_id, - $resource_id, - $item_id, - $this->permitted_resource_types, - true - ); - - $cache_control = new Cache\Control(Auth::user()->id); - $cache_key = new Cache\Key(); - - if ($item_category_id === 'nill' || $item_subcategory_id === 'nill') { - \App\Response\Responses::notFound(trans('entities.item-subcategory')); - } - - $item_sub_category = (new ItemSubcategory())->instance( - $resource_type_id, - $resource_id, - $item_id, - $item_category_id, - $item_subcategory_id - ); - - if ($item_sub_category === null) { - \App\Response\Responses::notFound(trans('entities.item-subcategory')); - } - - - try { - (new ItemSubcategory())->find($item_subcategory_id)->delete(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->items($resource_type_id, $resource_id), - $cache_key->resourceTypeItems($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->items($resource_type_id, $resource_id), - $cache_key->resourceTypeItems($resource_type_id) - ]); - } - - \App\Response\Responses::successNoContent(); - } catch (QueryException $e) { - \App\Response\Responses::foreignKeyConstraintError(); - } catch (Exception $e) { - \App\Response\Responses::notFound(trans('entities.item-subcategory'), $e); - } - } } diff --git a/app/Http/Controllers/ItemTransferManage.php b/app/Http/Controllers/ItemTransferManage.php new file mode 100644 index 00000000..e7a8f394 --- /dev/null +++ b/app/Http/Controllers/ItemTransferManage.php @@ -0,0 +1,92 @@ + + * @copyright Dean Blackborough 2018-2020 + * @license https://github.com/costs-to-expect/api/blob/master/LICENSE + */ +class ItemTransferManage extends Controller +{ + public function transfer( + string $resource_type_id, + string $resource_id, + string $item_id + ): JsonResponse + { + Route\Validate::item( + $resource_type_id, + $resource_id, + $item_id, + $this->permitted_resource_types, + true + ); + + $user_id = Auth::user()->id; + + $cache_control = new Cache\Control($user_id); + $cache_key = new Cache\Key(); + + $validator = (new ItemTransferValidator)->create( + [ + 'resource_type_id' => $resource_type_id, + 'existing_resource_id' => $resource_id + ] + ); + \App\Request\BodyValidation::validateAndReturnErrors($validator); + + try { + $new_resource_id = $this->hash->decode('resource', request()->input('resource_id')); + + if ($new_resource_id === false) { + return \App\Response\Responses::unableToDecode(); + } + + $item = (new Item())->instance($resource_type_id, $resource_id, $item_id); + if ($item !== null) { + $item->resource_id = $new_resource_id; + $item->save(); + } else { + return \App\Response\Responses::failedToSelectModelForUpdateOrDelete(); + } + + $item_transfer = new ItemTransfer([ + 'resource_type_id' => $resource_type_id, + 'from' => (int) $resource_id, + 'to' => $new_resource_id, + 'item_id' => $item_id, + 'transferred_by' => $user_id + ]); + $item_transfer->save(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->transfers($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->transfers($resource_type_id) + ]); + } + } catch (QueryException $e) { + return \App\Response\Responses::foreignKeyConstraintError(); + } catch (Exception $e) { + return \App\Response\Responses::failedToSaveModelForUpdate(); + } + + return \App\Response\Responses::successNoContent(); + } +} diff --git a/app/Http/Controllers/ItemTransferController.php b/app/Http/Controllers/ItemTransferView.php similarity index 75% rename from app/Http/Controllers/ItemTransferController.php rename to app/Http/Controllers/ItemTransferView.php index e6f414d5..817008ee 100644 --- a/app/Http/Controllers/ItemTransferController.php +++ b/app/Http/Controllers/ItemTransferView.php @@ -2,7 +2,6 @@ namespace App\Http\Controllers; -use App\Models\Item; use App\Models\ItemTransfer; use App\Models\Resource; use App\Models\Transformers\ItemTransfer as ItemTransferTransformer; @@ -13,11 +12,7 @@ use App\Request\Parameter; use App\Request\Route; use App\Response\Pagination as UtilityPagination; -use App\Request\Validate\ItemTransfer as ItemTransferValidator; -use Exception; -use Illuminate\Database\QueryException; use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Config; /** @@ -27,7 +22,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class ItemTransferController extends Controller +class ItemTransferView extends Controller { /** * Return the item transfers collection @@ -231,75 +226,6 @@ public function show( ); } - public function transfer( - string $resource_type_id, - string $resource_id, - string $item_id - ): JsonResponse - { - Route\Validate::item( - $resource_type_id, - $resource_id, - $item_id, - $this->permitted_resource_types, - true - ); - - $user_id = Auth::user()->id; - - $cache_control = new Cache\Control($user_id); - $cache_key = new Cache\Key(); - - $validator = (new ItemTransferValidator)->create( - [ - 'resource_type_id' => $resource_type_id, - 'existing_resource_id' => $resource_id - ] - ); - \App\Request\BodyValidation::validateAndReturnErrors($validator); - - try { - $new_resource_id = $this->hash->decode('resource', request()->input('resource_id')); - - if ($new_resource_id === false) { - return \App\Response\Responses::unableToDecode(); - } - - $item = (new Item())->instance($resource_type_id, $resource_id, $item_id); - if ($item !== null) { - $item->resource_id = $new_resource_id; - $item->save(); - } else { - return \App\Response\Responses::failedToSelectModelForUpdateOrDelete(); - } - - $item_transfer = new ItemTransfer([ - 'resource_type_id' => $resource_type_id, - 'from' => (int) $resource_id, - 'to' => $new_resource_id, - 'item_id' => $item_id, - 'transferred_by' => $user_id - ]); - $item_transfer->save(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->transfers($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->transfers($resource_type_id) - ]); - } - } catch (QueryException $e) { - return \App\Response\Responses::foreignKeyConstraintError(); - } catch (Exception $e) { - return \App\Response\Responses::failedToSaveModelForUpdate(); - } - - return \App\Response\Responses::successNoContent(); - } - /** * Generate any conditional POST parameters, will be merged with the * relevant config/api/[type]/fields.php data array diff --git a/app/Http/Controllers/ItemTypeController.php b/app/Http/Controllers/ItemTypeView.php similarity index 99% rename from app/Http/Controllers/ItemTypeController.php rename to app/Http/Controllers/ItemTypeView.php index ad33a4d3..82940fce 100644 --- a/app/Http/Controllers/ItemTypeController.php +++ b/app/Http/Controllers/ItemTypeView.php @@ -20,7 +20,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class ItemTypeController extends Controller +class ItemTypeView extends Controller { protected bool $allow_entire_collection = true; diff --git a/app/Http/Controllers/PassportController.php b/app/Http/Controllers/PassportView.php similarity index 98% rename from app/Http/Controllers/PassportController.php rename to app/Http/Controllers/PassportView.php index 1ca68775..eba942a7 100644 --- a/app/Http/Controllers/PassportController.php +++ b/app/Http/Controllers/PassportView.php @@ -13,7 +13,7 @@ * * @package App\Http\Controllers */ -class PassportController extends Controller +class PassportView extends Controller { /** * login to the API and create a token diff --git a/routes/api/auth.php b/routes/api/auth.php index 679470b7..ac023cee 100644 --- a/routes/api/auth.php +++ b/routes/api/auth.php @@ -10,23 +10,23 @@ function () { Route::post( 'auth/login', - 'PassportController@login' + 'PassportView@login' ); Route::get( 'auth/user', - 'PassportController@user' + 'PassportView@user' ); Route::get( 'auth/check', - 'PassportController@check' + 'PassportView@check' ); if (Config::get('api.app.config.registrations') === true) { Route::post( 'auth/register', - 'PassportController@register' + 'PassportView@register' ); } } diff --git a/routes/api/private-routes.php b/routes/api/private-routes.php index 9f703df5..b10d57b1 100644 --- a/routes/api/private-routes.php +++ b/routes/api/private-routes.php @@ -14,7 +14,7 @@ function () { Route::get( 'auth/user', - 'PassportController@user' + 'PassportView@user' ); Route::post( @@ -49,7 +49,7 @@ function () { Route::post( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/categories/{item_category_id}/subcategories', - 'ItemSubcategoryController@create' + 'ItemSubcategoryManage@create' ); Route::post( @@ -59,7 +59,7 @@ function () { Route::post( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/transfer', - 'ItemTransferController@transfer' + 'ItemTransferManage@transfer' ); Route::delete( @@ -99,7 +99,7 @@ function () { Route::delete( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/categories/{item_category_id}/subcategories/{item_subcategory_id}', - 'ItemSubcategoryController@delete' + 'ItemSubcategoryManage@delete' ); Route::patch( diff --git a/routes/api/public-routes.php b/routes/api/public-routes.php index c7326bca..3fae9ddf 100644 --- a/routes/api/public-routes.php +++ b/routes/api/public-routes.php @@ -36,22 +36,22 @@ function () { Route::get( 'item-types', - 'ItemTypeController@index' + 'ItemTypeView@index' ); Route::options( 'item-types', - 'ItemTypeController@optionsIndex' + 'ItemTypeView@optionsIndex' ); Route::get( 'item-types/{item_type_id}', - 'ItemTypeController@show' + 'ItemTypeView@show' ); Route::options( 'item-types/{item_type_id}', - 'ItemTypeController@optionsShow' + 'ItemTypeView@optionsShow' ); Route::get( @@ -201,7 +201,7 @@ function () { Route::options( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/transfer', - 'ItemTransferController@optionsTransfer' + 'ItemTransferView@optionsTransfer' ); /*This route needs to be removed*/ @@ -231,45 +231,45 @@ function () { /*This route needs to be removed*/ Route::get( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/categories/{item_category_id}/subcategories', - 'ItemSubcategoryController@index' + 'ItemSubcategoryView@index' ); /*This route needs to be removed*/ Route::options( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/categories/{item_category_id}/subcategories', - 'ItemSubcategoryController@optionsIndex' + 'ItemSubcategoryView@optionsIndex' ); /*This route needs to be removed*/ Route::get( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/categories/{item_category_id}/subcategories/{item_subcategory_id}', - 'ItemSubcategoryController@show' + 'ItemSubcategoryView@show' ); /*This route needs to be removed*/ Route::options( 'resource-types/{resource_type_id}/resources/{resource_id}/items/{item_id}/categories/{item_category_id}/subcategories/{item_subcategory_id}', - 'ItemSubcategoryController@optionsShow' + 'ItemSubcategoryView@optionsShow' ); Route::options( 'resource-types/{resource_type_id}/transfers', - 'ItemTransferController@optionsIndex' + 'ItemTransferView@optionsIndex' ); Route::get( 'resource-types/{resource_type_id}/transfers', - 'ItemTransferController@index' + 'ItemTransferView@index' ); Route::options( 'resource-types/{resource_type_id}/transfers/{item_transfer_id}', - 'ItemTransferController@optionsShow' + 'ItemTransferView@optionsShow' ); Route::get( 'resource-types/{resource_type_id}/transfers/{item_transfer_id}', - 'ItemTransferController@show' + 'ItemTransferView@show' ); // Request access and error logs From dff399e36922afde79522edc684d800478001c4a Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Wed, 1 Jul 2020 00:09:53 +0100 Subject: [PATCH 20/24] Refactoring - Split controllers --- ...erController.php => PermittedUserView.php} | 2 +- app/Http/Controllers/RequestManage.php | 58 +++++ ...{RequestController.php => RequestView.php} | 44 +--- app/Http/Controllers/ResourceManage.php | 185 ++++++++++++++ ...ontroller.php => ResourceTypeItemView.php} | 2 +- app/Http/Controllers/ResourceTypeManage.php | 230 ++++++++++++++++++ ...ypeController.php => ResourceTypeView.php} | 210 +--------------- ...esourceController.php => ResourceView.php} | 166 +------------ app/Http/Controllers/SubcategoryManage.php | 204 ++++++++++++++++ ...goryController.php => SubcategoryView.php} | 185 +------------- ...ategoryController.php => CategoryView.php} | 2 +- .../{ItemController.php => ItemView.php} | 2 +- ...{RequestController.php => RequestView.php} | 2 +- ...ontroller.php => ResourceTypeItemView.php} | 2 +- ...ypeController.php => ResourceTypeView.php} | 2 +- ...esourceController.php => ResourceView.php} | 2 +- ...goryController.php => SubcategoryView.php} | 2 +- routes/api/private-routes.php | 18 +- routes/api/public-routes.php | 42 ++-- routes/api/public-summary-routes.php | 28 +-- 20 files changed, 734 insertions(+), 654 deletions(-) rename app/Http/Controllers/{PermittedUserController.php => PermittedUserView.php} (98%) create mode 100644 app/Http/Controllers/RequestManage.php rename app/Http/Controllers/{RequestController.php => RequestView.php} (71%) create mode 100644 app/Http/Controllers/ResourceManage.php rename app/Http/Controllers/{ResourceTypeItemController.php => ResourceTypeItemView.php} (99%) create mode 100644 app/Http/Controllers/ResourceTypeManage.php rename app/Http/Controllers/{ResourceTypeController.php => ResourceTypeView.php} (54%) rename app/Http/Controllers/{ResourceController.php => ResourceView.php} (58%) create mode 100644 app/Http/Controllers/SubcategoryManage.php rename app/Http/Controllers/{SubcategoryController.php => SubcategoryView.php} (57%) rename app/Http/Controllers/Summary/{CategoryController.php => CategoryView.php} (98%) rename app/Http/Controllers/Summary/{ItemController.php => ItemView.php} (99%) rename app/Http/Controllers/Summary/{RequestController.php => RequestView.php} (98%) rename app/Http/Controllers/Summary/{ResourceTypeItemController.php => ResourceTypeItemView.php} (99%) rename app/Http/Controllers/Summary/{ResourceTypeController.php => ResourceTypeView.php} (98%) rename app/Http/Controllers/Summary/{ResourceController.php => ResourceView.php} (98%) rename app/Http/Controllers/Summary/{SubcategoryController.php => SubcategoryView.php} (98%) diff --git a/app/Http/Controllers/PermittedUserController.php b/app/Http/Controllers/PermittedUserView.php similarity index 98% rename from app/Http/Controllers/PermittedUserController.php rename to app/Http/Controllers/PermittedUserView.php index 6fc4283a..f9b43d28 100644 --- a/app/Http/Controllers/PermittedUserController.php +++ b/app/Http/Controllers/PermittedUserView.php @@ -21,7 +21,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class PermittedUserController extends Controller +class PermittedUserView extends Controller { protected bool $allow_entire_collection = true; diff --git a/app/Http/Controllers/RequestManage.php b/app/Http/Controllers/RequestManage.php new file mode 100644 index 00000000..5a57b7c5 --- /dev/null +++ b/app/Http/Controllers/RequestManage.php @@ -0,0 +1,58 @@ + + * @copyright Dean Blackborough 2018-2020 + * @license https://github.com/costs-to-expect/api/blob/master/LICENSE + */ +class RequestManage extends Controller +{ + /** + * Log a request error, these are logged when the web app receives an unexpected + * http status code response + * + * @return JsonResponse + */ + public function createErrorLog(): JsonResponse + { + $validator = (new RequestErrorLogValidator())->create(); + \App\Request\BodyValidation::validateAndReturnErrors($validator); + + try { + $request_error_log = new RequestErrorLog([ + 'method' => request()->input('method'), + 'source' => request()->input('source'), + 'expected_status_code' => request()->input('expected_status_code'), + 'returned_status_code' => request()->input('returned_status_code'), + 'request_uri' => request()->input('request_uri'), + 'debug' => request()->input('debug') + ]); + $request_error_log->save(); + + event(new RequestError([ + 'method' => request()->input('method'), + 'source' => request()->input('source'), + 'expected_status_code' => request()->input('expected_status_code'), + 'returned_status_code' => request()->input('returned_status_code'), + 'request_uri' => request()->input('request_uri'), + 'referer' => request()->server('HTTP_REFERER', 'NOT SET!'), + 'debug' => request()->input('debug') + ])); + + } catch (Exception $e) { + \App\Response\Responses::failedToSaveModelForCreate(); + } + + return \App\Response\Responses::successNoContent(); + } +} diff --git a/app/Http/Controllers/RequestController.php b/app/Http/Controllers/RequestView.php similarity index 71% rename from app/Http/Controllers/RequestController.php rename to app/Http/Controllers/RequestView.php index a256908b..1612510f 100644 --- a/app/Http/Controllers/RequestController.php +++ b/app/Http/Controllers/RequestView.php @@ -2,7 +2,6 @@ namespace App\Http\Controllers; -use App\Events\RequestError; use App\Option\Get; use App\Option\Post; use App\Response\Header\Header; @@ -12,8 +11,6 @@ use App\Models\Transformers\RequestErrorLog as RequestErrorLogTransformer; use App\Models\Transformers\RequestLog as RequestLogTransformer; use App\Response\Pagination as UtilityPagination; -use App\Request\Validate\RequestErrorLog as RequestErrorLogValidator; -use Exception; use Illuminate\Http\JsonResponse; use Illuminate\Support\Facades\Config; @@ -24,7 +21,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class RequestController extends Controller +class RequestView extends Controller { protected $collection_parameters = []; @@ -145,43 +142,4 @@ public function optionsErrorLog() 200 ); } - - /** - * Log a request error, these are logged when the web app receives an unexpected - * http status code response - * - * @return JsonResponse - */ - public function createErrorLog(): JsonResponse - { - $validator = (new RequestErrorLogValidator())->create(); - \App\Request\BodyValidation::validateAndReturnErrors($validator); - - try { - $request_error_log = new RequestErrorLog([ - 'method' => request()->input('method'), - 'source' => request()->input('source'), - 'expected_status_code' => request()->input('expected_status_code'), - 'returned_status_code' => request()->input('returned_status_code'), - 'request_uri' => request()->input('request_uri'), - 'debug' => request()->input('debug') - ]); - $request_error_log->save(); - - event(new RequestError([ - 'method' => request()->input('method'), - 'source' => request()->input('source'), - 'expected_status_code' => request()->input('expected_status_code'), - 'returned_status_code' => request()->input('returned_status_code'), - 'request_uri' => request()->input('request_uri'), - 'referer' => request()->server('HTTP_REFERER', 'NOT SET!'), - 'debug' => request()->input('debug') - ])); - - } catch (Exception $e) { - \App\Response\Responses::failedToSaveModelForCreate(); - } - - return \App\Response\Responses::successNoContent(); - } } diff --git a/app/Http/Controllers/ResourceManage.php b/app/Http/Controllers/ResourceManage.php new file mode 100644 index 00000000..fadf4e28 --- /dev/null +++ b/app/Http/Controllers/ResourceManage.php @@ -0,0 +1,185 @@ + + * @copyright Dean Blackborough 2018-2020 + * @license https://github.com/costs-to-expect/api/blob/master/LICENSE + */ +class ResourceManage extends Controller +{ + protected bool $allow_entire_collection = true; + + /** + * Create a new resource + * + * @param string $resource_type_id + * + * @return JsonResponse + */ + public function create(string $resource_type_id): JsonResponse + { + Route\Validate::resourceType( + $resource_type_id, + $this->permitted_resource_types, + true + ); + + $cache_control = new Cache\Control(Auth::user()->id); + $cache_key = new Cache\Key(); + + $validator = (new ResourceValidator)->create(['resource_type_id' => $resource_type_id]); + \App\Request\BodyValidation::validateAndReturnErrors($validator); + + try { + $resource = new Resource([ + 'resource_type_id' => $resource_type_id, + 'name' => request()->input('name'), + 'description' => request()->input('description'), + 'effective_date' => request()->input('effective_date') + ]); + $resource->save(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->resourceType($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->resourceType($resource_type_id) + ]); + } + } catch (Exception $e) { + \App\Response\Responses::failedToSaveModelForCreate(); + } + + return response()->json( + (new ResourceTransformer((New Resource())->instanceToArray($resource)))->asArray(), + 201 + ); + } + + /** + * Delete the requested resource + * + * @param string $resource_type_id, + * @param string $resource_id + * + * @return JsonResponse + */ + public function delete( + string $resource_type_id, + string $resource_id + ): JsonResponse + { + Route\Validate::resource( + $resource_type_id, + $resource_id, + $this->permitted_resource_types, + true + ); + + $cache_control = new Cache\Control(Auth::user()->id); + $cache_key = new Cache\Key(); + + try { + (new Resource())->find($resource_id)->delete(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->resourceType($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->resourceType($resource_type_id) + ]); + } + + \App\Response\Responses::successNoContent(); + } catch (QueryException $e) { + \App\Response\Responses::foreignKeyConstraintError(); + } catch (Exception $e) { + \App\Response\Responses::notFound(trans('entities.resource'), $e); + } + } + + /** + * Update the selected resource + * + * @param string $resource_type_id + * @param string $resource_id + * + * @return JsonResponse + */ + public function update( + string $resource_type_id, + string $resource_id + ): JsonResponse + { + Route\Validate::resource( + $resource_type_id, + $resource_id, + $this->permitted_resource_types, + true + ); + + $cache_control = new Cache\Control(Auth::user()->id); + $cache_key = new Cache\Key(); + + $resource = (new Resource())->instance($resource_type_id, $resource_id); + + if ($resource === null) { + \App\Response\Responses::failedToSelectModelForUpdateOrDelete(); + } + + \App\Request\BodyValidation::checkForEmptyPatch(); + + $validator = (new ResourceValidator())->update([ + 'resource_type_id' => (int)$resource_type_id, + 'resource_id' => (int)$resource_id + ]); + \App\Request\BodyValidation::validateAndReturnErrors($validator); + + \App\Request\BodyValidation::checkForInvalidFields( + array_merge( + (new Resource())->patchableFields(), + (new ResourceValidator())->dynamicDefinedFields() + ) + ); + + foreach (request()->all() as $key => $value) { + $resource->$key = $value; + } + + try { + $resource->save(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->resourceType($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->resourceType($resource_type_id) + ]); + } + } catch (Exception $e) { + \App\Response\Responses::failedToSaveModelForUpdate(); + } + + \App\Response\Responses::successNoContent(); + } +} diff --git a/app/Http/Controllers/ResourceTypeItemController.php b/app/Http/Controllers/ResourceTypeItemView.php similarity index 99% rename from app/Http/Controllers/ResourceTypeItemController.php rename to app/Http/Controllers/ResourceTypeItemView.php index b1b56d9e..fc831a1e 100644 --- a/app/Http/Controllers/ResourceTypeItemController.php +++ b/app/Http/Controllers/ResourceTypeItemView.php @@ -20,7 +20,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class ResourceTypeItemController extends Controller +class ResourceTypeItemView extends Controller { /** * Return all the items based on the set filter options diff --git a/app/Http/Controllers/ResourceTypeManage.php b/app/Http/Controllers/ResourceTypeManage.php new file mode 100644 index 00000000..141a113b --- /dev/null +++ b/app/Http/Controllers/ResourceTypeManage.php @@ -0,0 +1,230 @@ + + * @copyright Dean Blackborough 2018-2020 + * @license https://github.com/costs-to-expect/api/blob/master/LICENSE + */ +class ResourceTypeManage extends Controller +{ + protected bool $allow_entire_collection = true; + + /** + * Create a new resource type + * + * @return JsonResponse + */ + public function create(): JsonResponse + { + $user_id = Auth::user()->id; + + $validator = (new ResourceTypeValidator)->create([ + 'user_id' => $user_id + ]); + \App\Request\BodyValidation::validateAndReturnErrors($validator); + + $cache_control = new Cache\Control($user_id); + $cache_key = new Cache\Key(); + + try { + $resource_type = new ResourceType([ + 'name' => request()->input('name'), + 'description' => request()->input('description'), + 'public' => request()->input('public', 0) + ]); + $resource_type->save(); + + $permitted_users = new PermittedUser([ + 'resource_type_id' => $resource_type->id, + 'user_id' => $user_id, + 'added_by' => $user_id + ]); + $permitted_users->save(); + + $item_type_id = $this->hash->decode('item_type', request()->input('item_type_id')); + + if ($item_type_id === false) { + \App\Response\Responses::unableToDecode(); + } + + $resource_type_item_type = new ResourceTypeItemType([ + 'resource_type_id' => $resource_type->id, + 'item_type_id' => $item_type_id + ]); + $resource_type_item_type->save(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->resourcesTypes() + ]); + + if (request()->input('public', 0) !== 0) { + $cache_control->clearPublicCacheKeys([ + $cache_key->resourcesTypes() + ]); + } + } catch (Exception $e) { + \App\Response\Responses::failedToSaveModelForCreate(); + } + + return response()->json( + (new ResourceTypeTransformer((New ResourceType())->instanceToArray($resource_type)))->asArray(), + 201 + ); + } + + /** + * Delete the requested resource type + * + * @param string $resource_type_id + * + * @return JsonResponse + */ + public function delete( + string $resource_type_id + ): JsonResponse + { + Route\Validate::resourceType( + $resource_type_id, + $this->permitted_resource_types, + true + ); + + $user_id = Auth::user()->id; + + $cache_control = new Cache\Control($user_id); + $cache_key = new Cache\Key(); + + $resource_type_item_type = (new ResourceTypeItemType())->instance($resource_type_id); + $permitted_user = (new PermittedUser())->instance($resource_type_id, $user_id); + $resource_type = (new ResourceType())->find($resource_type_id); + + $categories = (new Category())->total( + $resource_type_id, + $this->permitted_resource_types, + $this->include_public + ); + + $resources = (new Resource())->totalCount( + $resource_type_id, + $this->permitted_resource_types, + $this->include_public + ); + + if ( + $categories === 0 && + $resources === 0 && + $resource_type_item_type !== null && + $permitted_user !== null && + $resource_type !== null + ) { + try { + $resource_type_item_type->delete(); + $permitted_user->delete(); + $resource_type->delete(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->resourcesTypes(), + $cache_key->permittedUsers($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->resourcesTypes(), + $cache_key->permittedUsers($resource_type_id) + ]); + } + + \App\Response\Responses::successNoContent(); + } catch (QueryException $e) { + \App\Response\Responses::foreignKeyConstraintError(); + } catch (Exception $e) { + \App\Response\Responses::notFound(trans('entities.resource-type'), $e); + } + } else { + \App\Response\Responses::foreignKeyConstraintError(); + } + } + + /** + * Update the selected category + * + * @param string $resource_type_id + * + * @return JsonResponse + */ + public function update( + string $resource_type_id + ): JsonResponse + { + Route\Validate::resourceType( + $resource_type_id, + $this->permitted_resource_types, + true + ); + + $user_id = Auth::user()->id; + + $cache_control = new Cache\Control($user_id); + $cache_key = new Cache\Key(); + + $resource_type = (new ResourceType())->instance($resource_type_id); + + if ($resource_type === null) { + \App\Response\Responses::failedToSelectModelForUpdateOrDelete(); + } + + \App\Request\BodyValidation::checkForEmptyPatch(); + + $validator = (new ResourceTypeValidator())->update([ + 'resource_type_id' => (int) ($resource_type_id), + 'user_id' => $user_id + ]); + \App\Request\BodyValidation::validateAndReturnErrors($validator); + + \App\Request\BodyValidation::checkForInvalidFields( + array_merge( + (new ResourceType())->patchableFields(), + (new ResourceTypeValidator())->dynamicDefinedFields() + ) + ); + + foreach (request()->all() as $key => $value) { + $resource_type->$key = $value; + } + + try { + $resource_type->save(); + $cache_control->clearPrivateCacheKeys([ + $cache_key->resourcesTypes() + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->resourcesTypes() + ]); + } + } catch (Exception $e) { + \App\Response\Responses::failedToSaveModelForUpdate(); + } + + \App\Response\Responses::successNoContent(); + } +} diff --git a/app/Http/Controllers/ResourceTypeController.php b/app/Http/Controllers/ResourceTypeView.php similarity index 54% rename from app/Http/Controllers/ResourceTypeController.php rename to app/Http/Controllers/ResourceTypeView.php index 60fc22c3..e1bfc093 100644 --- a/app/Http/Controllers/ResourceTypeController.php +++ b/app/Http/Controllers/ResourceTypeView.php @@ -2,11 +2,8 @@ namespace App\Http\Controllers; -use App\Models\Category; use App\Models\ItemType; -use App\Models\PermittedUser; use App\Models\Resource; -use App\Models\ResourceTypeItemType; use App\Option\Delete; use App\Option\Get; use App\Option\Patch; @@ -18,11 +15,7 @@ use App\Response\Pagination as UtilityPagination; use App\Models\ResourceType; use App\Models\Transformers\ResourceType as ResourceTypeTransformer; -use App\Request\Validate\ResourceType as ResourceTypeValidator; -use Exception; -use Illuminate\Database\QueryException; use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Config; /** @@ -32,7 +25,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class ResourceTypeController extends Controller +class ResourceTypeView extends Controller { protected bool $allow_entire_collection = true; @@ -220,207 +213,6 @@ public function optionsShow(string $resource_type_id): JsonResponse ); } - /** - * Create a new resource type - * - * @return JsonResponse - */ - public function create(): JsonResponse - { - $user_id = Auth::user()->id; - - $validator = (new ResourceTypeValidator)->create([ - 'user_id' => $user_id - ]); - \App\Request\BodyValidation::validateAndReturnErrors($validator); - - $cache_control = new Cache\Control($user_id); - $cache_key = new Cache\Key(); - - try { - $resource_type = new ResourceType([ - 'name' => request()->input('name'), - 'description' => request()->input('description'), - 'public' => request()->input('public', 0) - ]); - $resource_type->save(); - - $permitted_users = new PermittedUser([ - 'resource_type_id' => $resource_type->id, - 'user_id' => $user_id, - 'added_by' => $user_id - ]); - $permitted_users->save(); - - $item_type_id = $this->hash->decode('item_type', request()->input('item_type_id')); - - if ($item_type_id === false) { - \App\Response\Responses::unableToDecode(); - } - - $resource_type_item_type = new ResourceTypeItemType([ - 'resource_type_id' => $resource_type->id, - 'item_type_id' => $item_type_id - ]); - $resource_type_item_type->save(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->resourcesTypes() - ]); - - if (request()->input('public', 0) !== 0) { - $cache_control->clearPublicCacheKeys([ - $cache_key->resourcesTypes() - ]); - } - } catch (Exception $e) { - \App\Response\Responses::failedToSaveModelForCreate(); - } - - return response()->json( - (new ResourceTypeTransformer((New ResourceType())->instanceToArray($resource_type)))->asArray(), - 201 - ); - } - - /** - * Delete the requested resource type - * - * @param string $resource_type_id - * - * @return JsonResponse - */ - public function delete( - string $resource_type_id - ): JsonResponse - { - Route\Validate::resourceType( - $resource_type_id, - $this->permitted_resource_types, - true - ); - - $user_id = Auth::user()->id; - - $cache_control = new Cache\Control($user_id); - $cache_key = new Cache\Key(); - - $resource_type_item_type = (new ResourceTypeItemType())->instance($resource_type_id); - $permitted_user = (new PermittedUser())->instance($resource_type_id, $user_id); - $resource_type = (new ResourceType())->find($resource_type_id); - - $categories = (new Category())->total( - $resource_type_id, - $this->permitted_resource_types, - $this->include_public - ); - - $resources = (new Resource())->totalCount( - $resource_type_id, - $this->permitted_resource_types, - $this->include_public - ); - - if ( - $categories === 0 && - $resources === 0 && - $resource_type_item_type !== null && - $permitted_user !== null && - $resource_type !== null - ) { - try { - $resource_type_item_type->delete(); - $permitted_user->delete(); - $resource_type->delete(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->resourcesTypes(), - $cache_key->permittedUsers($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->resourcesTypes(), - $cache_key->permittedUsers($resource_type_id) - ]); - } - - \App\Response\Responses::successNoContent(); - } catch (QueryException $e) { - \App\Response\Responses::foreignKeyConstraintError(); - } catch (Exception $e) { - \App\Response\Responses::notFound(trans('entities.resource-type'), $e); - } - } else { - \App\Response\Responses::foreignKeyConstraintError(); - } - } - - /** - * Update the selected category - * - * @param string $resource_type_id - * - * @return JsonResponse - */ - public function update( - string $resource_type_id - ): JsonResponse - { - Route\Validate::resourceType( - $resource_type_id, - $this->permitted_resource_types, - true - ); - - $user_id = Auth::user()->id; - - $cache_control = new Cache\Control($user_id); - $cache_key = new Cache\Key(); - - $resource_type = (new ResourceType())->instance($resource_type_id); - - if ($resource_type === null) { - \App\Response\Responses::failedToSelectModelForUpdateOrDelete(); - } - - \App\Request\BodyValidation::checkForEmptyPatch(); - - $validator = (new ResourceTypeValidator())->update([ - 'resource_type_id' => (int) ($resource_type_id), - 'user_id' => $user_id - ]); - \App\Request\BodyValidation::validateAndReturnErrors($validator); - - \App\Request\BodyValidation::checkForInvalidFields( - array_merge( - (new ResourceType())->patchableFields(), - (new ResourceTypeValidator())->dynamicDefinedFields() - ) - ); - - foreach (request()->all() as $key => $value) { - $resource_type->$key = $value; - } - - try { - $resource_type->save(); - $cache_control->clearPrivateCacheKeys([ - $cache_key->resourcesTypes() - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->resourcesTypes() - ]); - } - } catch (Exception $e) { - \App\Response\Responses::failedToSaveModelForUpdate(); - } - - \App\Response\Responses::successNoContent(); - } - /** * Generate any conditional POST parameters, will be merged with the relevant * config/api/[type]/fields.php data array diff --git a/app/Http/Controllers/ResourceController.php b/app/Http/Controllers/ResourceView.php similarity index 58% rename from app/Http/Controllers/ResourceController.php rename to app/Http/Controllers/ResourceView.php index 63402e6b..04dba8be 100644 --- a/app/Http/Controllers/ResourceController.php +++ b/app/Http/Controllers/ResourceView.php @@ -14,11 +14,7 @@ use App\Response\Pagination as UtilityPagination; use App\Models\Resource; use App\Models\Transformers\Resource as ResourceTransformer; -use App\Request\Validate\Resource as ResourceValidator; -use Exception; -use Illuminate\Database\QueryException; use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Config; /** @@ -28,7 +24,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class ResourceController extends Controller +class ResourceView extends Controller { protected bool $allow_entire_collection = true; @@ -235,164 +231,4 @@ public function optionsShow(string $resource_type_id, string $resource_id): Json 200 ); } - - /** - * Create a new resource - * - * @param string $resource_type_id - * - * @return JsonResponse - */ - public function create(string $resource_type_id): JsonResponse - { - Route\Validate::resourceType( - $resource_type_id, - $this->permitted_resource_types, - true - ); - - $cache_control = new Cache\Control(Auth::user()->id); - $cache_key = new Cache\Key(); - - $validator = (new ResourceValidator)->create(['resource_type_id' => $resource_type_id]); - \App\Request\BodyValidation::validateAndReturnErrors($validator); - - try { - $resource = new Resource([ - 'resource_type_id' => $resource_type_id, - 'name' => request()->input('name'), - 'description' => request()->input('description'), - 'effective_date' => request()->input('effective_date') - ]); - $resource->save(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->resourceType($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->resourceType($resource_type_id) - ]); - } - } catch (Exception $e) { - \App\Response\Responses::failedToSaveModelForCreate(); - } - - return response()->json( - (new ResourceTransformer((New Resource())->instanceToArray($resource)))->asArray(), - 201 - ); - } - - /** - * Delete the requested resource - * - * @param string $resource_type_id, - * @param string $resource_id - * - * @return JsonResponse - */ - public function delete( - string $resource_type_id, - string $resource_id - ): JsonResponse - { - Route\Validate::resource( - $resource_type_id, - $resource_id, - $this->permitted_resource_types, - true - ); - - $cache_control = new Cache\Control(Auth::user()->id); - $cache_key = new Cache\Key(); - - try { - (new Resource())->find($resource_id)->delete(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->resourceType($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->resourceType($resource_type_id) - ]); - } - - \App\Response\Responses::successNoContent(); - } catch (QueryException $e) { - \App\Response\Responses::foreignKeyConstraintError(); - } catch (Exception $e) { - \App\Response\Responses::notFound(trans('entities.resource'), $e); - } - } - - /** - * Update the selected resource - * - * @param string $resource_type_id - * @param string $resource_id - * - * @return JsonResponse - */ - public function update( - string $resource_type_id, - string $resource_id - ): JsonResponse - { - Route\Validate::resource( - $resource_type_id, - $resource_id, - $this->permitted_resource_types, - true - ); - - $cache_control = new Cache\Control(Auth::user()->id); - $cache_key = new Cache\Key(); - - $resource = (new Resource())->instance($resource_type_id, $resource_id); - - if ($resource === null) { - \App\Response\Responses::failedToSelectModelForUpdateOrDelete(); - } - - \App\Request\BodyValidation::checkForEmptyPatch(); - - $validator = (new ResourceValidator())->update([ - 'resource_type_id' => (int)$resource_type_id, - 'resource_id' => (int)$resource_id - ]); - \App\Request\BodyValidation::validateAndReturnErrors($validator); - - \App\Request\BodyValidation::checkForInvalidFields( - array_merge( - (new Resource())->patchableFields(), - (new ResourceValidator())->dynamicDefinedFields() - ) - ); - - foreach (request()->all() as $key => $value) { - $resource->$key = $value; - } - - try { - $resource->save(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->resourceType($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->resourceType($resource_type_id) - ]); - } - } catch (Exception $e) { - \App\Response\Responses::failedToSaveModelForUpdate(); - } - - \App\Response\Responses::successNoContent(); - } } diff --git a/app/Http/Controllers/SubcategoryManage.php b/app/Http/Controllers/SubcategoryManage.php new file mode 100644 index 00000000..5f3d84ba --- /dev/null +++ b/app/Http/Controllers/SubcategoryManage.php @@ -0,0 +1,204 @@ + + * @copyright Dean Blackborough 2018-2020 + * @license https://github.com/costs-to-expect/api/blob/master/LICENSE + */ +class SubcategoryManage extends Controller +{ + protected bool $allow_entire_collection = true; + + /** + * Create a new sub category + * + * @param $resource_type_id + * @param $category_id + * + * @return JsonResponse + */ + public function create($resource_type_id, $category_id): JsonResponse + { + Route\Validate::category( + (int) $resource_type_id, + (int) $category_id, + $this->permitted_resource_types, + true + ); + + $cache_control = new Cache\Control(Auth::user()->id); + $cache_key = new Cache\Key(); + + $validator = (new SubcategoryValidator)->create(['category_id' => $category_id]); + \App\Request\BodyValidation::validateAndReturnErrors($validator); + + try { + $sub_category = new Subcategory([ + 'category_id' => $category_id, + 'name' => request()->input('name'), + 'description' => request()->input('description') + ]); + $sub_category->save(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->categories($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->categories($resource_type_id) + ]); + } + } catch (Exception $e) { + \App\Response\Responses::failedToSaveModelForCreate(); + } + + return response()->json( + (new SubcategoryTransformer((new Subcategory())->instanceToArray($sub_category)))->asArray(), + 201 + ); + } + + /** + * Delete the requested sub category + * + * @param $resource_type_id + * @param $category_id + * @param $subcategory_id + * + * @return JsonResponse + */ + public function delete( + $resource_type_id, + $category_id, + $subcategory_id + ): JsonResponse + { + Route\Validate::subcategory( + (int) $resource_type_id, + (int) $category_id, + (int) $subcategory_id, + $this->permitted_resource_types, + true + ); + + $cache_control = new Cache\Control(Auth::user()->id); + $cache_key = new Cache\Key(); + + $sub_category = (new Subcategory())->instance( + $category_id, + $subcategory_id + ); + + if ($sub_category === null) { + \App\Response\Responses::notFound(trans('entities.subcategory')); + } + + try { + $sub_category->delete(); + + $cache_control->clearPrivateCacheKeys([ + $cache_key->categories($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->categories($resource_type_id) + ]); + } + + \App\Response\Responses::successNoContent(); + } catch (QueryException $e) { + \App\Response\Responses::foreignKeyConstraintError(); + } catch (Exception $e) { + \App\Response\Responses::notFound(trans('entities.subcategory'), $e); + } + } + + /** + * Update the selected subcategory + * + * @param $resource_type_id + * @param $category_id + * @param $subcategory_id + * + * @return JsonResponse + */ + public function update( + $resource_type_id, + $category_id, + $subcategory_id + ): JsonResponse + { + Route\Validate::subcategory( + (int) $resource_type_id, + (int) $category_id, + (int) $subcategory_id, + $this->permitted_resource_types, + true + ); + + $cache_control = new Cache\Control(Auth::user()->id); + $cache_key = new Cache\Key(); + + $subcategory = (new Subcategory())->instance($category_id, $subcategory_id); + + if ($subcategory === null) { + \App\Response\Responses::failedToSelectModelForUpdateOrDelete(); + } + + \App\Request\BodyValidation::checkForEmptyPatch(); + + $validator = (new SubcategoryValidator())->update([ + 'category_id' => (int)$category_id, + 'subcategory_id' => (int)$subcategory_id + ]); + \App\Request\BodyValidation::validateAndReturnErrors($validator); + + \App\Request\BodyValidation::checkForInvalidFields( + array_merge( + (new Subcategory())->patchableFields(), + (new SubcategoryValidator)->dynamicDefinedFields() + ) + ); + + foreach (request()->all() as $key => $value) { + $subcategory->$key = $value; + } + + try { + $subcategory->save(); + + $cache_control->clearPrivateCacheKeys([ + // We need to clear subcategories, resource type items + // and items dur to includes so simpler to clear the entire + // resource type + $cache_key->resourceType($resource_type_id) + ]); + + if (in_array($resource_type_id, $this->public_resource_types, true)) { + $cache_control->clearPublicCacheKeys([ + $cache_key->resourceType($resource_type_id) + ]); + } + } catch (Exception $e) { + \App\Response\Responses::failedToSaveModelForUpdate(); + } + + \App\Response\Responses::successNoContent(); + } +} diff --git a/app/Http/Controllers/SubcategoryController.php b/app/Http/Controllers/SubcategoryView.php similarity index 57% rename from app/Http/Controllers/SubcategoryController.php rename to app/Http/Controllers/SubcategoryView.php index 8395f98a..91cd419f 100644 --- a/app/Http/Controllers/SubcategoryController.php +++ b/app/Http/Controllers/SubcategoryView.php @@ -14,11 +14,7 @@ use App\Response\Pagination as UtilityPagination; use App\Models\Subcategory; use App\Models\Transformers\Subcategory as SubcategoryTransformer; -use App\Request\Validate\Subcategory as SubcategoryValidator; -use Exception; -use Illuminate\Database\QueryException; use Illuminate\Http\JsonResponse; -use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Config; /** @@ -28,7 +24,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class SubcategoryController extends Controller +class SubcategoryView extends Controller { protected bool $allow_entire_collection = true; @@ -244,183 +240,4 @@ public function optionsShow( 200 ); } - - /** - * Create a new sub category - * - * @param $resource_type_id - * @param $category_id - * - * @return JsonResponse - */ - public function create($resource_type_id, $category_id): JsonResponse - { - Route\Validate::category( - (int) $resource_type_id, - (int) $category_id, - $this->permitted_resource_types, - true - ); - - $cache_control = new Cache\Control(Auth::user()->id); - $cache_key = new Cache\Key(); - - $validator = (new SubcategoryValidator)->create(['category_id' => $category_id]); - \App\Request\BodyValidation::validateAndReturnErrors($validator); - - try { - $sub_category = new Subcategory([ - 'category_id' => $category_id, - 'name' => request()->input('name'), - 'description' => request()->input('description') - ]); - $sub_category->save(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->categories($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->categories($resource_type_id) - ]); - } - } catch (Exception $e) { - \App\Response\Responses::failedToSaveModelForCreate(); - } - - return response()->json( - (new SubcategoryTransformer((new Subcategory())->instanceToArray($sub_category)))->asArray(), - 201 - ); - } - - /** - * Delete the requested sub category - * - * @param $resource_type_id - * @param $category_id - * @param $subcategory_id - * - * @return JsonResponse - */ - public function delete( - $resource_type_id, - $category_id, - $subcategory_id - ): JsonResponse - { - Route\Validate::subcategory( - (int) $resource_type_id, - (int) $category_id, - (int) $subcategory_id, - $this->permitted_resource_types, - true - ); - - $cache_control = new Cache\Control(Auth::user()->id); - $cache_key = new Cache\Key(); - - $sub_category = (new Subcategory())->instance( - $category_id, - $subcategory_id - ); - - if ($sub_category === null) { - \App\Response\Responses::notFound(trans('entities.subcategory')); - } - - try { - $sub_category->delete(); - - $cache_control->clearPrivateCacheKeys([ - $cache_key->categories($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->categories($resource_type_id) - ]); - } - - \App\Response\Responses::successNoContent(); - } catch (QueryException $e) { - \App\Response\Responses::foreignKeyConstraintError(); - } catch (Exception $e) { - \App\Response\Responses::notFound(trans('entities.subcategory'), $e); - } - } - - /** - * Update the selected subcategory - * - * @param $resource_type_id - * @param $category_id - * @param $subcategory_id - * - * @return JsonResponse - */ - public function update( - $resource_type_id, - $category_id, - $subcategory_id - ): JsonResponse - { - Route\Validate::subcategory( - (int) $resource_type_id, - (int) $category_id, - (int) $subcategory_id, - $this->permitted_resource_types, - true - ); - - $cache_control = new Cache\Control(Auth::user()->id); - $cache_key = new Cache\Key(); - - $subcategory = (new Subcategory())->instance($category_id, $subcategory_id); - - if ($subcategory === null) { - \App\Response\Responses::failedToSelectModelForUpdateOrDelete(); - } - - \App\Request\BodyValidation::checkForEmptyPatch(); - - $validator = (new SubcategoryValidator())->update([ - 'category_id' => (int)$category_id, - 'subcategory_id' => (int)$subcategory_id - ]); - \App\Request\BodyValidation::validateAndReturnErrors($validator); - - \App\Request\BodyValidation::checkForInvalidFields( - array_merge( - (new Subcategory())->patchableFields(), - (new SubcategoryValidator)->dynamicDefinedFields() - ) - ); - - foreach (request()->all() as $key => $value) { - $subcategory->$key = $value; - } - - try { - $subcategory->save(); - - $cache_control->clearPrivateCacheKeys([ - // We need to clear subcategories, resource type items - // and items dur to includes so simpler to clear the entire - // resource type - $cache_key->resourceType($resource_type_id) - ]); - - if (in_array($resource_type_id, $this->public_resource_types, true)) { - $cache_control->clearPublicCacheKeys([ - $cache_key->resourceType($resource_type_id) - ]); - } - } catch (Exception $e) { - \App\Response\Responses::failedToSaveModelForUpdate(); - } - - \App\Response\Responses::successNoContent(); - } } diff --git a/app/Http/Controllers/Summary/CategoryController.php b/app/Http/Controllers/Summary/CategoryView.php similarity index 98% rename from app/Http/Controllers/Summary/CategoryController.php rename to app/Http/Controllers/Summary/CategoryView.php index b75c5190..941ef4e5 100644 --- a/app/Http/Controllers/Summary/CategoryController.php +++ b/app/Http/Controllers/Summary/CategoryView.php @@ -19,7 +19,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class CategoryController extends Controller +class CategoryView extends Controller { /** * Return a summary of the categories diff --git a/app/Http/Controllers/Summary/ItemController.php b/app/Http/Controllers/Summary/ItemView.php similarity index 99% rename from app/Http/Controllers/Summary/ItemController.php rename to app/Http/Controllers/Summary/ItemView.php index 6534e0a5..295e57e3 100644 --- a/app/Http/Controllers/Summary/ItemController.php +++ b/app/Http/Controllers/Summary/ItemView.php @@ -23,7 +23,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class ItemController extends Controller +class ItemView extends Controller { private $model; diff --git a/app/Http/Controllers/Summary/RequestController.php b/app/Http/Controllers/Summary/RequestView.php similarity index 98% rename from app/Http/Controllers/Summary/RequestController.php rename to app/Http/Controllers/Summary/RequestView.php index 57556138..76a46787 100644 --- a/app/Http/Controllers/Summary/RequestController.php +++ b/app/Http/Controllers/Summary/RequestView.php @@ -18,7 +18,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class RequestController extends Controller +class RequestView extends Controller { private $collection_parameters; diff --git a/app/Http/Controllers/Summary/ResourceTypeItemController.php b/app/Http/Controllers/Summary/ResourceTypeItemView.php similarity index 99% rename from app/Http/Controllers/Summary/ResourceTypeItemController.php rename to app/Http/Controllers/Summary/ResourceTypeItemView.php index 261834ff..aca58200 100644 --- a/app/Http/Controllers/Summary/ResourceTypeItemController.php +++ b/app/Http/Controllers/Summary/ResourceTypeItemView.php @@ -24,7 +24,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class ResourceTypeItemController extends Controller +class ResourceTypeItemView extends Controller { private $model; diff --git a/app/Http/Controllers/Summary/ResourceTypeController.php b/app/Http/Controllers/Summary/ResourceTypeView.php similarity index 98% rename from app/Http/Controllers/Summary/ResourceTypeController.php rename to app/Http/Controllers/Summary/ResourceTypeView.php index 703792f6..e330efff 100644 --- a/app/Http/Controllers/Summary/ResourceTypeController.php +++ b/app/Http/Controllers/Summary/ResourceTypeView.php @@ -18,7 +18,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class ResourceTypeController extends Controller +class ResourceTypeView extends Controller { /** * Return a summary of the resource types diff --git a/app/Http/Controllers/Summary/ResourceController.php b/app/Http/Controllers/Summary/ResourceView.php similarity index 98% rename from app/Http/Controllers/Summary/ResourceController.php rename to app/Http/Controllers/Summary/ResourceView.php index 3bf71f25..6ccbb5d8 100644 --- a/app/Http/Controllers/Summary/ResourceController.php +++ b/app/Http/Controllers/Summary/ResourceView.php @@ -19,7 +19,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class ResourceController extends Controller +class ResourceView extends Controller { /** * Return a summary of the resources diff --git a/app/Http/Controllers/Summary/SubcategoryController.php b/app/Http/Controllers/Summary/SubcategoryView.php similarity index 98% rename from app/Http/Controllers/Summary/SubcategoryController.php rename to app/Http/Controllers/Summary/SubcategoryView.php index 5a0a4611..eb560b00 100644 --- a/app/Http/Controllers/Summary/SubcategoryController.php +++ b/app/Http/Controllers/Summary/SubcategoryView.php @@ -19,7 +19,7 @@ * @copyright Dean Blackborough 2018-2020 * @license https://github.com/costs-to-expect/api/blob/master/LICENSE */ -class SubcategoryController extends Controller +class SubcategoryView extends Controller { /** * Return a summary of the subcategories diff --git a/routes/api/private-routes.php b/routes/api/private-routes.php index b10d57b1..bef5f089 100644 --- a/routes/api/private-routes.php +++ b/routes/api/private-routes.php @@ -19,7 +19,7 @@ function () { Route::post( 'resource-types', - 'ResourceTypeController@create' + 'ResourceTypeManage@create' ); Route::post( @@ -29,12 +29,12 @@ function () { Route::post( 'resource-types/{resource_type_id}/categories/{category_id}/subcategories', - 'SubcategoryController@create' + 'SubcategoryManage@create' ); Route::post( 'resource-types/{resource_type_id}/resources', - 'ResourceController@create' + 'ResourceManage@create' ); Route::post( @@ -64,7 +64,7 @@ function () { Route::delete( 'resource-types/{resource_type_id}', - 'ResourceTypeController@delete' + 'ResourceTypeManage@delete' ); Route::delete( @@ -74,7 +74,7 @@ function () { Route::delete( 'resource-types/{resource_type_id}/categories/{category_id}/subcategories/{subcategory_id}', - 'SubcategoryController@delete' + 'SubcategoryManager@delete' ); Route::delete( @@ -84,7 +84,7 @@ function () { Route::delete( 'resource-types/{resource_type_id}/resources/{resource_id}', - 'ResourceController@delete' + 'ResourceManage@delete' ); Route::delete( @@ -104,7 +104,7 @@ function () { Route::patch( 'resource-types/{resource_type_id}', - 'ResourceTypeController@update' + 'ResourceTypeManage@update' ); Route::patch( @@ -114,12 +114,12 @@ function () { Route::patch( 'resource-types/{resource_type_id}/categories/{category_id}/subcategories/{subcategory_id}', - 'SubcategoryController@update' + 'SubcategoryManage@update' ); Route::patch( 'resource-types/{resource_type_id}/resources/{resource_id}', - 'ResourceController@update' + 'ResourceManage@update' ); Route::patch( diff --git a/routes/api/public-routes.php b/routes/api/public-routes.php index 3fae9ddf..63715be5 100644 --- a/routes/api/public-routes.php +++ b/routes/api/public-routes.php @@ -56,22 +56,22 @@ function () { Route::get( 'resource-types', - 'ResourceTypeController@index' + 'ResourceTypeView@index' ); Route::options( 'resource-types', - 'ResourceTypeController@optionsIndex' + 'ResourceTypeView@optionsIndex' ); Route::get( 'resource-types/{resource_type_id}', - 'ResourceTypeController@show' + 'ResourceTypeView@show' ); Route::options( 'resource-types/{resource_type_id}', - 'ResourceTypeController@optionsShow' + 'ResourceTypeView@optionsShow' ); Route::get( @@ -96,32 +96,32 @@ function () { Route::get( 'resource-types/{resource_type_id}/categories/{category_id}/subcategories', - 'SubcategoryController@index' + 'SubcategoryView@index' ); Route::options( 'resource-types/{resource_type_id}/categories/{category_id}/subcategories', - 'SubcategoryController@optionsIndex' + 'SubcategoryView@optionsIndex' ); Route::get( 'resource-types/{resource_type_id}/categories/{category_id}/subcategories/{subcategory_id}', - 'SubcategoryController@show' + 'SubcategoryView@show' ); Route::options( 'resource-types/{resource_type_id}/categories/{category_id}/subcategories/{subcategory_id}', - 'SubcategoryController@optionsShow' + 'SubcategoryView@optionsShow' ); Route::get( 'resource-types/{resource_type_id}/items', - 'ResourceTypeItemController@index' + 'ResourceTypeItemView@index' ); Route::options( 'resource-types/{resource_type_id}/items', - 'ResourceTypeItemController@optionsIndex' + 'ResourceTypeItemView@optionsIndex' ); Route::get( @@ -146,32 +146,32 @@ function () { Route::get( 'resource-types/{resource_type_id}/permitted-users', - 'PermittedUserController@index' + 'PermittedUserView@index' ); Route::options( 'resource-types/{resource_type_id}/permitted-users', - 'PermittedUserController@optionsIndex' + 'PermittedUserView@optionsIndex' ); Route::get( 'resource-types/{resource_type_id}/resources', - 'ResourceController@index' + 'ResourceView@index' ); Route::options( 'resource-types/{resource_type_id}/resources', - 'ResourceController@optionsIndex' + 'ResourceView@optionsIndex' ); Route::get( 'resource-types/{resource_type_id}/resources/{resource_id}', - 'ResourceController@show' + 'ResourceView@show' ); Route::options( 'resource-types/{resource_type_id}/resources/{resource_id}', - 'ResourceController@optionsShow' + 'ResourceView@optionsShow' ); Route::get( @@ -275,27 +275,27 @@ function () { // Request access and error logs Route::options( 'request/error-log', - 'RequestController@optionsErrorLog' + 'RequestView@optionsErrorLog' ); Route::get( 'request/error-log', - 'RequestController@errorLog' + 'RequestView@errorLog' ); Route::post( 'request/error-log', - 'RequestController@createErrorLog' + 'RequestManage@createErrorLog' ); Route::get( 'request/access-log', - 'RequestController@accessLog' + 'RequestView@accessLog' ); Route::options( 'request/access-log', - 'RequestController@optionsAccessLog' + 'RequestView@optionsAccessLog' ); } ); diff --git a/routes/api/public-summary-routes.php b/routes/api/public-summary-routes.php index 7cabdd47..865221ea 100644 --- a/routes/api/public-summary-routes.php +++ b/routes/api/public-summary-routes.php @@ -16,72 +16,72 @@ function () { Route::get( 'summary/resource-types', - 'Summary\ResourceTypeController@index' + 'Summary\ResourceTypeView@index' ); Route::options( 'summary/resource-types', - 'Summary\ResourceTypeController@optionsIndex' + 'Summary\ResourceTypeView@optionsIndex' ); Route::get( 'summary/resource-types/{resource_type_id}/categories', - 'Summary\CategoryController@index' + 'Summary\CategoryView@index' ); Route::options( 'summary/resource-types/{resource_type_id}/categories', - 'Summary\CategoryController@optionsIndex' + 'Summary\CategoryView@optionsIndex' ); Route::get( 'summary/resource-types/{resource_type_id}/categories/{category_id}/subcategories', - 'Summary\SubcategoryController@index' + 'Summary\SubcategoryView@index' ); Route::options( 'summary/resource-types/{resource_type_id}/categories/{category_id}/subcategories', - 'Summary\SubcategoryController@optionsIndex' + 'Summary\SubcategoryView@optionsIndex' ); Route::get( 'summary/resource-types/{resource_type_id}/resources', - 'Summary\ResourceController@index' + 'Summary\ResourceView@index' ); Route::options( 'summary/resource-types/{resource_type_id}/resources', - 'Summary\ResourceController@optionsIndex' + 'Summary\ResourceView@optionsIndex' ); Route::get( 'summary/resource-types/{resource_type_id}/items', - 'Summary\ResourceTypeItemController@index' + 'Summary\ResourceTypeItemView@index' ); Route::options( 'summary/resource-types/{resource_type_id}/items', - 'Summary\ResourceTypeItemController@optionsIndex' + 'Summary\ResourceTypeItemView@optionsIndex' ); Route::get( 'summary/resource-types/{resource_type_id}/resources/{resource_id}/items', - 'Summary\ItemController@index' + 'Summary\ItemView@index' ); Route::options( 'summary/resource-types/{resource_type_id}/resources/{resource_id}/items', - 'Summary\ItemController@optionsIndex' + 'Summary\ItemView@optionsIndex' ); Route::get( 'summary/request/access-log', - 'Summary\RequestController@AccessLog' + 'Summary\RequestView@AccessLog' ); Route::options( 'summary/request/access-log', - 'Summary\RequestController@optionsAccessLog' + 'Summary\RequestView@optionsAccessLog' ); } ); From 37b2f52df2b9eb6cad6e883f60bd6a8f76d59b93 Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Wed, 1 Jul 2020 00:16:05 +0100 Subject: [PATCH 21/24] Fixed route - Route controller name incorrect --- routes/api/private-routes.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routes/api/private-routes.php b/routes/api/private-routes.php index bef5f089..cbed9eeb 100644 --- a/routes/api/private-routes.php +++ b/routes/api/private-routes.php @@ -74,7 +74,7 @@ function () { Route::delete( 'resource-types/{resource_type_id}/categories/{category_id}/subcategories/{subcategory_id}', - 'SubcategoryManager@delete' + 'SubcategoryManage@delete' ); Route::delete( From e39d34edebd86b235497c9cc21becb5e592828f1 Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Wed, 1 Jul 2020 14:49:04 +0100 Subject: [PATCH 22/24] Clear public cache - Publica cache will be cleared when expected. --- app/Http/Controllers/CategoryManage.php | 6 +++--- app/Http/Controllers/ItemCategoryManage.php | 4 ++-- app/Http/Controllers/ItemManage.php | 6 +++--- app/Http/Controllers/ItemPartialTransferManage.php | 4 ++-- app/Http/Controllers/ItemSubcategoryManage.php | 4 ++-- app/Http/Controllers/ItemTransferManage.php | 2 +- app/Http/Controllers/ResourceManage.php | 6 +++--- app/Http/Controllers/ResourceTypeManage.php | 4 ++-- app/Http/Controllers/SubcategoryManage.php | 6 +++--- 9 files changed, 21 insertions(+), 21 deletions(-) diff --git a/app/Http/Controllers/CategoryManage.php b/app/Http/Controllers/CategoryManage.php index 2f716719..de825f0d 100644 --- a/app/Http/Controllers/CategoryManage.php +++ b/app/Http/Controllers/CategoryManage.php @@ -53,7 +53,7 @@ public function create($resource_type_id): JsonResponse $cache_key->categories($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->categories($resource_type_id) ]); @@ -97,7 +97,7 @@ public function delete( $cache_key->categories($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->categories($resource_type_id) ]); @@ -166,7 +166,7 @@ public function update($resource_type_id, $category_id): JsonResponse $cache_key->resourceType($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->resourceType($resource_type_id) ]); diff --git a/app/Http/Controllers/ItemCategoryManage.php b/app/Http/Controllers/ItemCategoryManage.php index 0b13d5b2..4929be68 100644 --- a/app/Http/Controllers/ItemCategoryManage.php +++ b/app/Http/Controllers/ItemCategoryManage.php @@ -72,7 +72,7 @@ public function create( $cache_key->resourceTypeItems($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->items($resource_type_id, $resource_id), $cache_key->resourceTypeItems($resource_type_id) @@ -166,7 +166,7 @@ public function delete( $cache_key->resourceTypeItems($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->items($resource_type_id, $resource_id), $cache_key->resourceTypeItems($resource_type_id) diff --git a/app/Http/Controllers/ItemManage.php b/app/Http/Controllers/ItemManage.php index 248f38aa..ab3e31aa 100644 --- a/app/Http/Controllers/ItemManage.php +++ b/app/Http/Controllers/ItemManage.php @@ -68,7 +68,7 @@ public function create( $cache_key->items($resource_type_id, $resource_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->resourceTypeItems($resource_type_id), $cache_key->items($resource_type_id, $resource_id) @@ -142,7 +142,7 @@ public function update( $cache_key->items($resource_type_id, $resource_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->resourceTypeItems($resource_type_id), $cache_key->items($resource_type_id, $resource_id) @@ -206,7 +206,7 @@ public function delete( $cache_key->items($resource_type_id, $resource_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->resourceTypeItems($resource_type_id), $cache_key->items($resource_type_id, $resource_id) diff --git a/app/Http/Controllers/ItemPartialTransferManage.php b/app/Http/Controllers/ItemPartialTransferManage.php index 048303ea..0f09e1c4 100644 --- a/app/Http/Controllers/ItemPartialTransferManage.php +++ b/app/Http/Controllers/ItemPartialTransferManage.php @@ -55,7 +55,7 @@ public function delete( $cache_key->partialTransfers($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->partialTransfers($resource_type_id) ]); @@ -120,7 +120,7 @@ public function transfer( $cache_key->partialTransfers($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->partialTransfers($resource_type_id) ]); diff --git a/app/Http/Controllers/ItemSubcategoryManage.php b/app/Http/Controllers/ItemSubcategoryManage.php index 2bc3005a..4d241f20 100644 --- a/app/Http/Controllers/ItemSubcategoryManage.php +++ b/app/Http/Controllers/ItemSubcategoryManage.php @@ -83,7 +83,7 @@ public function create( $cache_key->resourceTypeItems($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->items($resource_type_id, $resource_id), $cache_key->resourceTypeItems($resource_type_id) @@ -188,7 +188,7 @@ public function delete( $cache_key->resourceTypeItems($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->items($resource_type_id, $resource_id), $cache_key->resourceTypeItems($resource_type_id) diff --git a/app/Http/Controllers/ItemTransferManage.php b/app/Http/Controllers/ItemTransferManage.php index e7a8f394..7f7a3179 100644 --- a/app/Http/Controllers/ItemTransferManage.php +++ b/app/Http/Controllers/ItemTransferManage.php @@ -76,7 +76,7 @@ public function transfer( $cache_key->transfers($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->transfers($resource_type_id) ]); diff --git a/app/Http/Controllers/ResourceManage.php b/app/Http/Controllers/ResourceManage.php index fadf4e28..76be6694 100644 --- a/app/Http/Controllers/ResourceManage.php +++ b/app/Http/Controllers/ResourceManage.php @@ -57,7 +57,7 @@ public function create(string $resource_type_id): JsonResponse $cache_key->resourceType($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->resourceType($resource_type_id) ]); @@ -102,7 +102,7 @@ public function delete( $cache_key->resourceType($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->resourceType($resource_type_id) ]); @@ -171,7 +171,7 @@ public function update( $cache_key->resourceType($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->resourceType($resource_type_id) ]); diff --git a/app/Http/Controllers/ResourceTypeManage.php b/app/Http/Controllers/ResourceTypeManage.php index 141a113b..8875ae15 100644 --- a/app/Http/Controllers/ResourceTypeManage.php +++ b/app/Http/Controllers/ResourceTypeManage.php @@ -145,7 +145,7 @@ public function delete( $cache_key->permittedUsers($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->resourcesTypes(), $cache_key->permittedUsers($resource_type_id) @@ -216,7 +216,7 @@ public function update( $cache_key->resourcesTypes() ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->resourcesTypes() ]); diff --git a/app/Http/Controllers/SubcategoryManage.php b/app/Http/Controllers/SubcategoryManage.php index 5f3d84ba..766d49c1 100644 --- a/app/Http/Controllers/SubcategoryManage.php +++ b/app/Http/Controllers/SubcategoryManage.php @@ -58,7 +58,7 @@ public function create($resource_type_id, $category_id): JsonResponse $cache_key->categories($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->categories($resource_type_id) ]); @@ -115,7 +115,7 @@ public function delete( $cache_key->categories($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->categories($resource_type_id) ]); @@ -190,7 +190,7 @@ public function update( $cache_key->resourceType($resource_type_id) ]); - if (in_array($resource_type_id, $this->public_resource_types, true)) { + if (in_array((int) $resource_type_id, $this->public_resource_types, true)) { $cache_control->clearPublicCacheKeys([ $cache_key->resourceType($resource_type_id) ]); From f896ab19faae91512d0456cc47843c339bd382f5 Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Wed, 1 Jul 2020 15:48:24 +0100 Subject: [PATCH 23/24] Refactoring - Updated the indexes for hash ids --- app/Http/Controllers/ResourceTypeManage.php | 2 +- app/Http/Controllers/ResourceTypeView.php | 2 +- app/Http/Middleware/ConvertGetParameters.php | 4 +-- .../Middleware/ConvertRouteParameters.php | 14 ++++----- app/Request/Hash.php | 30 +++++++++---------- app/Response/Cache/Key.php | 16 +++++----- config/api/app/hashids.php | 16 +++++----- 7 files changed, 42 insertions(+), 42 deletions(-) diff --git a/app/Http/Controllers/ResourceTypeManage.php b/app/Http/Controllers/ResourceTypeManage.php index 8875ae15..cf70fc76 100644 --- a/app/Http/Controllers/ResourceTypeManage.php +++ b/app/Http/Controllers/ResourceTypeManage.php @@ -59,7 +59,7 @@ public function create(): JsonResponse ]); $permitted_users->save(); - $item_type_id = $this->hash->decode('item_type', request()->input('item_type_id')); + $item_type_id = $this->hash->decode('item-type', request()->input('item_type_id')); if ($item_type_id === false) { \App\Response\Responses::unableToDecode(); diff --git a/app/Http/Controllers/ResourceTypeView.php b/app/Http/Controllers/ResourceTypeView.php index e1bfc093..8162b871 100644 --- a/app/Http/Controllers/ResourceTypeView.php +++ b/app/Http/Controllers/ResourceTypeView.php @@ -225,7 +225,7 @@ private function fieldsData(): array $parameters = ['item_type_id' => []]; foreach ($item_types as $item_type) { - $id = $this->hash->encode('item_type', $item_type['item_type_id']); + $id = $this->hash->encode('item-type', $item_type['item_type_id']); if ($id === false) { \App\Response\Responses::unableToDecode(); diff --git a/app/Http/Middleware/ConvertGetParameters.php b/app/Http/Middleware/ConvertGetParameters.php index dd19f3f9..3bc4a8c4 100644 --- a/app/Http/Middleware/ConvertGetParameters.php +++ b/app/Http/Middleware/ConvertGetParameters.php @@ -27,12 +27,12 @@ public function handle($request, Closure $next) { $config = Config::get('api.app.hashids'); - $min_length = $config['min_length']; + $min_length = $config['min-length']; $parameters = [ 'category' => new Hashids($config['category'], $min_length), 'subcategory' => new Hashids($config['subcategory'], $min_length), - 'resource-type' => new Hashids($config['resource_type'], $min_length), + 'resource-type' => new Hashids($config['resource-type'], $min_length), 'item' => new Hashids($config['item'], $min_length) ]; diff --git a/app/Http/Middleware/ConvertRouteParameters.php b/app/Http/Middleware/ConvertRouteParameters.php index 92beeae8..79b5a6ba 100644 --- a/app/Http/Middleware/ConvertRouteParameters.php +++ b/app/Http/Middleware/ConvertRouteParameters.php @@ -26,19 +26,19 @@ public function handle($request, Closure $next) { $config = Config::get('api.app.hashids'); - $min_length = $config['min_length']; + $min_length = $config['min-length']; $route_params = [ 'category_id' => new Hashids($config['category'], $min_length), 'subcategory_id' => new Hashids($config['subcategory'], $min_length), - 'resource_type_id' => new Hashids($config['resource_type'], $min_length), + 'resource_type_id' => new Hashids($config['resource-type'], $min_length), 'resource_id' => new Hashids($config['resource'], $min_length), 'item_id' => new Hashids($config['item'], $min_length), - 'item_category_id' => new Hashids($config['item_category'], $min_length), - 'item_partial_transfer_id' => new Hashids($config['item_partial_transfer'], $min_length), - 'item_subcategory_id' => new Hashids($config['item_subcategory'], $min_length), - 'item_transfer_id' => new Hashids($config['item_transfer'], $min_length), - 'item_type_id' => new Hashids($config['item_type'], $min_length), + 'item_category_id' => new Hashids($config['item-category'], $min_length), + 'item_partial_transfer_id' => new Hashids($config['item-partial-transfer'], $min_length), + 'item_subcategory_id' => new Hashids($config['item-subcategory'], $min_length), + 'item_transfer_id' => new Hashids($config['item-transfer'], $min_length), + 'item_type_id' => new Hashids($config['item-type'], $min_length), ]; $params_to_convert = array_keys($route_params); diff --git a/app/Request/Hash.php b/app/Request/Hash.php index 4501804e..0a2e70d3 100644 --- a/app/Request/Hash.php +++ b/app/Request/Hash.php @@ -35,19 +35,19 @@ private function setUp(): void { $config = Config::get('api.app.hashids'); - $min_length = $config['min_length']; + $min_length = $config['min-length']; $this->hashers['category'] = new Hashids($config['category'], $min_length); $this->hashers['subcategory'] = new Hashids($config['subcategory'], $min_length); - $this->hashers['resource_type'] = new Hashids($config['resource_type'], $min_length); + $this->hashers['resource-type'] = new Hashids($config['resource-type'], $min_length); $this->hashers['resource'] = new Hashids($config['resource'], $min_length); $this->hashers['item'] = new Hashids($config['item'], $min_length); - $this->hashers['item_category'] = new Hashids($config['item_category'], $min_length); - $this->hashers['item_partial_transfer'] = new Hashids($config['item_partial_transfer'], $min_length); - $this->hashers['item_subcategory'] = new Hashids($config['item_subcategory'], $min_length); - $this->hashers['item_transfer'] = new Hashids($config['item_transfer'], $min_length); - $this->hashers['item_type'] = new Hashids($config['item_type'], $min_length); - $this->hashers['permitted_user'] = new Hashids($config['permitted_user'], $min_length); + $this->hashers['item-category'] = new Hashids($config['item-category'], $min_length); + $this->hashers['item-partial-transfer'] = new Hashids($config['item-partial-transfer'], $min_length); + $this->hashers['item-subcategory'] = new Hashids($config['item-subcategory'], $min_length); + $this->hashers['item-transfer'] = new Hashids($config['item-transfer'], $min_length); + $this->hashers['item-type'] = new Hashids($config['item-type'], $min_length); + $this->hashers['permitted-user'] = new Hashids($config['permitted-user'], $min_length); $this->hashers['user'] = new Hashids($config['user'], $min_length); } @@ -113,7 +113,7 @@ public function subCategory(): Hashids */ public function resourceType(): Hashids { - return $this->hashers['resource_type']; + return $this->hashers['resource-type']; } /** @@ -143,7 +143,7 @@ public function item(): Hashids */ public function itemCategory(): Hashids { - return $this->hashers['item_category']; + return $this->hashers['item-category']; } /** @@ -153,7 +153,7 @@ public function itemCategory(): Hashids */ public function itemPartialTransfer(): Hashids { - return $this->hashers['item_partial_transfer']; + return $this->hashers['item-partial-transfer']; } /** @@ -163,7 +163,7 @@ public function itemPartialTransfer(): Hashids */ public function itemSubCategory(): Hashids { - return $this->hashers['item_subcategory']; + return $this->hashers['item-subcategory']; } /** @@ -173,7 +173,7 @@ public function itemSubCategory(): Hashids */ public function itemTransfer(): Hashids { - return $this->hashers['item_transfer']; + return $this->hashers['item-transfer']; } /** @@ -183,7 +183,7 @@ public function itemTransfer(): Hashids */ public function itemType(): Hashids { - return $this->hashers['item_type']; + return $this->hashers['item-type']; } /** @@ -193,7 +193,7 @@ public function itemType(): Hashids */ public function permittedUser(): Hashids { - return $this->hashers['permitted_user']; + return $this->hashers['permitted-user']; } /** diff --git a/app/Response/Cache/Key.php b/app/Response/Cache/Key.php index 8fe66b96..8618c0b3 100644 --- a/app/Response/Cache/Key.php +++ b/app/Response/Cache/Key.php @@ -22,7 +22,7 @@ public function __construct() public function categories(int $resource_type_id): string { return '/v2/resource-types/' . - $this->hash->encode('resource_type', $resource_type_id) . + $this->hash->encode('resource-type', $resource_type_id) . '/categories'; } @@ -35,7 +35,7 @@ public function categories(int $resource_type_id): string public function items(int $resource_type_id, int $resource_id): string { return '/v2/resource-types/' . - $this->hash->encode('resource_type', $resource_type_id) . + $this->hash->encode('resource-type', $resource_type_id) . '/resources/' . $this->hash->encode('resource', $resource_id) . '/items'; } @@ -60,7 +60,7 @@ public function partialTransfers(int $resource_type_id): string public function permittedUsers(int $resource_type_id): string { return '/v2/resource-types/' . - $this->hash->encode('resource_type', $resource_type_id) . + $this->hash->encode('resource-type', $resource_type_id) . '/permitted-users'; } @@ -72,7 +72,7 @@ public function permittedUsers(int $resource_type_id): string public function resources(int $resource_type_id): string { return '/v2/resource-types/' . - $this->hash->encode('resource_type', $resource_type_id) . + $this->hash->encode('resource-type', $resource_type_id) . '/resources'; } @@ -84,7 +84,7 @@ public function resources(int $resource_type_id): string public function resourceTypeItems(int $resource_type_id): string { return '/v2/resource-types/' . - $this->hash->encode('resource_type', $resource_type_id) . + $this->hash->encode('resource-type', $resource_type_id) . '/items'; } @@ -96,7 +96,7 @@ public function resourceTypeItems(int $resource_type_id): string public function resourceType(int $resource_type_id): string { return '/v2/resource-types/' . - $this->hash->encode('resource_type', $resource_type_id); + $this->hash->encode('resource-type', $resource_type_id); } /** @@ -116,7 +116,7 @@ public function resourcesTypes(): string public function subcategories(int $resource_type_id, int $category_id): string { return '/v2/resource-types/' . - $this->hash->encode('resource_type', $resource_type_id) . + $this->hash->encode('resource-type', $resource_type_id) . '/categories/' . $this->hash->encode('category', $category_id) . '/subcategories'; } @@ -129,7 +129,7 @@ public function subcategories(int $resource_type_id, int $category_id): string public function transfers(int $resource_type_id): string { return '/v2/resource-types/' . - $this->hash->encode('resource_type', $resource_type_id) . + $this->hash->encode('resource-type', $resource_type_id) . '/transfers'; } } diff --git a/config/api/app/hashids.php b/config/api/app/hashids.php index 9629171a..901a8edf 100644 --- a/config/api/app/hashids.php +++ b/config/api/app/hashids.php @@ -3,17 +3,17 @@ declare(strict_types=1); return [ - 'min_length' => env('APP_HASH_MIN_LENGTH'), + 'min-length' => env('APP_HASH_MIN_LENGTH'), 'category' => env('APP_HASH_SALT_CATEGORY'), 'subcategory' => env('APP_HASH_SALT_SUBCATEGORY'), - 'resource_type' => env('APP_HASH_SALT_RESOURCE_TYPE'), + 'resource-type' => env('APP_HASH_SALT_RESOURCE_TYPE'), 'resource' => env('APP_HASH_SALT_RESOURCE'), 'item' => env('APP_HASH_SALT_ITEM'), - 'item_category' => env('APP_HASH_SALT_ITEM_CATEGORY'), - 'item_partial_transfer' => env('APP_HASH_SALT_ITEM_PARTIAL_TRANSFER'), - 'item_subcategory' => env('APP_HASH_SALT_ITEM_SUBCATEGORY'), - 'item_transfer' => env('APP_HASH_SALT_ITEM_TRANSFER'), - 'item_type' => env('APP_HASH_SALT_ITEM_TYPE'), - 'permitted_user' => env('APP_HASH_SALT_PERMITTED_USER'), + 'item-category' => env('APP_HASH_SALT_ITEM_CATEGORY'), + 'item-partial-transfer' => env('APP_HASH_SALT_ITEM_PARTIAL_TRANSFER'), + 'item-subcategory' => env('APP_HASH_SALT_ITEM_SUBCATEGORY'), + 'item-transfer' => env('APP_HASH_SALT_ITEM_TRANSFER'), + 'item-type' => env('APP_HASH_SALT_ITEM_TYPE'), + 'permitted-user' => env('APP_HASH_SALT_PERMITTED_USER'), 'user' => env('APP_HASH_SALT_USER') ]; From 95cb21600b89b5f5ea49ebb689db26e66a5a82aa Mon Sep 17 00:00:00 2001 From: Dean Blackborough Date: Wed, 1 Jul 2020 15:55:37 +0100 Subject: [PATCH 24/24] Release - Release v2.11.6 of the Costs to Expect API --- CHANGELOG.md | 18 ++++++++++++++++++ config/api/app/version.php | 4 ++-- resources/views/welcome.blade.php | 20 +++++++++++--------- 3 files changed, 31 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b6c1b30d..53030976 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,24 @@ The complete changelog for the Costs to Expect REST API, our changelog follows the format defined at https://keepachangelog.com/en/1.0.0/ +## [v2.11.6] - 2020-07-01 +### Added +- We have added support for an `X-Skip-Cache` request header; If you include the header with your request we will skip response caching and fetch live values, please use this with care. + +### Changed +- We have added separate links for the documentation and example page and the postman collection. +- We have simplified our `\Model\Transformer` classes and made it possible to alter the returned data format. +- We have added `public` as a sorting option for resource types. +- We have reworked our pagination class; we have moved it to a new workspace and also improved how it works. +- We have moved our `Hash` class; the `Hash` class now lives in the `Request` namespace. +- We have moved our `ModelUtility` class: the `ModelUtility` class now lives in the `Models` namespace. +- We have updated the indexes in our `Hash` request class; the indexes are consistent with the rest of the app. + +### Fixed +- We have updated our pagination helper to include any defined filtering parameters. +- We have corrected pagination calls in all our controllers; we now include all possible request parameters. +- We have corrected calls to clear public caches; we were comparing different types. + ## [v2.11.5] - 2020-06-24 ### Added - We have added a documentation page; the documentation page links to the API documentation and includes a couple of examples. diff --git a/config/api/app/version.php b/config/api/app/version.php index 79dbd743..283057b5 100644 --- a/config/api/app/version.php +++ b/config/api/app/version.php @@ -3,9 +3,9 @@ declare(strict_types=1); return [ - 'version'=> 'v2.11.5', + 'version'=> 'v2.11.6', 'prefix' => 'v2', - 'release_date' => '2020-06-24', + 'release_date' => '2020-07-01', 'changelog' => [ 'api' => '/v2/changelog', 'markdown' => 'https://github.com/costs-to-expect/api/blob/master/CHANGELOG.md' diff --git a/resources/views/welcome.blade.php b/resources/views/welcome.blade.php index 0727664f..66abc2d1 100644 --- a/resources/views/welcome.blade.php +++ b/resources/views/welcome.blade.php @@ -223,25 +223,27 @@ function gtag(){dataLayer.push(arguments);}

Added

    -
  • We have added a documentation page; the documentation page links to the API documentation and includes a couple of examples. - Changed
  • +
  • We have added support for an `X-Skip-Cache` request header; If you include the header with your request we will skip response caching and fetch live values, please use this with care.

Changed

    -
  • We have updated the example ENV file.
  • -
  • We have renamed a couple of our helper conversion/validation classes and moved them to a new namespace.
  • -
  • We have made a minor content tweak on the landing page; the documentation button is in another section.
  • -
  • We have updated and relocated our validation classes; the validation classes are now part of the `App\Request\Validate` namespace.
  • -
  • We have reworked our summary controllers; we have removed some code duplication and added additional error checking.
  • +
  • We have added separate links for the documentation and example page and the postman collection.
  • +
  • We have simplified our `\Model\Transformer` classes and made it possible to alter the returned data format.
  • +
  • We have added `public` as a sorting option for resource types.
  • +
  • We have reworked our pagination class; we have moved it to a new workspace and also improved how it works.
  • +
  • We have moved our `Hash` class; the `Hash` class now lives in the `Request` namespace.
  • +
  • We have moved our `ModelUtility` class: the `ModelUtility` class now lives in the `Models` namespace.
  • +
  • We have updated the indexes in our `Hash` request class; the indexes are consistent with the rest of the app.

Fixed

    -
  • Incorrectly assuming the result will be an array with at least one value.
  • -
  • We have fixed an error in the changelog; we jump a couple of minor versions.
  • +
  • We have updated our pagination helper to include any defined filtering parameters.
  • +
  • We have corrected pagination calls in all our controllers; we now include all possible request parameters.
  • +
  • We have corrected calls to clear public caches; we were comparing different types.