CakeProducts/src/Controller/ProductPhotosController.php

203 lines
8.0 KiB
PHP

<?php
declare(strict_types=1);
namespace CakeProducts\Controller;
use Cake\Core\Configure;
use Cake\Datasource\Exception\RecordNotFoundException;
use Cake\Http\Exception\ForbiddenException;
use Cake\Http\Response;
use Cake\Utility\Text;
use CakeProducts\Controller\AppController;
use CakeProducts\Model\Table\ProductPhotosTable;
use CheeseCake\Controller\Traits\OverrideTableTrait;
use Psr\Http\Message\UploadedFileInterface;
/**
* ProductPhotos Controller
*
* @property ProductPhotosTable $ProductPhotos
*/
class ProductPhotosController extends AppController
{
use OverrideTableTrait;
/**
* Index method
*
* @return Response|null|void Renders view
*/
public function index()
{
$query = $this->getTable()->find()
->contain(['Products', 'ProductSkus']);
$productPhotos = $this->paginate($query);
$this->set(compact('productPhotos'));
}
/**
* View method
*
* @param string|null $id Product Photo id.
* @return Response|null|void Renders view
* @throws RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$productPhoto = $this->getTable()->get($id, contain: ['Products', 'ProductSkus', 'ProductCategories']);
$this->set(compact('productPhoto'));
}
/**
* Add method
*
* @return Response|null|void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$productPhotosTable = $this->getTable();
$productPhoto = $productPhotosTable->newEmptyEntity();
if ($this->request->is('post')) {
if (!$this->request->getData('photo')) {
$this->Flash->error('Photo is required. Nothing was uploaded. Please try again.');
$productCategory = $productPhoto->product_category_id ? $productPhotosTable->ProductCategories->find()->where(['internal_id' => $productPhoto->product_category_id ?? '-1'])->first() : null;
$productCatalogs = $productPhotosTable->ProductCategories->ProductCatalogs->find('list')->toArray();
$this->set(compact('productPhoto', 'productCatalogs', 'productCategory'));
return;
}
$uuid = Text::uuid();
$postData = $this->request->getData();
$postData['id'] = $uuid;
$baseDir = Configure::readOrFail('CakeProducts.photos.directory');
$path = '';
if ($this->request->getData('product_sku_id')) {
$productSku = $productPhotosTable->ProductSkus
->find()
->contain(['Products', 'Products.ProductCategories'])
->where([
'ProductSkus.id' => $this->request->getData('product_sku_id'),
])
->first();
$path = $productSku ? $productSku->product_id . DS . 'skus' . DS . $productSku->id : $path;
} else if ($this->request->getData('product_id')) {
$product = $productPhotosTable->Products
->find()
->contain(['ProductCategories'])
->where([
'Products.id' => $this->request->getData('product_id'),
])
->first();
$path = $product ? $product->id : $path;
} else if ($this->request->getData('product_category_id')) {
$categoryId = $this->request->getData('product_category_id');
$field = is_integer($categoryId) ? 'ProductCategories.id' : 'ProductCategories.internal_id';
$productCategoryPosted = $productPhotosTable->ProductCategories
->find()
->where([
$field => $categoryId,
])
->first();
$postData['product_category_id'] = $productCategoryPosted->internal_id ?? null;
$path = $productCategoryPosted ? 'categories' : $path;
}
/**
* @var UploadedFileInterface $photoObject
*/
$photoObject = $this->request->getData('photo');
$fullPath = $baseDir . $path;
if (!file_exists($fullPath)) {
if (!mkdir($fullPath, 0777, true)) {
throw new ForbiddenException('Failed to create the required folders. Please check the folder permissions and try again.');
}
}
$destination = $fullPath . DS . $uuid;
// Existing files with the same name will be replaced.
$photoObject->moveTo($destination);
if (!file_exists($destination)) {
throw new ForbiddenException('Failed to move the uploaded image to the appropriate folder. Please try again.');
}
$postData['photo_dir'] = $path;
$postData['photo_filename'] = $uuid;
$productPhoto = $productPhotosTable->patchEntity($productPhoto, $postData);
if ($productPhotosTable->save($productPhoto)) {
$this->Flash->success(__('The product photo has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The product photo could not be saved. Please, try again.'));
}
$productCategory = $productPhoto->product_category_id ? $productPhotosTable->ProductCategories->find()->where(['internal_id' => $productPhoto->product_category_id ?? '-1'])->first() : null;
$productCatalogs = $productPhotosTable->ProductCategories->ProductCatalogs->find('list')->toArray();
$this->set(compact('productPhoto', 'productCatalogs', 'productCategory'));
}
/**
* Edit method
*
* @param string|null $id Product Photo id.
* @return Response|null|void Redirects on successful edit, renders view otherwise.
* @throws RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$productPhotosTable = $this->getTable();
$productPhoto = $productPhotosTable->get($id, contain: []);
if ($this->request->is(['patch', 'post', 'put'])) {
$postData = $this->request->getData();
$productPhoto = $productPhotosTable->patchEntity($productPhoto, $postData);
if ($productPhotosTable->save($productPhoto)) {
$this->Flash->success(__('The product photo has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The product photo could not be saved. Please, try again.'));
}
$products = $productPhotosTable->Products->find('list', limit: 200)->all();
$productSkus = $productPhotosTable->ProductSkus->find('list', limit: 200)->all();
$this->set(compact('productPhoto', 'products', 'productSkus'));
}
/**
* Delete method
*
* @param string|null $id Product Photo id.
* @return Response|null Redirects to index.
* @throws RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$productPhotosTable = $this->getTable();
$productPhoto = $productPhotosTable->get($id);
if ($productPhotosTable->delete($productPhoto)) {
$this->Flash->success(__('The product photo has been deleted.'));
} else {
$this->Flash->error(__('The product photo could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
/**
* @param $id
* @return Response
*/
public function image($id = null)
{
$productPhoto = $this->getTable()->get($id);
$fullPath = Configure::readOrFail('CakeProducts.photos.directory') . $productPhoto->photo_dir . DS . $productPhoto->photo_filename;
return $this->response->withFile($fullPath, [
'download' => $this->request->getQuery('download', false) === '1'
]);
}
}