phpcbf and added .gitea workflows

This commit is contained in:
2026-01-23 20:32:22 -08:00
parent 4b45725b33
commit a033c13b8d
24 changed files with 949 additions and 919 deletions

View File

@@ -13,9 +13,9 @@ use Cake\Routing\RouteBuilder;
/**
* Plugin for CakeCarts
*/
class CakeCartsPlugin extends BasePlugin
{
/**
class CakeCartsPlugin extends BasePlugin {
/**
* Load all the plugin configuration and bootstrap logic.
*
* The host application is provided as an argument. This allows you to load
@@ -24,12 +24,11 @@ class CakeCartsPlugin extends BasePlugin
* @param \Cake\Core\PluginApplicationInterface $app The host application
* @return void
*/
public function bootstrap(PluginApplicationInterface $app): void
{
// remove this method hook if you don't need it
}
public function bootstrap(PluginApplicationInterface $app): void {
// remove this method hook if you don't need it
}
/**
/**
* Add routes for the plugin.
*
* If your plugin has many routes and you would like to isolate them into a separate file,
@@ -38,62 +37,59 @@ class CakeCartsPlugin extends BasePlugin
* @param \Cake\Routing\RouteBuilder $routes The route builder to update.
* @return void
*/
public function routes(RouteBuilder $routes): void
{
// remove this method hook if you don't need it
$routes->plugin(
'CakeCarts',
['path' => '/cake-carts'],
function (RouteBuilder $builder) {
// Add custom routes here
$builder->connect('/wishlist', ['controller' => 'CakeCarts', 'action' => 'wishlist']);
public function routes(RouteBuilder $routes): void {
// remove this method hook if you don't need it
$routes->plugin(
'CakeCarts',
['path' => '/cake-carts'],
function (RouteBuilder $builder) {
// Add custom routes here
$builder->connect('/wishlist', ['controller' => 'CakeCarts', 'action' => 'wishlist']);
$builder->fallbacks();
}
);
parent::routes($routes);
}
$builder->fallbacks();
},
);
parent::routes($routes);
}
/**
/**
* Add middleware for the plugin.
*
* @param \Cake\Http\MiddlewareQueue $middlewareQueue The middleware queue to update.
* @return \Cake\Http\MiddlewareQueue
*/
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
{
// Add your middlewares here
// remove this method hook if you don't need it
public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue {
// Add your middlewares here
// remove this method hook if you don't need it
return $middlewareQueue;
}
return $middlewareQueue;
}
/**
/**
* Add commands for the plugin.
*
* @param \Cake\Console\CommandCollection $commands The command collection to update.
* @return \Cake\Console\CommandCollection
*/
public function console(CommandCollection $commands): CommandCollection
{
// Add your commands here
// remove this method hook if you don't need it
public function console(CommandCollection $commands): CommandCollection {
// Add your commands here
// remove this method hook if you don't need it
$commands = parent::console($commands);
$commands = parent::console($commands);
return $commands;
}
return $commands;
}
/**
/**
* Register application container services.
*
* @link https://book.cakephp.org/5/en/development/dependency-injection.html#dependency-injection
* @param \Cake\Core\ContainerInterface $container The Container to update.
* @return void
* @link https://book.cakephp.org/5/en/development/dependency-injection.html#dependency-injection
*/
public function services(ContainerInterface $container): void
{
// Add your services here
// remove this method hook if you don't need it
}
public function services(ContainerInterface $container): void {
// Add your services here
// remove this method hook if you don't need it
}
}

View File

@@ -5,6 +5,5 @@ namespace CakeCarts\Controller;
use App\Controller\AppController as BaseController;
class AppController extends BaseController
{
class AppController extends BaseController {
}

View File

@@ -4,10 +4,7 @@ declare(strict_types=1);
namespace CakeCarts\Controller;
use Cake\Core\Configure;
use Cake\Datasource\Exception\RecordNotFoundException;
use Cake\Http\Client;
use Cake\Log\Log;
use CakeCarts\Controller\AppController;
/**
* CartItems Controller
@@ -15,148 +12,148 @@ use CakeCarts\Controller\AppController;
* @property \CakeCarts\Model\Table\CartItemsTable $CartItems
* @property \Authorization\Controller\Component\AuthorizationComponent $Authorization
*/
class CartItemsController extends AppController
{
public function initialize(): void
{
parent::initialize(); // TODO: Change the autogenerated stub
class CartItemsController extends AppController {
if (!$this->components()->has('ShoppingCart')) {
$this->loadComponent('CakeCarts.ShoppingCart', [
// This is default config. You can modify "actions" as needed to make
// component work only for specified methods.
'actions' => ['add'],
]);
}
/**
* @return void
*/
public function initialize(): void {
parent::initialize(); // TODO: Change the autogenerated stub
if ($this->components()->has('Authorization')) {
$this->Authorization->skipAuthorization();
}
}
if (!$this->components()->has('ShoppingCart')) {
$this->loadComponent('CakeCarts.ShoppingCart', [
// This is default config. You can modify "actions" as needed to make
// component work only for specified methods.
'actions' => ['add'],
]);
}
/**
if ($this->components()->has('Authorization')) {
$this->Authorization->skipAuthorization();
}
}
/**
* Add method
*
* @return \Cake\Http\Response|null|void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$this->request->allowMethod(['post', 'put', 'patch']);
public function add() {
$this->request->allowMethod(['post', 'put', 'patch']);
Log::debug(print_r('$this->request->getData()', true));
Log::debug(print_r($this->request->getData(), true));
$cart = $this->viewBuilder()->getVar('cart');
$postData = $this->request->getData();
$postData['cart_id'] = $cart->id;
// get product skus with variants
$price = $this->request->getData('price');
$qty = $this->request->getData('qty', 1);
$postData['price'] = $price;
$postData['subtotal'] = isset($price) ? bcmul("$price", "$qty", 5) : null;
Log::debug(print_r('$this->request->getData()', true));
Log::debug(print_r($this->request->getData(), true));
$cart = $this->viewBuilder()->getVar('cart');
$postData = $this->request->getData();
$postData['cart_id'] = $cart->id;
// get product skus with variants
$price = $this->request->getData('price');
$qty = $this->request->getData('qty', 1);
$postData['price'] = $price;
$postData['subtotal'] = isset($price) ? bcmul("$price", "$qty", 5) : null;
$newCartItem = $this->CartItems->newEntity($postData, [
'validate' => Configure::readOrFail('CakeCarts.CartItems.requirePricing') ? 'requirePricing' : 'default',
]);
$newCartItem = $this->CartItems->newEntity($postData, [
'validate' => Configure::readOrFail('CakeCarts.CartItems.requirePricing') ? 'requirePricing' : 'default',
]);
if ($this->CartItems->save($newCartItem)) {
$this->Flash->success('Added to cart');
if ($this->CartItems->save($newCartItem)) {
$this->Flash->success('Added to cart');
return $this->redirect($this->referer([
'plugin' => 'CakeCarts',
'controller' => 'CartItems',
'action' => 'index'
]));
}
return $this->redirect($this->referer([
'plugin' => 'CakeCarts',
'controller' => 'CartItems',
'action' => 'index',
]));
}
// Log::debug(print_r('$newCartItem->getErrors()', true));
// Log::debug(print_r($newCartItem->getErrors(), true));
$this->Flash->error('Failed to add to cart.');
$this->Flash->error('Failed to add to cart.');
return $this->redirect($this->referer([
'plugin' => 'CakeCarts',
'controller' => 'CartItems',
'action' => 'index'
]));
}
return $this->redirect($this->referer([
'plugin' => 'CakeCarts',
'controller' => 'CartItems',
'action' => 'index',
]));
}
/**
/**
* Edit method
*
* @param string|null $id Cart Item id.
* @return \Cake\Http\Response|null|void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
* @return \Cake\Http\Response|null|void Redirects on successful edit, renders view otherwise.
*/
public function edit($id = null)
{
$this->request->allowMethod(['post', 'put', 'patch']);
public function edit($id = null) {
$this->request->allowMethod(['post', 'put', 'patch']);
$cartItem = $this->CartItems->find()
->where(['CartItems.id' => $id])
->contain(['Carts'])
->firstOrFail();
$cartItem = $this->CartItems->find()
->where(['CartItems.id' => $id])
->contain(['Carts'])
->firstOrFail();
$this->ShoppingCart->checkIfIsOwnCart($cartItem->cart);
$this->ShoppingCart->checkIfIsOwnCart($cartItem->cart);
if ($this->request->is(['patch', 'post', 'put'])) {
$postData = $this->request->getData();
$qty = $this->request->getData('qty', 1);
$price = $this->request->getData('price', null);
$subtotal = isset($price) ? bcmul("$qty", "$price", 5) : null;
$postData['subtotal'] = $subtotal;
$cartItem = $this->CartItems->patchEntity($cartItem, $postData, [
'validate' => Configure::readOrFail('CakeCarts.CartItems.requirePricing') ? 'requiresPricing' : 'default',
]);
if ($this->CartItems->save($cartItem)) {
$this->Flash->success(__('The cart item has been saved.'));
if ($this->request->is(['patch', 'post', 'put'])) {
$postData = $this->request->getData();
$qty = $this->request->getData('qty', 1);
$price = $this->request->getData('price', null);
$subtotal = isset($price) ? bcmul("$qty", "$price", 5) : null;
$postData['subtotal'] = $subtotal;
$cartItem = $this->CartItems->patchEntity($cartItem, $postData, [
'validate' => Configure::readOrFail('CakeCarts.CartItems.requirePricing') ? 'requiresPricing' : 'default',
]);
if ($this->CartItems->save($cartItem)) {
$this->Flash->success(__('The cart item has been saved.'));
return $this->redirect($this->referer([
'plugin' => 'CakeCarts',
'controller' => 'CartItems',
'action' => 'index'
]));
}
Log::debug(print_r('$cartItem->getErrors()', true));
Log::debug(print_r($cartItem->getErrors(), true));
$this->Flash->error(__('The cart item could not be saved. Please, try again.'));
}
return $this->redirect($this->referer([
'plugin' => 'CakeCarts',
'controller' => 'CartItems',
'action' => 'index',
]));
}
Log::debug(print_r('$cartItem->getErrors()', true));
Log::debug(print_r($cartItem->getErrors(), true));
$this->Flash->error(__('The cart item could not be saved. Please, try again.'));
}
return $this->redirect($this->referer([
'plugin' => 'CakeCarts',
'controller' => 'CartItems',
'action' => 'index'
]));
}
return $this->redirect($this->referer([
'plugin' => 'CakeCarts',
'controller' => 'CartItems',
'action' => 'index',
]));
}
/**
/**
* Delete method
*
* @param string|null $id Cart Item id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
* @return \Cake\Http\Response|null Redirects to index.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$identity = $this->getRequest()->getAttribute('identity');
public function delete($id = null) {
$this->request->allowMethod(['post', 'delete']);
$identity = $this->getRequest()->getAttribute('identity');
// $cart = $this->viewBuilder()->getVar('cart');
$cartItem = $this->CartItems->find()
->where(['CartItems.id' => $id])
->contain(['Carts'])
->firstOrFail();
$cartItem = $this->CartItems->find()
->where(['CartItems.id' => $id])
->contain(['Carts'])
->firstOrFail();
$this->ShoppingCart->checkIfIsOwnCart($cartItem->cart);
$this->ShoppingCart->checkIfIsOwnCart($cartItem->cart);
unset($cartItem->cart);
if ($this->CartItems->delete($cartItem)) {
$this->Flash->success(__('The cart item has been deleted.'));
} else {
$this->Flash->error(__('The cart item could not be deleted. Please, try again.'));
}
unset($cartItem->cart);
if ($this->CartItems->delete($cartItem)) {
$this->Flash->success(__('The cart item has been deleted.'));
} else {
$this->Flash->error(__('The cart item could not be deleted. Please, try again.'));
}
return $this->redirect($this->referer([
'plugin' => 'CakeCarts',
'controller' => 'CartItems',
'action' => 'index',
]));
}
return $this->redirect($this->referer([
'plugin' => 'CakeCarts',
'controller' => 'CartItems',
'action' => 'index'
]));
}
}

View File

@@ -4,37 +4,36 @@ declare(strict_types=1);
namespace CakeCarts\Controller;
use App\Controller\AppController;
use Cake\Core\Configure;
use Cake\Event\EventInterface;
use CakeCarts\Model\Enum\CartTypeId;
/**
* Carts Controller
*
* @property \Authorization\Controller\Component\AuthorizationComponent $Authorization
*/
class CartsController extends AppController
{
public function initialize(): void
{
parent::initialize(); // TODO: Change the autogenerated stub
class CartsController extends AppController {
if (!$this->components()->has('ShoppingCart')) {
$this->loadComponent('CakeCarts.ShoppingCart', [
// This is default config. You can modify "actions" as needed to make
// component work only for specified methods.
'actions' => true,
]);
}
}
/**
* @return void
*/
public function initialize(): void {
parent::initialize(); // TODO: Change the autogenerated stub
/**
if (!$this->components()->has('ShoppingCart')) {
$this->loadComponent('CakeCarts.ShoppingCart', [
// This is default config. You can modify "actions" as needed to make
// component work only for specified methods.
'actions' => true,
]);
}
}
/**
* Index method
*
* @return \Cake\Http\Response|null|void Renders view
*/
public function index()
{
// use cart from beforeFilter
}
public function index() {
// use cart from beforeFilter
}
}

View File

@@ -10,159 +10,156 @@ use Cake\Datasource\Exception\RecordNotFoundException;
use Cake\Event\EventInterface;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use CakeCarts\Model\Entity\CartItem;
use CakeCarts\Model\Enum\CartTypeId;
use CakeCarts\Model\Table\CartsTable;
/**
* ShoppingCart component
*/
class ShoppingCartComponent extends Component
{
/**
class ShoppingCartComponent extends Component {
/**
* @var string $userIdField
*/
protected string $userIdField;
protected string $userIdField;
/**
* @var CartsTable|Table $Carts
/**
* @var \CakeCarts\Model\Table\CartsTable|\Cake\ORM\Table $Carts
*/
protected CartsTable|Table $Carts;
protected CartsTable|Table $Carts;
/**
* @return void
*/
public function initialize(array $config): void {
parent::initialize($config); // TODO: Change the autogenerated stub
public function initialize(array $config): void
{
parent::initialize($config); // TODO: Change the autogenerated stub
$this->userIdField = Configure::readOrFail('CakeCarts.Users.user_id') === 'uuid' ? 'user_id_uuid' : 'user_id';
$this->Carts = TableRegistry::getTableLocator()->get(Configure::readOrFail('CakeCarts.Carts.table'));
}
$this->userIdField = Configure::readOrFail('CakeCarts.Users.user_id') === 'uuid' ? 'user_id_uuid' : 'user_id';
$this->Carts = TableRegistry::getTableLocator()->get(Configure::readOrFail('CakeCarts.Carts.table'));
}
/**
/**
* Default configuration.
*
* @var array<string, mixed>
*/
protected array $_defaultConfig = [];
protected array $_defaultConfig = [];
public function beforeFilter(EventInterface $event): void
{
if (!$this->_isActionEnabled()) {
return;
}
/**
* @return void
*/
public function beforeFilter(EventInterface $event): void {
if (!$this->_isActionEnabled()) {
return;
}
$sessionId = $this->getSessionId();
$cart = $this->findExistingCartOrCreate($sessionId);
$sessionId = $this->getSessionId();
$cart = $this->findExistingCartOrCreate($sessionId);
$this->getController()->set(compact('cart'));
}
$this->getController()->set(compact('cart'));
}
/**
/**
* @param string $cartId
*
* @return mixed
*/
public function getCartForUserById(string $cartId)
{
$identity = $this->getController()->getRequest()->getAttribute('identity');
$sessionId = $this->getSessionId();
public function getCartForUserById(string $cartId) {
$identity = $this->getController()->getRequest()->getAttribute('identity');
$sessionId = $this->getSessionId();
$cartsQ = $this->Carts
->find()
->contain(['CartItems'])
->where(['Carts.id' => $cartId]);
if ($identity) {
$cartsQ->where([$this->userIdField => $identity->getIdentifier()]);
} else {
$cartsQ->where(['session_id' => $sessionId]);
}
$cartsQ = $this->Carts
->find()
->contain(['CartItems'])
->where(['Carts.id' => $cartId]);
if ($identity) {
$cartsQ->where([$this->userIdField => $identity->getIdentifier()]);
} else {
$cartsQ->where(['session_id' => $sessionId]);
}
return $cartsQ->firstOrFail();
}
return $cartsQ->firstOrFail();
}
public function findExistingCartOrCreate(string $sessionId, int $cartTypeId = null)
{
$identity = $this->getController()->getRequest()->getAttribute('identity');
public function findExistingCartOrCreate(string $sessionId, int|null $cartTypeId = null) {
$identity = $this->getController()->getRequest()->getAttribute('identity');
$cartTypeId = $cartTypeId ?? CartTypeId::Cart->value;
$cartTypeId = $cartTypeId ?? CartTypeId::Cart->value;
$cart = $this->Carts
->findBySessionId($sessionId)
->contain(['CartItems'])
->where(['cart_type_id' => $cartTypeId])
->first();
$cart = $this->Carts
->findBySessionId($sessionId)
->contain(['CartItems'])
->where(['cart_type_id' => $cartTypeId])
->first();
if (isset($cart) && isset($identity) && !isset($cart[$this->userIdField])) {
$cart = $this->Carts->patchEntity($cart, [
$this->userIdField => $identity->getIdentifier(),
]);
if (isset($cart) && isset($identity) && !isset($cart[$this->userIdField])) {
$cart = $this->Carts->patchEntity($cart, [
$this->userIdField => $identity->getIdentifier(),
]);
$cart = $this->Carts->saveOrFail($cart);
}
if (!isset($cart)) {
$cart = $this->Carts->newEntity([
'cart_type_id' => $cartTypeId,
'session_id' => $sessionId,
$this->userIdField => isset($identity) ? $identity->getIdentifier() : null,
'num_items' => 0,
'cart_items' => [],
]);
$cart = $this->Carts->saveOrFail($cart);
}
if (!isset($cart)) {
$cart = $this->Carts->newEntity([
'cart_type_id' => $cartTypeId,
'session_id' => $sessionId,
$this->userIdField => isset($identity) ? $identity->getIdentifier() : null,
'num_items' => 0,
'cart_items' => [],
]);
$cart = $this->Carts->saveOrFail($cart);
}
$cart = $this->Carts->saveOrFail($cart);
}
return $cart;
}
return $cart;
}
public function getUserIdField()
{
return $this->userIdField;
}
public function getUserIdField() {
return $this->userIdField;
}
/**
/**
* @return string
*/
public function getSessionId(): string
{
if (!$this->getController()->getRequest()->getSession()->started()) {
$this->getController()->getRequest()->getSession()->start();
}
public function getSessionId(): string {
if (!$this->getController()->getRequest()->getSession()->started()) {
$this->getController()->getRequest()->getSession()->start();
}
if (!$this->getController()->getRequest()->getSession()->check('CakeCarts.session_id')) {
$this->getController()->getRequest()->getSession()->write('CakeCarts.session_id', $this->getController()->getRequest()->getSession()->id());
}
if (!$this->getController()->getRequest()->getSession()->check('CakeCarts.session_id')) {
$this->getController()->getRequest()->getSession()->write('CakeCarts.session_id', $this->getController()->getRequest()->getSession()->id());
}
return $this->getController()->getRequest()->getSession()->read('CakeCarts.session_id');
}
return $this->getController()->getRequest()->getSession()->read('CakeCarts.session_id');
}
/**
* @param EntityInterface $cart
* @throws RecordNotFoundException
/**
* @param \Cake\Datasource\EntityInterface $cart
* @throws \Cake\Datasource\Exception\RecordNotFoundException
*
* @return void
*/
public function checkIfIsOwnCart(EntityInterface $cart): void
{
$identity = $this->getController()->getRequest()->getAttribute('identity');
public function checkIfIsOwnCart(EntityInterface $cart): void {
$identity = $this->getController()->getRequest()->getAttribute('identity');
if (!isset($identity) && isset($cart->session_id) && ($cart->session_id != $this->getSessionId())) {
throw new RecordNotFoundException();
}
if (isset($identity) && $identity->getIdentifier() != $cart->get($this->getUserIdField())) {
throw new RecordNotFoundException();
}
}
if (!isset($identity) && isset($cart->session_id) && ($cart->session_id != $this->getSessionId())) {
throw new RecordNotFoundException();
}
if (isset($identity) && $identity->getIdentifier() != $cart->get($this->getUserIdField())) {
throw new RecordNotFoundException();
}
}
/**
/**
* @return bool
*/
protected function _isActionEnabled(): bool
{
$actions = $this->getConfig('actions');
if (is_bool($actions)) {
return $actions;
}
protected function _isActionEnabled(): bool {
$actions = $this->getConfig('actions');
if (is_bool($actions)) {
return $actions;
}
return in_array($this->getController()->getRequest()->getParam('action'), (array)$actions, true);
}
return in_array($this->getController()->getRequest()->getParam('action'), (array)$actions, true);
}
}

View File

@@ -11,7 +11,7 @@ use Cake\ORM\Entity;
* @property string $id
* @property int $cart_type_id
* @property string|null $session_id
* @property integer|null $user_id
* @property int|null $user_id
* @property string|null $user_id_uuid
* @property \Cake\I18n\DateTime $created
* @property \Cake\I18n\DateTime|null $modified
@@ -22,9 +22,9 @@ use Cake\ORM\Entity;
*
* @property \CakeCarts\Model\Entity\CartItem[] $cart_items
*/
class Cart extends Entity
{
/**
class Cart extends Entity {
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
@@ -33,18 +33,19 @@ class Cart extends Entity
*
* @var array<string, bool>
*/
protected array $_accessible = [
'cart_type_id' => true,
'session_id' => true,
'user_id' => true,
'user_id_uuid' => true,
'created' => true,
'modified' => true,
'deleted' => true,
'removed' => true,
'removed_reason_id' => true,
'num_items' => true,
'user' => true,
'cart_items' => true,
];
protected array $_accessible = [
'cart_type_id' => true,
'session_id' => true,
'user_id' => true,
'user_id_uuid' => true,
'created' => true,
'modified' => true,
'deleted' => true,
'removed' => true,
'removed_reason_id' => true,
'num_items' => true,
'user' => true,
'cart_items' => true,
];
}

View File

@@ -20,9 +20,9 @@ use Cake\ORM\Entity;
*
* @property \CakeCarts\Model\Entity\Cart $cart
*/
class CartItem extends Entity
{
/**
class CartItem extends Entity {
/**
* Fields that can be mass assigned using newEntity() or patchEntity().
*
* Note that when '*' is set to true, this allows all unspecified fields to
@@ -31,15 +31,16 @@ class CartItem extends Entity
*
* @var array<string, bool>
*/
protected array $_accessible = [
'foreign_key' => true,
'foreign_key_uuid' => true,
'model' => true,
'cart_id' => true,
'position' => true,
'qty' => true,
'price' => true,
'subtotal' => true,
'cart' => true,
];
protected array $_accessible = [
'foreign_key' => true,
'foreign_key_uuid' => true,
'model' => true,
'cart_id' => true,
'position' => true,
'qty' => true,
'price' => true,
'subtotal' => true,
'cart' => true,
];
}

View File

@@ -1,4 +1,5 @@
<?php
namespace CakeCarts\Model\Enum;
use Cake\Database\Type\EnumLabelInterface;
@@ -6,18 +7,17 @@ use Tools\Model\Enum\EnumOptionsTrait;
enum CartTypeId: int implements EnumLabelInterface
{
use EnumOptionsTrait;
use EnumOptionsTrait;
case Cart = 1;
case Wishlist = 2;
case CustomList = 3;
case Cart = 1;
case Wishlist = 2;
case CustomList = 3;
public function label(): string
{
return match($this) {
self::Cart => 'Cart',
self::Wishlist => 'Wishlist',
self::CustomList => 'List'
};
}
public function label(): string {
return match ($this) {
static::Cart => 'Cart',
static::Wishlist => 'Wishlist',
static::CustomList => 'List'
};
}
}

View File

@@ -3,7 +3,6 @@ declare(strict_types=1);
namespace CakeCarts\Model\Table;
use Cake\ORM\Query\SelectQuery;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
@@ -27,94 +26,91 @@ use Cake\Validation\Validator;
* @method iterable<\CakeCarts\Model\Entity\CartItem>|\Cake\Datasource\ResultSetInterface<\CakeCarts\Model\Entity\CartItem>|false deleteMany(iterable $entities, array $options = [])
* @method iterable<\CakeCarts\Model\Entity\CartItem>|\Cake\Datasource\ResultSetInterface<\CakeCarts\Model\Entity\CartItem> deleteManyOrFail(iterable $entities, array $options = [])
*/
class CartItemsTable extends Table
{
/**
class CartItemsTable extends Table {
/**
* Initialize method
*
* @param array<string, mixed> $config The configuration for the Table.
* @return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
public function initialize(array $config): void {
parent::initialize($config);
$this->setTable('cart_items');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->setTable('cart_items');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->belongsTo('Carts', [
'foreignKey' => 'cart_id',
'joinType' => 'INNER',
'className' => 'CakeCarts.Carts',
]);
}
$this->belongsTo('Carts', [
'foreignKey' => 'cart_id',
'joinType' => 'INNER',
'className' => 'CakeCarts.Carts',
]);
}
/**
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator): Validator
{
$validator
->scalar('foreign_key')
->allowEmptyString('foreign_key');
public function validationDefault(Validator $validator): Validator {
$validator
->scalar('foreign_key')
->allowEmptyString('foreign_key');
$validator
->uuid('foreign_key_uuid')
->allowEmptyString('foreign_key_uuid');
$validator
->uuid('foreign_key_uuid')
->allowEmptyString('foreign_key_uuid');
$validator
->scalar('model')
->requirePresence('model', 'create')
->notEmptyString('model');
$validator
->scalar('model')
->requirePresence('model', 'create')
->notEmptyString('model');
$validator
->uuid('cart_id')
->notEmptyString('cart_id');
$validator
->uuid('cart_id')
->notEmptyString('cart_id');
$validator
->integer('position')
->allowEmptyString('position');
$validator
->integer('position')
->allowEmptyString('position');
$validator
->integer('qty')
->requirePresence('qty', 'create')
->notEmptyString('qty');
$validator
->integer('qty')
->requirePresence('qty', 'create')
->notEmptyString('qty');
return $validator;
}
return $validator;
}
public function validationRequiresPricing(Validator $validator): Validator
{
$validator = $this->validationDefault($validator);
public function validationRequiresPricing(Validator $validator): Validator {
$validator = $this->validationDefault($validator);
$validator
->decimal('price')
->requirePresence('price', 'create')
->allowEmptyString('price');
$validator
->decimal('price')
->requirePresence('price', 'create')
->allowEmptyString('price');
$validator
->decimal('subtotal')
->requirePresence('subtotal', 'create')
->notEmptyString('subtotal');
$validator
->decimal('subtotal')
->requirePresence('subtotal', 'create')
->notEmptyString('subtotal');
return $validator;
}
return $validator;
}
/**
/**
* Returns a rules checker object that will be used for validating
* application integrity.
*
* @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
* @return \Cake\ORM\RulesChecker
*/
public function buildRules(RulesChecker $rules): RulesChecker
{
$rules->add($rules->existsIn(['cart_id'], 'Carts'), ['errorField' => 'cart_id']);
public function buildRules(RulesChecker $rules): RulesChecker {
$rules->add($rules->existsIn(['cart_id'], 'Carts'), ['errorField' => 'cart_id']);
return $rules;
}
return $rules;
}
}

View File

@@ -4,8 +4,6 @@ declare(strict_types=1);
namespace CakeCarts\Model\Table;
use Cake\Database\Type\EnumType;
use Cake\ORM\Query\SelectQuery;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use CakeCarts\Model\Enum\CartTypeId;
@@ -32,74 +30,73 @@ use CakeCarts\Model\Enum\CartTypeId;
*
* @mixin \Cake\ORM\Behavior\TimestampBehavior
*/
class CartsTable extends Table
{
/**
class CartsTable extends Table {
/**
* Initialize method
*
* @param array<string, mixed> $config The configuration for the Table.
* @return void
*/
public function initialize(array $config): void
{
parent::initialize($config);
public function initialize(array $config): void {
parent::initialize($config);
$this->setTable('carts');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->setTable('carts');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('Timestamp');
$this->hasMany('CartItems', [
'foreignKey' => 'cart_id',
'className' => 'CakeCarts.CartItems',
]);
$this->getSchema()->setColumnType('cart_type_id', EnumType::from(CartTypeId::class));
$this->hasMany('CartItems', [
'foreignKey' => 'cart_id',
'className' => 'CakeCarts.CartItems',
]);
$this->getSchema()->setColumnType('cart_type_id', EnumType::from(CartTypeId::class));
}
}
/**
/**
* Default validation rules.
*
* @param \Cake\Validation\Validator $validator Validator instance.
* @return \Cake\Validation\Validator
*/
public function validationDefault(Validator $validator): Validator
{
$validator
->integer('cart_type_id')
->requirePresence('cart_type_id', 'create')
->notEmptyString('cart_type_id');
public function validationDefault(Validator $validator): Validator {
$validator
->integer('cart_type_id')
->requirePresence('cart_type_id', 'create')
->notEmptyString('cart_type_id');
$validator
->scalar('session_id')
->maxLength('session_id', 255)
->allowEmptyString('session_id');
$validator
->scalar('session_id')
->maxLength('session_id', 255)
->allowEmptyString('session_id');
$validator
->uuid('user_id_uuid')
->allowEmptyString('user_id_uuid');
$validator
->uuid('user_id_uuid')
->allowEmptyString('user_id_uuid');
$validator
->integer('user_id')
->allowEmptyString('user_id');
$validator
->integer('user_id')
->allowEmptyString('user_id');
$validator
->dateTime('deleted')
->allowEmptyDateTime('deleted');
$validator
->dateTime('deleted')
->allowEmptyDateTime('deleted');
$validator
->dateTime('removed')
->allowEmptyDateTime('removed');
$validator
->dateTime('removed')
->allowEmptyDateTime('removed');
$validator
->integer('removed_reason_id')
->allowEmptyString('removed_reason_id');
$validator
->integer('removed_reason_id')
->allowEmptyString('removed_reason_id');
$validator
->integer('num_items')
->notEmptyString('num_items');
$validator
->integer('num_items')
->notEmptyString('num_items');
return $validator;
}
return $validator;
}
}