Skip to content

armgit / Vvveb

Public Imported from GitHub
0

Powerful and easy to use cms to build websites, blogs or ecommerce stores.

Add signup, guest checkout and checkout field validators, update REST and GraphQL controllers

Givan3b2b1340e508
diff --git a/admin/validate/admin.php b/admin/validate/admin.php
index 092dd53..3cccb36 100755
--- a/admin/validate/admin.php
+++ b/admin/validate/admin.php
@@ -42,7 +42,7 @@ return [
'email' => [
'email' => '',
],
- /*
+ /*
'captcha' => [
['captcha' => ''],
], */
diff --git a/admin/validate/checkout.php b/admin/validate/checkout.php
new file mode 100755
index 0000000..3d2e613
--- /dev/null
+++ b/admin/validate/checkout.php
@@ -0,0 +1,30 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+return [
+ 'shipping_method' => [
+ 'notEmpty' => '',
+ ],
+ 'payment_method' => [
+ 'notEmpty' => '',
+ ],
+];
diff --git a/admin/validate/checkout_billing.php b/admin/validate/checkout_billing.php
new file mode 100755
index 0000000..75d8eee
--- /dev/null
+++ b/admin/validate/checkout_billing.php
@@ -0,0 +1,89 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+use function Vvveb\__;
+
+return [
+ 'billing_first_name' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+
+ ['maxLength' => 100,
+ 'message' => __('%s must not be greater than 100'), ],
+ ],
+ 'billing_last_name' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+
+ ['maxLength' => 100,
+ 'message' => __('%s must not be greater than 100'), ],
+ ],
+ /*
+ 'billing_company' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+
+ ['maxLength' => 100,
+ 'message' => __('%s must not be greater than 100'), ],
+ ],*/
+ 'billing_address_1' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+
+ ['maxLength' => 100,
+ 'message' => __('%s must not be greater than 100'), ],
+ ],
+ 'billing_address_2' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+
+ ['maxLength' => 100,
+ 'message' => __('%s must not be greater than 100'), ],
+ ],
+ 'billing_city' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+
+ ['maxLength' => 100,
+ 'message' => __('%s must not be greater than 100'), ],
+ ],
+ 'billing_post_code' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+
+ ['maxLength' => 100,
+ 'message' => __('%s must not be greater than 100'), ],
+ ],
+ 'billing_country_id' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+ ],
+ 'billing_region_id' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+ ],
+ /*
+ 'billing.phone_number' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+ ],*/
+];
diff --git a/admin/validate/checkout_shipping.php b/admin/validate/checkout_shipping.php
new file mode 100755
index 0000000..66e73ab
--- /dev/null
+++ b/admin/validate/checkout_shipping.php
@@ -0,0 +1,83 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+use function Vvveb\__;
+
+return [
+ 'shipping_first_name' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+
+ ['maxLength' => 100,
+ 'message' => __('%s must not be greater than 100'), ],
+ ],
+ 'shipping_last_name' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+
+ ['maxLength' => 100,
+ 'message' => __('%s must not be greater than 100'), ],
+ ], /*
+ 'shipping_company' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+
+ ['maxLength' => 100,
+ 'message' => __('%s must not be greater than 100'), ],
+ ],*/
+ 'shipping_address_1' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+
+ ['maxLength' => 100,
+ 'message' => __('%s must not be greater than 100'), ],
+ ],
+ 'shipping_address_2' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+
+ ['maxLength' => 100,
+ 'message' => __('%s must not be greater than 100'), ],
+ ],
+ 'shipping_city' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+
+ ['maxLength' => 100,
+ 'message' => __('%s must not be greater than 100'), ],
+ ],
+ 'shipping_post_code' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+
+ ['maxLength' => 100,
+ 'message' => __('%s must not be greater than 100'), ],
+ ],
+ 'shipping_country_id' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+ ],
+ 'shipping_region_id' => [
+ ['notEmpty' => '',
+ 'message' => '%s must not be empty', ],
+ ],
+];
diff --git a/admin/validate/checkout_signup.php b/admin/validate/checkout_signup.php
new file mode 100755
index 0000000..def7763
--- /dev/null
+++ b/admin/validate/checkout_signup.php
@@ -0,0 +1,45 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+return [
+ 'first_name' => [
+ 'notEmpty' => '',
+ 'maxLength' => 100,
+ ],
+ 'last_name' => [
+ 'notEmpty' => '',
+ 'maxLength' => 100,
+ ],
+ 'email' => [
+ 'notEmpty' => '',
+ 'maxLength' => 100,
+ ],
+ 'password' => [
+ //'passwordComplexity' => 'low',
+ 'minLength' => 6,
+ 'maxLength' => 32,
+ ],
+ 'phone_number' => [
+ 'notEmpty' => '',
+ 'maxLength' => 100,
+ ],
+];
diff --git a/admin/validate/guest.php b/admin/validate/guest.php
new file mode 100755
index 0000000..4bc75be
--- /dev/null
+++ b/admin/validate/guest.php
@@ -0,0 +1,40 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+return [
+ 'first_name' => [
+ 'notEmpty' => '',
+ 'maxLength' => 100,
+ ],
+ 'last_name' => [
+ 'notEmpty' => '',
+ 'maxLength' => 100,
+ ],
+ 'email' => [
+ 'notEmpty' => '',
+ 'maxLength' => 100,
+ ],
+ 'phone_number' => [
+ 'notEmpty' => '',
+ 'maxLength' => 100,
+ ],
+];
diff --git a/admin/validate/login.php b/admin/validate/login.php
index e90fbe0..d169ef8 100755
--- a/admin/validate/login.php
+++ b/admin/validate/login.php
@@ -38,7 +38,7 @@ return [
'session' => 'csrf',
],
*/
- /*
+ /*
'captcha' => [
['captcha' => ''],
], */
diff --git a/admin/validate/order.php b/admin/validate/order.php
index 0038b78..88b3ff8 100755
--- a/admin/validate/order.php
+++ b/admin/validate/order.php
@@ -22,15 +22,15 @@
return [
'first_name' => [
- 'notEmpty' => '',
- 'maxLength' => 100,
+ 'notEmpty' => '',
+ 'maxLength' => 100,
],
'last_name' => [
- 'notEmpty' => '',
- 'maxLength' => 100,
+ 'notEmpty' => '',
+ 'maxLength' => 100,
],
'email' => [
- 'notEmpty' => '',
- 'maxLength' => 100,
+ 'notEmpty' => '',
+ 'maxLength' => 100,
],
];
diff --git a/admin/validate/plugins.php b/admin/validate/plugins.php
index 5b1047f..396eb50 100755
--- a/admin/validate/plugins.php
+++ b/admin/validate/plugins.php
@@ -26,10 +26,10 @@ return [
'maxLength' => 100,
],
'search' => [
- 'optional' => '',
+ 'optional' => '',
],
'taxonomy_item_id' => [
- 'optional' => '',
+ 'optional' => '',
],
'browse' => [
'allowedValues' => ['popular', 'featured', 'updated', 'new'],
diff --git a/admin/validate/post_content.php b/admin/validate/post_content.php
index 130a386..d25d376 100755
--- a/admin/validate/post_content.php
+++ b/admin/validate/post_content.php
@@ -27,10 +27,10 @@ return [
],
'content' => [
- 'notEmpty' => '',
+ 'notEmpty' => '',
],
'slug' => [
- 'notEmpty' => '',
+ 'notEmpty' => '',
],
/*
diff --git a/admin/validate/product_content.php b/admin/validate/product_content.php
index 313d69c..0f25a3d 100755
--- a/admin/validate/product_content.php
+++ b/admin/validate/product_content.php
@@ -27,10 +27,10 @@ return [
],
'content' => [
- 'notEmpty' => '',
+ 'notEmpty' => '',
],
'slug' => [
- 'notEmpty' => '',
+ 'notEmpty' => '',
],
];
diff --git a/admin/validate/settings.php b/admin/validate/settings.php
index 787e8ba..8bd1823 100755
--- a/admin/validate/settings.php
+++ b/admin/validate/settings.php
@@ -22,11 +22,11 @@
return [
'site-title' => [
- 'notEmpty' => '',
- 'maxLength' => 100,
+ 'notEmpty' => '',
+ 'maxLength' => 100,
],
'site-description' => [
- 'notEmpty' => '',
- 'maxLength' => 255,
+ 'notEmpty' => '',
+ 'maxLength' => 255,
],
];
diff --git a/admin/validate/signup.php b/admin/validate/signup.php
new file mode 100755
index 0000000..5d8850c
--- /dev/null
+++ b/admin/validate/signup.php
@@ -0,0 +1,50 @@
+<?php
+
+/**
+ * Vvveb
+ *
+ * Copyright (C) 2022 Ziadin Givan
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+return [
+ /*
+ 'first_name' => [
+ 'notEmpty' => '',
+ 'maxLength' => 100,
+ ],
+ 'last_name' => [
+ 'notEmpty' => '',
+ 'maxLength' => 100,
+ ],
+*/
+ 'username' => [
+ 'notEmpty' => '',
+ 'maxLength' => 100,
+ ],
+ 'email' => [
+ 'notEmpty' => '',
+ 'maxLength' => 100,
+ ],
+ 'password' => [
+ //'passwordComplexity' => 'low',
+ 'minLength' => 6,
+ 'maxLength' => 32,
+ ],
+ 'confirm_password' => [
+ 'match' => 'password',
+ ],
+];
diff --git a/admin/validate/site.php b/admin/validate/site.php
index cdcdcb5..7458ee2 100755
--- a/admin/validate/site.php
+++ b/admin/validate/site.php
@@ -31,10 +31,10 @@ return [
],
*/
'host' => [
- 'notEmpty' => '',
+ 'notEmpty' => '',
],
'theme' => [
- 'notEmpty' => '',
+ 'notEmpty' => '',
],
];
diff --git a/admin/validate/themes.php b/admin/validate/themes.php
index f4c8eb2..07c0fdc 100755
--- a/admin/validate/themes.php
+++ b/admin/validate/themes.php
@@ -29,16 +29,16 @@ return [
'message' => __('%s must not be greater than %d')*/,
],
'taxonomy_item_id' => [
- 'optional' => '',
+ 'optional' => '',
],
'search' => [
- 'optional' => '',
+ 'optional' => '',
],
'browse' => [
'allowedValues' => ['popular', 'featured', 'updated', 'new'],
],
- /*
+ /*
'captcha' => [
['captcha' => ''],
], */
diff --git a/admin/validate/user.php b/admin/validate/user.php
index c94e98c..ca34ce9 100755
--- a/admin/validate/user.php
+++ b/admin/validate/user.php
@@ -47,7 +47,7 @@ return [
'email' => '',
'maxLength' => 100,
],
- /*
+ /*
'captcha' => [
['captcha' => ''],
], */
diff --git a/graphql/controller/base.php b/graphql/controller/base.php
old mode 100644
new mode 100755
index 04a2829..a8f452d
--- a/graphql/controller/base.php
+++ b/graphql/controller/base.php
@@ -22,7 +22,6 @@
namespace Vvveb\Controller;
-use \Vvveb\System\Core\FrontController;
use function Vvveb\__;
use function Vvveb\config;
use function Vvveb\siteSettings;
@@ -38,19 +37,26 @@ use Vvveb\System\User\Admin;
class Base {
use Permission;
- protected $global = [];
+ /** @var array<string, mixed> */
+ protected array $global = [];
- function auth() {
+ /**
+ * Authenticate the current admin user via HTTP or token-based auth.
+ *
+ * @return void
+ */
+ public function auth(): void {
$admin = Admin::current();
- if (! $admin) {
+ if (!$admin) {
$authMode = config(APP . '.auth.mode');
- if ($authMode == 'http') {
+ if ($authMode === 'http') {
if (isset($_SERVER['PHP_AUTH_USER'])) {
$user = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'] ?? '';
$loginData = compact('user', 'password');
+ $feedback = [];
if ($userInfo = Admin::login($loginData, [], $feedback)) {
} else {
@@ -59,10 +65,9 @@ class Base {
$message = __('Auth failed!');
if (DEBUG) {
- $message .= ' ' . $feedback['message'] ?? [];
+ $message .= ' ' . ($feedback['message'] ?? '');
$message .= " auth.mode = $authMode";
}
- //FrontController::notFound(false, $message, 403);
$this->notFound($message, 403);
}
} else {
@@ -74,31 +79,29 @@ class Base {
$message .= __('No credentials!');
$message .= " auth.mode = $authMode";
}
- //FrontController::notFound(false, $message, 403);
$this->notFound($message, 403);
}
} else {
- if ($authMode == 'token') {
+ if ($authMode === 'token') {
$headers = getallheaders();
$token = $headers['Bearer'] ?? $_SERVER['HTTP_BEARER'] ?? null;
- if (! $token) {
+ if (!$token) {
$token = $headers['Authorization'] ?? $_SERVER['HTTP_AUTHORIZATION'] ?? '';
$token = trim(substr($token, 6)) ?: $this->request->get['_token'] ?? false;
}
if ($token) {
+ $feedback = [];
if ($userInfo = Admin::auth($token, [], $feedback)) {
} else {
$this->response->addHeader('HTTP/1.0 401 Unauthorized');
$message = __('Auth failed!');
if (DEBUG) {
- $message .= ' ' . $feedback['message'] ?? [];
+ $message .= ' ' . ($feedback['message'] ?? '');
$message .= " auth.mode = $authMode";
- $message .= " token = $token";
}
- //FrontController::notFound(false, $message, 403);
$this->notFound($message, 403);
}
} else {
@@ -108,9 +111,7 @@ class Base {
if (DEBUG) {
$message .= __('No credentials!');
$message .= " auth.mode = $authMode";
- $message .= " token = $token";
}
- //FrontController::notFound(false, $message, 403);
$this->notFound($message, 403);
}
}
@@ -118,19 +119,32 @@ class Base {
}
}
- protected function initEcommerce($countryId, $regionId) {
+ /**
+ * Initialize ecommerce tax rules for the given region.
+ *
+ * @param int $countryId
+ * @param int $regionId
+ *
+ * @return void
+ */
+ protected function initEcommerce(int $countryId, int $regionId): void {
$tax = \Vvveb\System\Cart\Tax::getInstance();
$tax->setRegionRules($countryId, $regionId, 'store');
}
- function init() {
+ /**
+ * Initialize the GraphQL controller: set up request/response/session, authenticate, and load global settings.
+ *
+ * @return string|null
+ */
+ public function init(): ?string {
$this->response = Response::getInstance();
$this->request = Request::getInstance();
$this->session = Session::getInstance();
$this->response->setType('json');
- if (! GRAPHQL) {
+ if (!GRAPHQL) {
$this->notFound(__('GRAPHQL is disabled!'), 404);
}
@@ -138,20 +152,29 @@ class Base {
$method = $this->request->getMethod();
- Plugins :: loadPlugins();
+ Plugins::loadPlugins();
$site = siteSettings();
- list($site) = Event::trigger(__CLASS__, __FUNCTION__, $site);
+ [$site] = Event::trigger(__CLASS__, __FUNCTION__, $site);
- $this->global['site_id'] = SITE_ID ?? 1;
+ $this->global['site_id'] = SITE_ID;
+ $this->global['languages'] = $site['languages'] ?? [];
+ $this->global['language'] = ($site['language'] ?? '') ?: 'en';
$this->global['language_id'] = $this->session->get('language_id') ?? $site['language_id'] ?? 1;
+ $this->global['default_language'] = $site['language'] ?? 'en';
$this->global['default_language_id'] = $this->session->get('default_language_id') ?? $site['language_id'] ?? 1;
+ $this->global['default_lang_slug'] = $site['default_lang_slug'] ?? false;
+ $this->global['currency_id'] = (int)($this->session->get('currency_id') ?? $site['currency_id'] ?? 1);
+ $this->global['currency'] = $this->session->get('currency') ?? $site['currency'] ?? 'usd';
+ $this->global['currencies'] = $site['currencies'] ?? [];
$this->global['limit'] = 10;
$this->global['start'] = 0;
+
+ $user = Admin::current() ?: [];
$this->global['user_id'] = $user['user_id'] ?? false;
$this->global['user_group_id'] = $user['user_group_id'] ?? 1;
$this->global['site'] = &$site;
- $this->global['user'] = $user ?? [];
+ $this->global['user'] = $user;
$language_id = $this->global['language_id'];
@@ -165,24 +188,27 @@ class Base {
$this->global['site'] = &$site;
- list($this->global) = Event::trigger(__CLASS__, __FUNCTION__ . ':after', $this->global);
+ [$this->global] = Event::trigger(__CLASS__, __FUNCTION__ . ':after', $this->global);
+
+ return null;
}
/**
- * Call this function if the requeste information was not found, for example if the specifed news, image, profile etc is not found then call this function.
- * It shows a "Not found" page and it also send 404 http status code, this is usefull for search engines etc.
+ * Call this function if the requested information was not found.
+ * It outputs an error response and terminates.
+ *
+ * @param array<string, mixed>|string|null $message
+ * @param int $statusCode
+ * @param bool $service
*
- * @param unknown_type $code
- * @param mixed $service
- * @param mixed $statusCode
- * @param null|mixed $message
+ * @return never
*/
- protected function notFound($message = null, $statusCode = 404, $service = false) {
+ protected function notFound(array|string|null $message = null, int $statusCode = 404, bool $service = false): never {
$response = Response::getInstance();
http_response_code($statusCode);
$response->output(['errors' => is_array($message) ? $message : ['message' => $message]]);
- die();
+ exit();
}
}
diff --git a/graphql/controller/cart.php b/graphql/controller/cart.php
old mode 100644
new mode 100755
index 3a0a7b6..2336893
--- a/graphql/controller/cart.php
+++ b/graphql/controller/cart.php
@@ -29,40 +29,61 @@ use Vvveb\System\Payment;
use Vvveb\System\Shipping;
class Cart extends Base {
-// use CartTrait;
use Cart\CouponTrait;
- private $cart;
-
- private $payment;
-
- private $shipping;
-
- private function cart($cart_id = null) {
- $this->init();
+ /** @var ShoppingCart|null */
+ private ?ShoppingCart $cart = null;
+
+ /**
+ * Initialize the shopping cart instance.
+ *
+ * @param int|null $cart_id
+ *
+ * @return void
+ */
+ private bool $initialized = false;
+
+ private function cart(?int $cart_id = null): void {
+ //GraphQL resolvers bypass FrontController, so init() runs on first use;
+ //guard it to avoid re-running auth/plugins/site setup for every field
+ if (!$this->initialized) {
+ $this->init();
+ $this->initialized = true;
+ }
- $options = array_intersect_key($this->global['site'],
- array_flip(['weight_type_id', 'length_type_id', 'currency_id', 'country_id']));
+ $options = array_intersect_key(
+ $this->global['site'],
+ array_flip(['weight_type_id', 'length_type_id', 'currency_id', 'country_id'])
+ );
$options['cart_id'] = $cart_id;
$this->cart = ShoppingCart::getInstance($this->global + $options);
}
- function index($args) {
+ /**
+ * Retrieve the full cart contents and totals.
+ *
+ * @param array<string, mixed> $args
+ *
+ * @return array<string, mixed>
+ */
+ public function index(array $args = []): array {
$cart_id = $args['cart_id'] ?? null;
- if (! $this->cart) {
+ if (!$this->cart) {
$this->cart($cart_id);
}
- $payment = Payment::getInstance();
- $shipping = Shipping::getInstance();
+ $payment = Payment::getInstance();
+ $shipping = Shipping::getInstance();
+ $paymentInfo = [];
+ $shippingInfo = [];
- $this->payment = $payment->getMethods([]);
- $this->shipping = $shipping->getMethods([]);
+ $payment->getMethods($paymentInfo);
+ $shipping->getMethods($shippingInfo);
- $cart = [
+ return [
'cart_id' => $this->cart->getId(),
'encrypted_cart_id' => $this->cart->getEncryptedId(),
'products' => $this->cart->getAll(),
@@ -78,14 +99,19 @@ class Cart extends Base {
'weight_unit' => $this->global['site']['weight_type'],
'length_unit' => $this->global['site']['length_type'],
];
-
- return $cart;
}
- function add($args) {
+ /**
+ * Add a product to the cart.
+ *
+ * @param array<string, mixed> $args
+ *
+ * @return array<string, mixed>|null
+ */
+ public function add(array $args): ?array {
$cart_id = $args['cart_id'] ?? null;
- if (! $this->cart) {
+ if (!$this->cart) {
$this->cart($cart_id);
}
@@ -97,7 +123,7 @@ class Cart extends Base {
if ($productId) {
if ($options && is_string($options)) {
- if ($options[0] != '{') {
+ if ($options[0] !== '{') {
$options = '{' . $options . '}';
}
$options = json_decode($options, true);
@@ -106,23 +132,37 @@ class Cart extends Base {
return $this->index($args);
}
+
+ return null;
}
- function create($args) {
- if (! $this->cart) {
+ /**
+ * Create a new empty cart.
+ *
+ * @param array<string, mixed> $args
+ *
+ * @return array<string, mixed>
+ */
+ public function create(array $args): array {
+ if (!$this->cart) {
$this->cart();
$args['cart_id'] = $this->cart->create();
}
- $cart = $this->index($args);
-
- return $cart;
+ return $this->index($args);
}
- function update($args) {
+ /**
+ * Update the quantity of a cart item.
+ *
+ * @param array<string, mixed> $args
+ *
+ * @return array<string, mixed>|null
+ */
+ public function update(array $args): ?array {
$cart_id = $args['cart_id'] ?? null;
- if (! $this->cart) {
+ if (!$this->cart) {
$this->cart($cart_id);
}
@@ -131,12 +171,21 @@ class Cart extends Base {
return $this->index($args);
}
+
+ return null;
}
- function remove($args) {
+ /**
+ * Remove an item from the cart.
+ *
+ * @param array<string, mixed> $args
+ *
+ * @return array<string, mixed>|null
+ */
+ public function remove(array $args): ?array {
$cart_id = $args['cart_id'] ?? null;
- if (! $this->cart) {
+ if (!$this->cart) {
$this->cart($cart_id);
}
@@ -145,5 +194,7 @@ class Cart extends Base {
return $this->index($args);
}
+
+ return null;
}
}
diff --git a/graphql/controller/error403.php b/graphql/controller/error403.php
old mode 100644
new mode 100755
index 50fabcb..af15bdc
--- a/graphql/controller/error403.php
+++ b/graphql/controller/error403.php
@@ -24,7 +24,12 @@ namespace Vvveb\Controller;
#[\AllowDynamicProperties]
class Error403 extends Base {
- function index() {
+ /**
+ * Return a 403 error response for GraphQL.
+ *
+ * @return array{errors: array{message: string, code: int}}
+ */
+ public function index(): array {
$this->response->setType('json');
return ['errors' => ['message' => $this->view->message, 'code' => $this->view->code ?? 403]];
diff --git a/graphql/controller/error404.php b/graphql/controller/error404.php
old mode 100644
new mode 100755
index 6497267..395eb77
--- a/graphql/controller/error404.php
+++ b/graphql/controller/error404.php
@@ -24,7 +24,12 @@ namespace Vvveb\Controller;
#[\AllowDynamicProperties]
class Error404 extends Base {
- function index() {
+ /**
+ * Return a 404 error response for GraphQL.
+ *
+ * @return array{errors: array{message: string, code: int}}
+ */
+ public function index(): array {
$this->response->setType('json');
return ['errors' => ['message' => $this->view->message ?? '', 'code' => $this->view->code ?? 404]];
diff --git a/graphql/controller/error500.php b/graphql/controller/error500.php
old mode 100644
new mode 100755
index 55f9344..b5932f0
--- a/graphql/controller/error500.php
+++ b/graphql/controller/error500.php
@@ -24,7 +24,12 @@ namespace Vvveb\Controller;
#[\AllowDynamicProperties]
class Error500 extends Base {
- function index() {
+ /**
+ * Return a 500 error response for GraphQL.
+ *
+ * @return array<string, mixed>
+ */
+ public function index(): array {
$this->response->setType('json');
if (DEBUG) {
diff --git a/graphql/controller/index.php b/graphql/controller/index.php
old mode 100644
new mode 100755
index d2a1575..4db6107
--- a/graphql/controller/index.php
+++ b/graphql/controller/index.php
@@ -22,72 +22,107 @@
namespace Vvveb\Controller;
-use function \Vvveb\arrayKeysToCamelCase;
-use function \Vvveb\arrayKeysToUnderscore;
-use function \Vvveb\camelToUnderscore;
-use function \Vvveb\controller;
-use function \Vvveb\isController;
-use function \Vvveb\isModel;
-use function \Vvveb\model;
use GraphQL\Error\DebugFlag;
use GraphQL\GraphQL;
use GraphQL\Language\Parser;
-use GraphQL\Type\Definition\ObjectType;
use GraphQL\Type\Definition\ResolveInfo;
use GraphQL\Type\Definition\Type;
use GraphQL\Utils\AST;
use GraphQL\Utils\BuildSchema;
+use function Vvveb\arrayKeysToCamelCase;
+use function Vvveb\arrayKeysToUnderscore;
+use function Vvveb\camelToUnderscore;
+use function Vvveb\controller;
+use function Vvveb\isController;
+use function Vvveb\isModel;
+use function Vvveb\model;
use Vvveb\System\Event;
class PostConnection {
- public $nodes;
+ /** @var mixed */
+ public mixed $nodes = null;
- public $PageInfo = [];
+ /** @var array<string, mixed> */
+ public array $PageInfo = [];
}
#[\AllowDynamicProperties]
class Index extends Base {
- protected $stack = [];
+ /** @var array<int, array<int, array<string, mixed>>> */
+ protected array $stack = [];
- protected $queryIndex = -1;
+ /** @var int Current query index in the stack */
+ protected int $queryIndex = -1;
- //protected $currentQuery = -1;
- protected $stackIndex = 0;
+ /** @var int Current stack index */
+ protected int $stackIndex = 0;
- protected $schema = [];
+ /** @var \GraphQL\Type\Schema|null GraphQL schema instance */
+ protected mixed $schema = null;
- protected $args = [];
+ /** @var array<string, mixed> Current resolved arguments */
+ protected array $args = [];
- protected $returnIsList = false;
+ /** @var bool Whether the current return type is a list */
+ protected bool $returnIsList = false;
- protected $queries = [];
+ /** @var array<string, callable> Custom query resolvers */
+ protected array $queries = [];
- protected $mutations = [];
+ /** @var array<string, callable> Custom mutation resolvers */
+ protected array $mutations = [];
- protected $types = [];
+ /** @var array<string, callable> Custom type resolvers */
+ protected array $types = [];
- protected $transforms = [
+ /** @var array<string, string> Transform class mappings */
+ protected array $transforms = [
'post' => 'Vvveb\Transform\Post',
'product' => 'Vvveb\Transform\Product',
];
- function queries() {
- list($this->queries) = Event::trigger(__CLASS__, __FUNCTION__, $this->queries);
+ /**
+ * Register custom query resolvers via event trigger.
+ *
+ * @return void
+ */
+ public function queries(): void {
+ [$this->queries] = Event::trigger(__CLASS__, __FUNCTION__, $this->queries);
}
- function mutations() {
- list($this->mutations) = Event::trigger(__CLASS__, __FUNCTION__, $this->mutations);
+ /**
+ * Register custom mutation resolvers via event trigger.
+ *
+ * @return void
+ */
+ public function mutations(): void {
+ [$this->mutations] = Event::trigger(__CLASS__, __FUNCTION__, $this->mutations);
}
- function types() {
- list($this->types) = Event::trigger(__CLASS__, __FUNCTION__, $this->types);
+ /**
+ * Register custom type resolvers via event trigger.
+ *
+ * @return void
+ */
+ public function types(): void {
+ [$this->types] = Event::trigger(__CLASS__, __FUNCTION__, $this->types);
}
- function transforms() {
- list($this->transforms) = Event::trigger(__CLASS__, __FUNCTION__, $this->transforms);
+ /**
+ * Register custom transforms via event trigger.
+ *
+ * @return void
+ */
+ public function transforms(): void {
+ [$this->transforms] = Event::trigger(__CLASS__, __FUNCTION__, $this->transforms);
}
- function init() {
+ /**
+ * Initialize the GraphQL controller by registering types, queries, mutations, and transforms.
+ *
+ * @return string|null
+ */
+ public function init(): ?string {
$this->types();
$this->queries();
$this->mutations();
@@ -96,56 +131,65 @@ class Index extends Base {
return parent::init();
}
- function cascadeOptions() {
- }
-
- function model($typeName, $isConnection = false) {
- $page = 1;
- $limit = 10;
+ /**
+ * Placeholder for cascading options.
+ *
+ * @return void
+ */
+ public function cascadeOptions(): void {}
+
+ /**
+ * Retrieve model data by type name, optionally as a connection (paginated).
+ *
+ * @param string $typeName
+ * @param bool $isConnection
+ *
+ * @return array<string, mixed>
+ */
+ public function model(string $typeName, bool $isConnection = false): array {
$data = [];
$typeName = camelToUnderscore($typeName, '_');
$options = $this->args + $this->global;
+ $limit = max(1, (int)($options['limit'] ?? 10));
+ $start = max(0, (int)($options['start'] ?? 0));
+ $page = (int)floor($start / $limit) + 1;
- if (! isModel($typeName, 'admin')) {
+ if (!isModel($typeName, 'admin')) {
return $data;
}
$type = model($typeName);
- if ($type) {
- $transform = null;
+ $transform = null;
- if (isset($this->transforms[$typeName])) {
- $class = $this->transforms[$typeName];
- $transform = new $class();
- }
-
- if ($this->returnIsList || $isConnection) {
- $data = $type->getAll($options);
- $data = $data[$typeName] ?? [];
+ if (isset($this->transforms[$typeName])) {
+ $class = $this->transforms[$typeName];
+ $transform = new $class();
+ }
- if ($transform) {
- error_log(print_r($options, 1));
- $data = $transform->getAll($data, $options);
- }
- } else {
- $data = $type->get($options);
+ if ($this->returnIsList || $isConnection) {
+ $allData = $type->getAll($options);
+ $count = $allData['count'] ?? 0;
+ $data = $allData[$typeName] ?? [];
- if ($transform) {
- $data = $transform->get($data, $options);
- }
+ if ($transform) {
+ $data = $transform->getAll($data, $options);
}
} else {
- throw new \Exception('Model does not exist!');
+ $data = $type->get($options);
+
+ if ($transform) {
+ $data = $transform->get($data, $options);
+ }
}
if ($isConnection) {
$pageInfo = [
- 'count' => $return['count'] ?? 0,
+ 'count' => $count,
'page' => $page,
'limit' => $limit,
- 'hasNextPage' => true,
- 'hasPreviousPage' => true,
+ 'hasNextPage' => ($page * $limit) < ($count),
+ 'hasPreviousPage' => $page > 1,
'startCursor' => 1,
];
@@ -155,7 +199,16 @@ class Index extends Base {
return $data;
}
- function controller($typeName, $args, $rootType = 'mutation') {
+ /**
+ * Resolve a controller or model method by type name.
+ *
+ * @param string $typeName
+ * @param array<string, mixed> $args
+ * @param string $rootType
+ *
+ * @return array<string, mixed>
+ */
+ public function controller(string $typeName, array $args, string $rootType = 'mutation'): array {
//check if has method
if (preg_match('/^(\w+)([A-Z]\w+)/', $typeName, $matches)) {
$method = $matches[1];
@@ -173,29 +226,23 @@ class Index extends Base {
if (isController($classFile)) {
$controller = controller($className);
- if ($controller) {
- if (method_exists($controller, $method)) {
- $data = $controller->$method($args + $this->global);
- } else {
- throw new \Exception('Controller method does not exist!');
- }
+ if (method_exists($controller, $method)) {
+ $data = $controller->$method($args + $this->global);
} else {
- throw new \Exception('Controller can\'t be loaded!');
+ throw new \Exception('Controller method does not exist!');
}
} else {
- $class = strtolower(camelToUnderscore($class,'_'));
+ $class = strtolower(camelToUnderscore($class, '_'));
if (isModel($class)) {
$class = model($class);
- if ($class) {
- if (method_exists($class, $method)) {
- $data = $class->$method($args + ['site_id' => 1]);
- } else {
- throw new \Exception('Model method does not exist!');
- }
+ if (method_exists($class, $method)) {
+ $data = $class->$method($args + ['site_id' => $this->global['site_id']]);
} else {
- throw new \Exception('Model can\'t be loaded!');
+ //no matching model method, return empty and let the
+ //caller fall through to type-based model resolution
+ return [];
}
} else {
//throw new \Exception('Model does not exist!');
@@ -205,16 +252,18 @@ class Index extends Base {
return $data;
}
- function defaultFieldResolver($objectValue, $args, $context, ResolveInfo $info) {
- $fieldName = $info->fieldName;
-
- if (is_null($fieldName)) {
- throw new \Exception('Could not get $fieldName from ResolveInfo');
- }
-
- if (is_null($info->parentType)) {
- throw new \Exception('Could not get $parentType from ResolveInfo');
- }
+ /**
+ * Default field resolver for GraphQL queries and mutations.
+ *
+ * @param mixed $objectValue
+ * @param array<string, mixed> $args
+ * @param mixed $context
+ * @param ResolveInfo $info
+ *
+ * @return mixed
+ */
+ public function defaultFieldResolver(mixed $objectValue, array $args, mixed $context, ResolveInfo $info): mixed {
+ $fieldName = $info->fieldName;
$parentTypeName = $info->parentType->name; //MutationType
$typeName = $info->fieldDefinition->config['type']->name ?? '';
@@ -228,51 +277,42 @@ class Index extends Base {
$this->args += $objectValue;
}
- if (GRAPHQL_CAMELCASE && is_array($this->args)) {
+ if (GRAPHQL_CAMELCASE) {
$this->args = arrayKeysToUnderscore($this->args, '_');
}
- if ($info->returnType) {
- //method_exists($info->returnType, 'getInnermostType')
- if (is_a($info->returnType, 'GraphQL\Type\Definition\ListOfType')) {
- $returnType = $info->returnType->getInnermostType()->name;
- $this->returnIsList = true;
- } else {
- $returnType = $info->returnType->name ?? '';
- }
+ //method_exists($info->returnType, 'getInnermostType')
+ if (is_a($info->returnType, 'GraphQL\Type\Definition\ListOfType')) {
+ $returnType = $info->returnType->getInnermostType()->name;
+ $this->returnIsList = true;
+ } else {
+ $returnType = $info->returnType->name ?? '';
}
- /*
- error_log('$returnType = ' . $returnType);
- error_log('$objectValue = ' . print_r($objectValue, 1));
- error_log('$fieldName = ' . $fieldName);
- error_log('$parentTypeName = ' . $parentTypeName);
- error_log('$typeName = ' . $typeName);
- error_log('$args = ' . print_r($this->args, 1));
- */
+
$method = '';
$type = '';
$permission = $fieldName;
if (preg_match('/^([a-z]+)([A-Z]\w+)/', $fieldName, $matches)) {
$method = $matches[1];
- $type = strtolower(camelToUnderscore($matches[2],'_'));
+ $type = strtolower(camelToUnderscore($matches[2], '_'));
$permission = "$type/$method";
}
$this->permission($permission);
$data = [];
- //if previous controller or model call already has the data then don't try to retrive it again
+ //if previous controller or model call already has the data then don't try to retrieve it again
if (isset($this->stack[$this->queryIndex][$this->stackIndex - 1]['data'][$fieldName])) {
$data = $this->stack[$this->queryIndex][$this->stackIndex - 1]['data'][$fieldName];
}
- //if object already has the data then don't try to retrive it again
+ //if object already has the data then don't try to retrieve it again
if (isset($objectValue[$fieldName])) {
$data = $objectValue[$fieldName];
}
- if ($parentTypeName == 'RootQueryType') {
+ if ($parentTypeName === 'RootQueryType') {
$this->queryIndex++;
if (isset($this->queries[$type])) {
@@ -282,7 +322,7 @@ class Index extends Base {
$data = $this->controller($fieldName, $this->args, 'query');
}
} else {
- if ($parentTypeName == 'MutationType') {
+ if ($parentTypeName === 'MutationType') {
$data = [];
if (isset($this->mutations[$type])) {
@@ -296,11 +336,13 @@ class Index extends Base {
}
}
- if (! $data) {
+ if (!$data && $parentTypeName !== 'MutationType') {
+ //mutations that return no data must stay empty and never
+ //fall through to an unrelated model read
foreach ([$typeName, $returnType] as $type) {
- if (substr_compare($type, 'Type', -4 ,4) === 0) {
- //$typeName = strtolower(preg_replace('/Type$/', '', $typeName));
+ if (substr_compare($type, 'Type', -4, 4) === 0) {
$type = substr($type, 0, -4);
+ //$typeName = strtolower(preg_replace('/Type$/', '', $typeName));
if (isset($this->types[$type])) {
$fn = $this->types[$type];
@@ -311,7 +353,7 @@ class Index extends Base {
break;
} else {
- if (substr_compare($type, 'Connection', -10 ,10) === 0) {
+ if (substr_compare($type, 'Connection', -10, 10) === 0) {
//$typeName = strtolower(preg_replace('/Type$/', '', $typeName));
$isConnection = true;
$type = substr($type, 0, -10);
@@ -337,21 +379,17 @@ class Index extends Base {
'model' => $typeName,
'method' => $method,
//'args' => $this->args,
- 'data' => $data,
- 'objectValue' => $objectValue,
+ 'data' => $data,
+ 'objectValue' => $objectValue,
];
if ($data) {
- if ($isConnection) {
- return $data;
- } else {
- return $data;
- }
+ return $data;
}
$property = null;
- if (is_array($objectValue) || $objectValue instanceof ArrayAccess) {
+ if (is_array($objectValue) || $objectValue instanceof \ArrayAccess) {
if (isset($objectValue[$fieldName])) {
$property = $objectValue[$fieldName];
}
@@ -360,70 +398,65 @@ class Index extends Base {
$property = $objectValue->{$fieldName};
}
}
+
//error_log(print_r($property, 1));
- return $property instanceof Closure
- ? $property($objectValue, $args, $contextValue, $info)
+ return $property instanceof \Closure
+ ? $property($objectValue, $args, $context, $info)
: $property;
}
- function index() {
+ /**
+ * Main GraphQL index action: parse and execute the GraphQL query.
+ *
+ * @return array<string, mixed>
+ */
+ public function index(): array {
$rawInput = file_get_contents('php://input');
- $typeConfigDecorator = function (array $typeConfig, $typeDefinitionNode) : array {
- $name = $typeConfig['name'];
- //error_log($name . ' $typeConfigDecorator');
- if ($name == 'ObjectType') {
- //error_log(print_r($typeDefinitionNode, 1));
-
-/*
-$typeDefinitionNode = new ObjectType([
- 'name' => 'PostConnection',
- 'fields' => [
- 'nodes' => [
- 'type' => Type::listOf('PostType'),
- 'resolve' => fn () => $data['nodes']
- ],
- 'pageInfo' => [
- 'type' => 'PageInfo',
- 'resolve' => fn () => $data['pageInfo']
- ]
- ]
-]);
- */
- }
+ $typeConfigDecorator = function(array $typeConfig, mixed $typeDefinitionNode): array {
// ... add missing options to $typeConfig based on type $name
return $typeConfig;
};
- $cacheFilename = DIR_STORAGE . 'model' . DS . 'cached_schema.php';
+ $cacheFilename = DIR_STORAGE . 'model/cached_schema.php';
- if (! file_exists($cacheFilename)) {
+ //regenerate at least weely so schema and model changes are picked up
+ $regenerate = true;
+
+ if (file_exists($cacheFilename)) {
+ $cached = require $cacheFilename;
+ $regenerate = (($cached['generated'] ?? 0) + 604800) < time();
+
+ if (!$regenerate) {
+ $document = AST::fromArray($cached['schema']); // fromArray() is a lazy operation as well
+ }
+ }
+
+ if ($regenerate) {
$schemaController = new Schema();
$schema = $schemaController->schema(); //file_get_contents(DIR_APP . 'schema.gql');
$document = Parser::parse($schema);
- file_put_contents($cacheFilename, "<?php\nreturn " . var_export(AST::toArray($document), true) . ";\n");
- } else {
- $document = AST::fromArray(require $cacheFilename); // fromArray() is a lazy operation as well
+ $exported = var_export(['generated' => time(), 'schema' => AST::toArray($document)], true);
+ //write to a temp file and rename, so concurrent requests never read a half written schema
+ $tmp = $cacheFilename . '.' . getmypid() . '.tmp';
+ file_put_contents($tmp, "<?php\nreturn " . $exported . ";\n");
+ rename($tmp, $cacheFilename);
}
- //$typeConfigDecorator = function () {};
- //$schema = BuildSchema::build($document);//, $typeConfigDecorator);
- $this->schema = BuildSchema::build($document, $typeConfigDecorator);
-
$input = json_decode($rawInput, true);
$query = $input['query'] ?? '';
$variableValues = $input['variables'] ?? null;
try {
- $result = GraphQL::executeQuery($this->schema, $query, null, null, $variableValues, null, [$this, 'defaultFieldResolver'] /*'Vvveb\Controller\defaultFieldResolver'*/);
+ $this->schema = BuildSchema::build($document, $typeConfigDecorator);
+
+ $result = GraphQL::executeQuery($this->schema, $query, null, null, $variableValues, null, [$this, 'defaultFieldResolver']);
$flags = 0;
if (DEBUG) {
$flags = DebugFlag::INCLUDE_DEBUG_MESSAGE | DebugFlag::INCLUDE_TRACE;
}
$output = $result->toArray($flags);
-
- //error_log(print_r($this->stack, 1));
} catch (\Exception $e) {
$message = $e->getMessage();
diff --git a/graphql/controller/mutation/cart.php b/graphql/controller/mutation/cart.php
old mode 100644
new mode 100755
index 580dcda..de203cf
--- a/graphql/controller/mutation/cart.php
+++ b/graphql/controller/mutation/cart.php
@@ -24,5 +24,4 @@ namespace Vvveb\Controller\Mutation;
use Vvveb\Controller\Cart as CartBase;
-class Cart extends CartBase {
-}
+class Cart extends CartBase {}
diff --git a/graphql/controller/query/cart.php b/graphql/controller/query/cart.php
old mode 100644
new mode 100755
index 49b6761..0c6626f
--- a/graphql/controller/query/cart.php
+++ b/graphql/controller/query/cart.php
@@ -24,5 +24,4 @@ namespace Vvveb\Controller\Query;
use Vvveb\Controller\Cart as CartBase;
-class Cart extends CartBase {
-}
+class Cart extends CartBase {}
diff --git a/graphql/controller/schema.php b/graphql/controller/schema.php
old mode 100644
new mode 100755
index a4cdb5e..915fa25
--- a/graphql/controller/schema.php
+++ b/graphql/controller/schema.php
@@ -33,19 +33,29 @@ use Vvveb\System\Sqlp\Sqlp;
#[\AllowDynamicProperties]
class Schema extends Base {
- private $models = [];
-
- private $tables = [];
-
- private $tableNames = [];
-
- function type($type) {
+ /**
+ * Map a database column type to a GraphQL type.
+ *
+ * @param string $type
+ *
+ * @return string
+ */
+ public function type(string $type): string {
+ //strip length and modifiers so raw database types map correctly:
+ //"varchar(191)" -> "varchar", "int unsigned" -> "int"
$compare = strtolower($type);
+ $compare = preg_replace('/[\s(].*$/', '', $compare);
switch ($compare) {
case 'int':
+ case 'integer':
case 'tinyint':
case 'smallint':
+ case 'smallinteger':
+ case 'mediumint':
+ case 'bigint':
+ case 'serial':
+ case 'bigserial':
case 'double':
case 'array':
$type = 'Int';
@@ -53,12 +63,15 @@ class Schema extends Base {
break;
case 'decimal':
+ case 'float':
+ case 'real':
$type = 'Float';
break;
- case 'array':
- $type = '[Int]';
+ case 'boolean':
+ case 'bool':
+ $type = 'Boolean';
break;
@@ -71,6 +84,15 @@ class Schema extends Base {
case 'timestamp':
case 'longtext':
case 'tinytext':
+ case 'json':
+ case 'blob':
+ $type = 'String';
+
+ break;
+
+ default:
+ //unknown types fall back to String so one exotic column
+ //can never break the entire generated schema
$type = 'String';
break;
@@ -79,15 +101,21 @@ class Schema extends Base {
return $type;
}
- function types() {
+ /**
+ * Build GraphQL type definitions from database tables.
+ *
+ * @return array<string, mixed>
+ */
+ public function types(): array {
$db = \Vvveb\System\Db::getInstance();
- $tables = $db->getTableNames(DB_NAME);
- $types = include(DIR_APP . 'types.php') ?? [];
+ $tables = $db->getTableNames(DB_NAME);
+ $typesFile = __DIR__ . '/../types.php';
+ $types = (file_exists($typesFile) ? include ($typesFile) : []) ?? [];
foreach ($tables as $table) {
//skip cart table
- if ($table == 'cart') {
+ if ($table === 'cart') {
continue;
}
$meta = $db->getColumnsMeta($table, true);
@@ -100,12 +128,12 @@ class Schema extends Base {
$col['description'] = $column['c'] ?? '';
//column is id (input) type
- if (substr_compare($name, '_id', -3 ,3) === 0) {
+ if (substr_compare($name, '_id', -3, 3) === 0) {
$type = 'ID';
- $relation = substr($name,0, -3);
+ $relation = substr($name, 0, -3);
- if ($relation != $table && strpos($table, $relation) === 0) {
- $relationType = dashesToCamelCase($table, '_') . 'Type';
+ if ($relation !== $table && str_starts_with($table, $relation)) {
+ $relationType = dashesToCamelCase($table, '_') . 'Type';
$typeTable = $table;
$pos = strpos($typeTable, $relation . '_');
@@ -116,19 +144,19 @@ class Schema extends Base {
if ($pos === 0) {
$typeTable = substr_replace($typeTable, '', $pos, 3);
- $relationType = dashesToCamelCase($typeTable, '_') . 'Type';
+ $relationType = dashesToCamelCase($typeTable, '_') . 'Type';
}
$typeTable = Plural::tablePlural($typeTable);
}
- if (! isset($types[$relation]['properties'][$typeTable])) {
+ if (!isset($types[$relation]['properties'][$typeTable])) {
$types[$relation]['properties'][$typeTable] = ['name' => $table, 'type' => "[$relationType]"];
}
}
} else {
if (in_array($name, $tables)) {
- $type = dashesToCamelCase($name, '_') . 'Type'; //. 'Input';
+ $type = dashesToCamelCase($name, '_') . 'Type';
} else {
$type = $this->type($column['t'] ?? 'Int');
}
@@ -139,7 +167,7 @@ class Schema extends Base {
$cols[$column['name']] = $col;
}
- if ($table == 'product_option' || $table == 'product_option_value') {
+ if ($table === 'product_option' || $table === 'product_option_value') {
$cols += [
'name' => ['name' => 'name', 'type' => 'string'],
];
@@ -150,7 +178,6 @@ class Schema extends Base {
'properties' => $cols,
];
- //$types[$table] = isset($types[$table]) ? array_replace_recursive($types[$table], $data) : $data;
if (isset($types[$table]['properties'])) {
$data['properties'] += $types[$table]['properties'];
}
@@ -158,22 +185,25 @@ class Schema extends Base {
$types[$table] = $data;
//for content table also add name and content columns to relation
- if (substr_compare($table, '_content', -8 ,8) === 0) {
- $relation = substr($table, 0, -8);
+ if (substr_compare($table, '_content', -8, 8) === 0) {
+ $relation = substr($table, 0, -8);
$types[$relation]['properties']['name'] = ['type' => 'char', 'name' => 'name'];
$types[$relation]['properties']['content'] = ['type' => 'char', 'name' => 'content'];
$types[$relation]['properties']['slug'] = ['type' => 'char', 'name' => 'slug'];
}
}
- //$types = array_replace($types, include(DIR_APP . 'types.php'));
-
- list($types) = Event :: trigger(__CLASS__,__FUNCTION__, $types);
+ [$types] = Event::trigger(__CLASS__, __FUNCTION__, $types);
return $types;
}
- function models() {
+ /**
+ * Parse SQL files to extract model method/param definitions.
+ *
+ * @return array<string, mixed>
+ */
+ public function models(): array {
$dirSQL = DIR_ROOT . 'admin' . DS . 'sql' . DS . DB_ENGINE . DS;
$sqlp = new Sqlp();
$models = [];
@@ -185,7 +215,7 @@ class Schema extends Base {
$tree = $sqlp->getModel();
$model = basename($file, '.sql');
//skip cart table
- if ($model == 'cart') {
+ if ($model === 'cart') {
continue;
}
@@ -194,12 +224,17 @@ class Schema extends Base {
}
}
- list($models) = Event :: trigger(__CLASS__,__FUNCTION__, $models);
+ [$models] = Event::trigger(__CLASS__, __FUNCTION__, $models);
return $models;
}
- function schema() {
+ /**
+ * Generate the full GraphQL schema string from types and models.
+ *
+ * @return string
+ */
+ public function schema(): string {
$typesText = '';
$types = $this->types();
@@ -207,7 +242,7 @@ class Schema extends Base {
$properties = '';
foreach ($attrs['properties'] as $name => $property) {
- if (substr_compare($name, '_id', -3 ,3) === 0) {
+ if (substr_compare($name, '_id', -3, 3) === 0) {
$type = 'ID';
} else {
$type = $this->type($property['type'] ?? 'Int');
@@ -234,7 +269,7 @@ class Schema extends Base {
$connectionsText = '';
foreach ($models as $model => $methods) {
- $modelComment = "\n\n # " . humanReadable($model) . "\n";
+ $modelComment = "\n\n # " . humanReadable($model) . "\n";
$mutationsText .= $modelComment;
$queriesText .= $modelComment;
@@ -247,12 +282,12 @@ class Schema extends Base {
$parameters = '';
foreach ($params as $name => $param) {
- if ($param['in_out'] == 'IN') {
+ if ($param['in_out'] === 'IN') {
$name = $param['name'];
$type = $this->type($param['type'] ?? 'Int');
- if (substr_compare($name, '_id', -3 ,3) === 0) {
- if ($param['type'] == 'ARRAY') {
+ if (substr_compare($name, '_id', -3, 3) === 0) {
+ if ($param['type'] === 'ARRAY') {
$type = '[ID]';
} else {
$type = 'ID';
@@ -271,7 +306,7 @@ class Schema extends Base {
$parameters = rtrim($parameters, ', ');
$type = dashesToCamelCase($model, '_');
- if (strpos($method, 'get') === 0) {
+ if (str_starts_with($method, 'get')) {
if ($model == 'category' || $model == 'filter' || $model == 'stat') {
//$type = 'Taxonomy';
}
@@ -279,7 +314,7 @@ class Schema extends Base {
$return = $type . 'Type';
$methodText = " $methodName($parameters):{$return}\n";
- if (strpos($method, 'getAll') === 0) {
+ if (str_starts_with($method, 'getAll')) {
$return = "[{$type}Type]";
$modelPlural = lcfirst(dashesToCamelCase(Plural::tablePlural($model), '_'));
$methodText = " $modelPlural($parameters):{$type}Connection\n";
@@ -288,7 +323,7 @@ class Schema extends Base {
"type {$type}Connection {\n nodes:[{$type}Type!]!\n pageInfo:PageInfo!\n}\n";
}
- if ($method == 'get') {
+ if ($method === 'get') {
$modelName = lcfirst(dashesToCamelCase($model, '_'));
$methodText = " $modelName($parameters):{$return}\n";
}
@@ -303,58 +338,61 @@ class Schema extends Base {
}
$cache = Cache::getInstance();
- $json = $cache->cache(APP,'graphql-schema',function () {
+ $json = $cache->cache(APP, 'graphql-schema', function() {
$site = siteSettings();
- $data = Sites :: getSiteData();
+ $data = Sites::getSiteData();
- $json = [];
+ $json = [];
$json['types'] = $this->types();
return $json;
}, 259200);
- $text = <<<GQL
-type PageInfo {
- count: Int
- page: Int
- limit: Int
- endCursor: String
- hasNextPage: Boolean!
- hasPreviousPage: Boolean!
- startCursor: String
-}
-
-$connectionsText
+ return <<<GQL
+ type PageInfo {
+ count: Int
+ page: Int
+ limit: Int
+ endCursor: String
+ hasNextPage: Boolean!
+ hasPreviousPage: Boolean!
+ startCursor: String
+ }
-$typesText
+ $connectionsText
-type RootQueryType {
-
- cart(cartId:ID!):CartType
+ $typesText
-$queriesText
-}
+ type RootQueryType {
-type MutationType {
+ cart(cartId:ID!):CartType
- createCart:CartType
- addCart(cartId:ID!, productId:ID!, quantity:Int, options:String, productVariantId:ID, subscriptionPlanId:ID):CartType
- updateCart(cartId:ID!, key:String!, quantity:Int!, options:String, productVariantId:ID, subscriptionPlanId:ID):CartType
- removeCart(cartId:ID!, key:[String!]!):CartType
+ $queriesText
+ }
-$mutationsText
-}
+ type MutationType {
-schema {
- query:RootQueryType
- mutation:MutationType
-}
-GQL;
+ createCart:CartType
+ addCart(cartId:ID!, productId:ID!, quantity:Int, options:String, productVariantId:ID, subscriptionPlanId:ID):CartType
+ updateCart(cartId:ID!, key:String!, quantity:Int!, options:String, productVariantId:ID, subscriptionPlanId:ID):CartType
+ removeCart(cartId:ID!, key:[String!]!):CartType
+
+ $mutationsText
+ }
- return $text;
+ schema {
+ query:RootQueryType
+ mutation:MutationType
+ }
+ GQL;
}
- function index() {
+ /**
+ * Output the GraphQL schema as text.
+ *
+ * @return void
+ */
+ public function index(): void {
$text = $this->schema();
$this->response->setType('text');
$this->response->output($text);
diff --git a/graphql/index.php b/graphql/index.php
old mode 100644
new mode 100755
index cfe181e..130e992
--- a/graphql/index.php
+++ b/graphql/index.php
@@ -19,8 +19,8 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
+defined('APP') || define('APP', 'graphql');
-define('APP', 'graphql');
-//define('DISABLE_PLUGIN_ON_ERORR', true);
-
-return include __DIR__ . '/../index.php';
+if (!defined('DIR_ROOT')) {
+ return include __DIR__ . '/../index.php';
+}
diff --git a/graphql/transform/product.php b/graphql/transform/product.php
old mode 100644
new mode 100755
index 7e3a780..7dd18ad
--- a/graphql/transform/product.php
+++ b/graphql/transform/product.php
@@ -27,7 +27,6 @@ use Vvveb\System\Traits\Product as ProductTrait;
#[\AllowDynamicProperties]
class Product extends Base {
- //use ProductTrait;
use ProductTrait {
product as get;
products as getAll;
diff --git a/graphql/types.php b/graphql/types.php
old mode 100644
new mode 100755
index 26003b7..7de516e
--- a/graphql/types.php
+++ b/graphql/types.php
@@ -161,9 +161,9 @@ return
'type' => 'String',
],
'weight_formatted' => [
- 'name' => 'price_tax',
+ 'name' => 'weight_formatted',
'description' => '',
- 'type' => 'Float',
+ 'type' => 'String',
],
],
],
diff --git a/plugins/contact-form b/plugins/contact-form
index 0412f5d..4a66364 160000
--- a/plugins/contact-form
+++ b/plugins/contact-form
@@ -1 +1 @@
-Subproject commit 0412f5d67aa35e5362328a84f27861ec904747b1
+Subproject commit 4a66364d33e24151a02651bd4b199fd63491f691
diff --git a/plugins/payment b/plugins/payment
index 86742ac..bccdb06 160000
--- a/plugins/payment
+++ b/plugins/payment
@@ -1 +1 @@
-Subproject commit 86742acdef161cbe49b62d1115fa3c59d10dc5d1
+Subproject commit bccdb06d9054a64054ede2ff695fb67b285baf20
diff --git a/plugins/shipping b/plugins/shipping
index 6612fd9..11d75d5 160000
--- a/plugins/shipping
+++ b/plugins/shipping
@@ -1 +1 @@
-Subproject commit 6612fd91bed587f1c5f616464aec175872fcd34a
+Subproject commit 11d75d55401b0b0539f76fb1e521a8cdff761ea3
diff --git a/rest/controller/base.php b/rest/controller/base.php
old mode 100644
new mode 100755
index f803276..5d81f9d
--- a/rest/controller/base.php
+++ b/rest/controller/base.php
@@ -22,10 +22,10 @@
namespace Vvveb\Controller;
-use \Vvveb\System\Core\FrontController;
use function Vvveb\__;
use function Vvveb\config;
use function Vvveb\siteSettings;
+use Vvveb\System\Core\FrontController;
use Vvveb\System\Core\Request;
use Vvveb\System\Core\Response;
use Vvveb\System\Event;
@@ -38,12 +38,18 @@ use Vvveb\System\User\Admin;
class Base {
use Permission;
- protected $global = [];
+ /** @var array<string, mixed> */
+ protected array $global = [];
- function auth() {
+ /**
+ * Authenticate the current admin user via HTTP or token-based auth.
+ *
+ * @return void
+ */
+ public function auth(): void {
$admin = Admin::current();
- if (! $admin) {
+ if (!$admin) {
$authMode = config(APP . '.auth.mode');
if ($authMode == 'http') {
@@ -51,6 +57,7 @@ class Base {
$user = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'] ?? '';
$loginData = compact('user', 'password');
+ $feedback = [];
if ($userInfo = Admin::login($loginData, [], $feedback)) {
} else {
@@ -59,7 +66,7 @@ class Base {
$message = __('Auth failed!');
if (DEBUG) {
- $message .= ' ' . $feedback['message'] ?? [];
+ $message .= ' ' . ($feedback['message'] ?? '');
$message .= " auth.mode = $authMode";
}
//FrontController::notFound(false, $message, 403);
@@ -82,21 +89,21 @@ class Base {
$headers = getallheaders();
$token = $headers['Bearer'] ?? $_SERVER['HTTP_BEARER'] ?? null;
- if (! $token) {
+ if (!$token) {
$token = $headers['Authorization'] ?? $_SERVER['HTTP_AUTHORIZATION'] ?? '';
$token = trim(substr($token, 6)) ?: $this->request->get['_token'] ?? false;
}
if ($token) {
+ $feedback = [];
if ($userInfo = Admin::auth($token, [], $feedback)) {
} else {
$this->response->addHeader('HTTP/1.0 401 Unauthorized');
$message = __('Auth failed!');
if (DEBUG) {
- $message .= ' ' . $feedback['message'] ?? [];
+ $message .= ' ' . ($feedback['message'] ?? '');
$message .= " auth.mode = $authMode";
- $message .= " token = $token";
}
//FrontController::notFound(false, $message, 403);
$this->notFound($message, 403);
@@ -108,7 +115,6 @@ class Base {
if (DEBUG) {
$message .= __('No credentials!');
$message .= " auth.mode = $authMode";
- $message .= " token = $token";
}
//FrontController::notFound(false, $message, 403);
$this->notFound($message, 403);
@@ -118,19 +124,32 @@ class Base {
}
}
- protected function initEcommerce($countryId, $regionId) {
+ /**
+ * Initialize ecommerce tax rules for the given region.
+ *
+ * @param int $countryId
+ * @param int $regionId
+ *
+ * @return void
+ */
+ protected function initEcommerce(int $countryId, int $regionId): void {
$tax = \Vvveb\System\Cart\Tax::getInstance();
$tax->setRegionRules($countryId, $regionId, 'store');
}
- function init() {
+ /**
+ * Initialize the REST controller: set up request/response/session, authenticate, and load global settings.
+ *
+ * @return string|null HTTP method for write operations, or null
+ */
+ public function init(): ?string {
$this->response = Response::getInstance();
$this->request = Request::getInstance();
$this->session = Session::getInstance();
$this->response->setType('json');
- if (! REST) {
+ if (!REST) {
$this->notFound(__('REST is disabled!'), 404);
}
@@ -141,7 +160,7 @@ class Base {
$permission = str_replace('/rest/', '', ($this->request->get['route'] ?? '') . '/' . $method);
//Check permissions
- $className = get_class($this);
+ $className = static::class;
if ($className != 'Vvveb\Controller\Error403') {
$this->permission($permission);
@@ -150,9 +169,10 @@ class Base {
Plugins :: loadPlugins();
$site = siteSettings();
- list($site) = Event::trigger(__CLASS__, __FUNCTION__, $site);
+ [$site] = Event::trigger(__CLASS__, __FUNCTION__, $site);
- $this->global['site_id'] = SITE_ID ?? 1;
+ $user = Admin::current();
+ $this->global['site_id'] = SITE_ID;
$this->global['language_id'] = $this->session->get('language_id') ?? $site['language_id'] ?? 1;
$this->global['default_language_id'] = $this->session->get('default_language_id') ?? $site['language_id'] ?? 1;
$this->global['limit'] = 10;
@@ -160,7 +180,7 @@ class Base {
$this->global['user_id'] = $user['user_id'] ?? false;
$this->global['user_group_id'] = $user['user_group_id'] ?? 1;
$this->global['site'] = &$site;
- $this->global['user'] = $user ?? [];
+ $this->global['user'] = $user;
$language_id = $this->global['language_id'];
@@ -174,52 +194,55 @@ class Base {
$this->global['site'] = &$site;
- list($this->global) = Event::trigger(__CLASS__, __FUNCTION__ . ':after', $this->global);
+ [$this->global] = Event::trigger(__CLASS__, __FUNCTION__ . ':after', $this->global);
if (in_array($method, ['post', 'put', 'delete', 'patch'])) {
return $method;
}
+
+ return null;
}
/**
- * Call this function if the requeste information was not found, for example if the specifed news, image, profile etc is not found then call this function.
- * It shows a "Not found" page and it also send 404 http status code, this is usefull for search engines etc.
+ * Call this function if the requested information was not found, for example if the specified news, image, profile etc is not found then call this function.
+ * It shows a "Not found" page and it also sends 404 http status code, this is useful for search engines etc.
+ *
+ * @param array<string, mixed>|string|null $message
+ * @param int $statusCode
+ * @param bool $service
*
- * @param unknown_type $code
- * @param mixed $service
- * @param mixed $statusCode
- * @param null|mixed $message
+ * @return never
*/
- protected function notFound($message = null, $statusCode = 404, $service = false) {
+ protected function notFound(array|string|null $message = null, int $statusCode = 404, bool $service = false): never {
$response = Response::getInstance();
http_response_code($statusCode);
$output = [
'openapi' => '3.1.0',
- 'info' => [
- 'title' => 'Vvveb',
+ 'info' => [
+ 'title' => 'Vvveb',
'description' => 'Vvveb',
- 'version' => '1',
- 'contact' => [
+ 'version' => '1',
+ 'contact' => [
],
],
- 'servers' => [['url' => '/rest']],
- 'tags' => [['name' => 'v1', 'description' => '']],
- 'security' => [['bearerAuth' => [], 'basicAuth' => []]],
+ 'servers' => [['url' => '/rest']],
+ 'tags' => [['name' => 'v1', 'description' => '']],
+ 'security' => [['bearerAuth' => [], 'basicAuth' => []]],
'components' => [
'securitySchemes' => [
'bearerAuth' => [
- 'type' => 'http',
- 'scheme' => 'bearer',
- 'in' => 'header',
+ 'type' => 'http',
+ 'scheme' => 'bearer',
+ 'in' => 'header',
'description' => 'Use api auth token as credential',
],
'basicAuth' => [
- 'type' => 'http',
- 'scheme' => 'basic',
- 'in' => 'header',
- 'username' => '',
- 'password' => '',
+ 'type' => 'http',
+ 'scheme' => 'basic',
+ 'in' => 'header',
+ 'username' => '',
+ 'password' => '',
'description' => 'Use admin user and password as credentials',
],
],
@@ -229,13 +252,13 @@ class Base {
];
if (is_array($message)) {
- $output = $output + $message;
+ $output += $message;
} else {
$output['message'] = $message;
}
$response->output($output);
- die();
+ exit();
}
}
diff --git a/rest/controller/cart/cart.php b/rest/controller/cart/cart.php
old mode 100644
new mode 100755
index a62a5a7..1d8f629
--- a/rest/controller/cart/cart.php
+++ b/rest/controller/cart/cart.php
@@ -25,23 +25,3 @@ namespace Vvveb\Controller\Cart;
include DIR_ROOT . 'app' . DS . 'controller' . DS . 'cart' . DS . 'coupon-trait.php';
include DIR_ROOT . 'app' . DS . 'controller' . DS . 'cart' . DS . 'cart.php';
-
-class CartBase extends Cart {
- function index() {
- echo 'asd';
-
- die('asd');
- }
-
- function delete() {
- return $this->action('remove');
- }
-
- function put() {
- return $this->action('update');
- }
-
- function post() {
- return $this->action('add');
- }
-}
diff --git a/rest/controller/crud.php b/rest/controller/crud.php
old mode 100644
new mode 100755
index c9e7c5c..aca0eab
--- a/rest/controller/crud.php
+++ b/rest/controller/crud.php
@@ -32,39 +32,54 @@ class Crud extends Base {
CrudTrait::index as get;
}
- protected $fullPost = true;
+ //protected bool $fullPost = true;
- function validate($method, $ignoreMissing = false) {
+ public function __construct() {
+ $this->fullPost = true;
+ }
+
+ /**
+ * Validate the incoming request data against the model.
+ *
+ * @param string $method
+ * @param bool $ignoreMissing
+ *
+ * @return array<int, string>|true Array of error messages or true on success
+ */
+ public function validate(string $method, bool $ignoreMissing = false): array|true {
$model = model($this->type);
$data = $this->request->post ?? [];
- if ($model) {
- $errors = $model->validate($data, $method, $this->type, $ignoreMissing);
+ $errors = $model->validate($data, $method, $this->type, $ignoreMissing);
- if ($errors) {
- return $errors;
- } else {
- return true;
- }
+ if ($errors) {
+ return $errors;
+ } else {
+ return true;
}
-
- $this->redirect = false;
-
- return [sprintf(__('%s not found!'), ucfirst($this->type))];
}
- function index() {
+ /**
+ * Retrieve a single resource by ID.
+ *
+ * @return array<string, mixed>
+ */
+ public function index(): array {
$data = $this->get();
- if (! $data || (! isset($data[$this->type . '_id']))) {
+ if (!$data || (!isset($data[$this->type . '_id']))) {
return $this->notFound(sprintf(__('%s not found!'), ucfirst($this->type)));
}
return $data;
}
- //create
- function post() {
+ /**
+ * Create a new resource.
+ *
+ * @return array<string, mixed>
+ */
+ public function post(): array {
if (($errors = $this->validate('add')) === true) {
$this->redirect = false;
@@ -74,8 +89,12 @@ class Crud extends Base {
}
}
- //edit
- function patch() {
+ /**
+ * Update an existing resource via PATCH.
+ *
+ * @return array<string, mixed>
+ */
+ public function patch(): array {
if (($errors = $this->validate('edit')) === true) {
$this->redirect = false;
@@ -85,8 +104,12 @@ class Crud extends Base {
}
}
- //upsert
- function put() {
+ /**
+ * Upsert a resource (create or update).
+ *
+ * @return array<string, mixed>
+ */
+ public function put(): array {
//if id update else create
if (($errors = $this->validate('edit', true)) === true) {
return $this->save();
@@ -95,10 +118,14 @@ class Crud extends Base {
}
}
- //delete
- function delete() {
+ /**
+ * Delete a resource by ID.
+ *
+ * @return array<string, mixed>
+ */
+ public function delete(): array {
$type = $this->type;
- $type_id = $this->type_id ?? "{$type}_id";
+ $type_id = $this->type_id ?: "{$type}_id";
$data_id = $this->request->post[$type_id] ?? $this->request->get[$type_id] ?? false;
$response = ['deleted' => false];
@@ -108,9 +135,7 @@ class Crud extends Base {
$data_id = [$data_id];
}
- if (! isset($this->modelName)) {
- $modelName = $type;
- }
+ $modelName = $this->modelName ?: $type;
$model = model($modelName);
$options = [$type_id => $data_id] + $this->global;
@@ -126,7 +151,7 @@ class Crud extends Base {
return $this->notFound($response, 410);
}
} else {
- $response['message'] = 'Error deleting %s!';
+ $response['message'] = sprintf('Error deleting %s!', $name);
return $this->notFound($response, 500);
}
diff --git a/rest/controller/default/crud.php b/rest/controller/default/crud.php
old mode 100644
new mode 100755
index 1e60c9a..f6af385
--- a/rest/controller/default/crud.php
+++ b/rest/controller/default/crud.php
@@ -26,14 +26,17 @@ use Vvveb\Controller\Crud as CrudBase;
#[\AllowDynamicProperties]
class Crud extends CrudBase {
- protected $type = '';
+ /** @var string The resource type/schema name */
+ protected string $type = '';
- function __construct() {
- $urlData = \Vvveb\System\Routes::getUrlData();
- $this->type = $urlData['schema'];
+ /**
+ * Constructor - resolves the resource type from the URL data.
+ */
+ public function __construct() {
+ $urlData = \Vvveb\System\Routes::getUrlData();
+ $this->type = $urlData['schema'];
if ($this->type) {
$this->module = $this->type;
}
}
-
}
diff --git a/rest/controller/default/index.php b/rest/controller/default/index.php
old mode 100644
new mode 100755
index e78fd05..f064065
--- a/rest/controller/default/index.php
+++ b/rest/controller/default/index.php
@@ -26,10 +26,14 @@ use Vvveb\Controller\Listing;
#[\AllowDynamicProperties]
class Index extends Listing {
- protected $type = '';
-
- function __construct() {
- $urlData = \Vvveb\System\Routes::getUrlData();
- $this->type = $urlData['schema'];
+ /** @var string The resource type/schema name */
+ protected string $type = '';
+
+ /**
+ * Constructor - resolves the resource type from the URL data.
+ */
+ public function __construct() {
+ $urlData = \Vvveb\System\Routes::getUrlData();
+ $this->type = $urlData['schema'];
}
}
diff --git a/rest/controller/error403.php b/rest/controller/error403.php
old mode 100644
new mode 100755
index 64a8106..514646c
--- a/rest/controller/error403.php
+++ b/rest/controller/error403.php
@@ -24,7 +24,12 @@ namespace Vvveb\Controller;
#[\AllowDynamicProperties]
class Error403 extends Base {
- function index() {
+ /**
+ * Return a 403 error response.
+ *
+ * @return array{message: string, code: int}
+ */
+ public function index(): array {
$this->response->setType('json');
return ['message' => $this->view->message, 'code' => $this->view->code ?? 403];
diff --git a/rest/controller/error404.php b/rest/controller/error404.php
old mode 100644
new mode 100755
index bf72bcf..92e43f9
--- a/rest/controller/error404.php
+++ b/rest/controller/error404.php
@@ -24,7 +24,12 @@ namespace Vvveb\Controller;
#[\AllowDynamicProperties]
class Error404 extends Base {
- function index() {
+ /**
+ * Return a 404 error response.
+ *
+ * @return array{message: string, code: int, file?: string}
+ */
+ public function index(): array {
$this->response->setType('json');
$return = ['message' => $this->view->message ?? 'Route not found!', 'code' => $this->view->code ?? 404];
diff --git a/rest/controller/error500.php b/rest/controller/error500.php
old mode 100644
new mode 100755
index 55f9344..68d2958
--- a/rest/controller/error500.php
+++ b/rest/controller/error500.php
@@ -24,7 +24,12 @@ namespace Vvveb\Controller;
#[\AllowDynamicProperties]
class Error500 extends Base {
- function index() {
+ /**
+ * Return a 500 error response.
+ *
+ * @return array{message?: string, file?: string, line_no?: string, line?: string, lines?: string, trace?: string, codeLines?: string, code: int}
+ */
+ public function index(): array {
$this->response->setType('json');
if (DEBUG) {
diff --git a/rest/controller/index.php b/rest/controller/index.php
old mode 100644
new mode 100755
index a66f996..11fe94c
--- a/rest/controller/index.php
+++ b/rest/controller/index.php
@@ -28,6 +28,7 @@ use function Vvveb\reconstructJson;
use function Vvveb\siteSettings;
use Vvveb\System\Cache;
use Vvveb\System\Core\View;
+use Vvveb\System\Db;
use Vvveb\System\Event;
use Vvveb\System\Functions\Plural;
use Vvveb\System\Sites;
@@ -36,20 +37,69 @@ use function Vvveb\url;
#[\AllowDynamicProperties]
class Index extends Base {
- function type($type) {
+ /**
+ * Map a database column type to an OpenAPI schema type.
+ *
+ * @param string $type
+ *
+ * @return string
+ */
+ public function type(string $type): string {
+ //strip length and modifiers so raw database types map correctly:
+ //"varchar(191)" -> "varchar", "int unsigned" -> "int"
$type = strtolower($type);
+ $type = preg_replace('/[\s(].*$/', '', $type);
switch ($type) {
case 'int':
+ case 'integer':
case 'tinyint':
+ case 'smallint':
+ case 'smallinteger':
+ case 'mediumint':
+ case 'bigint':
+ case 'serial':
+ case 'bigserial':
$type = 'integer';
break;
+ case 'decimal':
+ case 'float':
+ case 'double':
+ case 'real':
+ $type = 'number';
+
+ break;
+
+ case 'boolean':
+ case 'bool':
+ $type = 'boolean';
+
+ break;
+
+ case 'array':
+ $type = 'array';
+
+ break;
+
case 'varchar':
case 'char':
- case 'datetime':
+ case 'text':
+ case 'tinytext':
case 'longtext':
+ case 'enum':
+ case 'date':
+ case 'datetime':
+ case 'timestamp':
+ case 'json':
+ $type = 'string';
+
+ break;
+
+ default:
+ //unknown types fall back to string so one exotic column
+ //can never poison the generated specification
$type = 'string';
break;
@@ -58,7 +108,12 @@ class Index extends Base {
return $type;
}
- function paths() {
+ /**
+ * Build OpenAPI paths from database tables and route configurations.
+ *
+ * @return array<string, mixed>
+ */
+ public function paths(): array {
$routes = config('rest-routes');
$paths = [];
$sqlp = new Sqlp();
@@ -75,7 +130,7 @@ class Index extends Base {
$routeSchemas = array_values($routeSchemas);
$this->tables = [];
- $db = \Vvveb\System\Db::getInstance();
+ $db = Db::getInstance();
$tables = $db->getTableNames(DB_NAME);
$routesNew = [];
@@ -88,7 +143,7 @@ class Index extends Base {
}
$this->tables[$table] = $cols;
- if (! in_array($table, $routeSchemas)) {
+ if (!in_array($table, $routeSchemas)) {
if (file_exists($dirSQL . $table . '.sql')) {
$plural = Plural::tablePlural($table);
$routes['/rest/' . $plural] = ['module' => 'default', 'methods' => ['get', 'post'], 'schema' => $table];
@@ -96,7 +151,6 @@ class Index extends Base {
}
}
}
- //echo var_export($routesNew, true);
foreach ($routes as $route => $options) {
$route = str_replace(['/rest', '/#', '#'], ['', '/{', '}'], $route);
@@ -119,7 +173,6 @@ class Index extends Base {
}
}
- //$responses
$meth = ['responses' => []];
$ok = [
'description' => 'OK',
@@ -142,12 +195,12 @@ class Index extends Base {
$action = $actions[$method];
- if ($method == 'get' && ! isset($methods['delete'])) {
+ if ($method == 'get' && !isset($methods['delete'])) {
$action = 'getAll';
}
if (($tree && isset($tree[$action])) &&
- ($method != 'get' || ($method == 'get' && ! $getParams))) {
+ ($method != 'get' || ($method == 'get' && !$getParams))) {
foreach ($tree[$action]['params'] as $p) {
if ($p['in_out'] == 'OUT') {
continue;
@@ -165,13 +218,11 @@ class Index extends Base {
$params[$name]['type'] = $this->type($p['type'] ?? 'integer');
if ($params[$name]['type'] == 'array' && isset($this->tables[$name])) {
- $encoding[$name]['explode'] = true;
- $encoding[$name]['style'] = 'deepObject';
- //$encoding[$name]['contentType'] = 'application/x-www-form-urlencoded';
+ $encoding[$name]['explode'] = true;
+ $encoding[$name]['style'] = 'deepObject';
$params[$name]['type'] = 'object';
$params[$name]['style'] = 'deepObject';
$params[$name]['explode'] = true;
- //$params[$name]['contentEncoding'] = 'text/plain';
$properties = [];
@@ -186,14 +237,14 @@ class Index extends Base {
}
$properties[$col['name']] = ['type' => $this->type($col['t'])];
- if ($col['d'] === NULL || $col['d'] == 'NULL') {
+ if ($col['d'] === null || $col['d'] == 'NULL') {
$properties[$col['name']]['required'] = true;
} else {
$properties[$col['name']]['required'] = false;
}
}
- if (in_array($name,['post_content', 'product_content'])) {
+ if (in_array($name, ['post_content', 'product_content'])) {
$params[$name]['type'] = 'array';
$params[$name]['items']['type'] = 'object';
$params[$name]['items']['explode'] = true;
@@ -201,28 +252,24 @@ class Index extends Base {
$params[$name]['items']['properties'] = $properties;
$encoding[$name]['items']['explode'] = true;
$encoding[$name]['items']['style'] = 'deepObject';
- //$encoding[$name]['items']['type'] = 'object';
- //$encoding[$name]['type'] = 'array';
} else {
$params[$name]['properties'] = $properties;
}
}
- if ($params[$name]['type'] == 'array' && substr_compare($name, '_id', -3 ,3) === 0) {
- $params[$name]['items']['type'] = 'integer';
- //$params[$name]['items']['explode'] = true;
+ if ($params[$name]['type'] == 'array' && substr_compare($name, '_id', -3, 3) === 0) {
+ $params[$name]['items']['type'] = 'integer';
$params[$name]['style'] = 'deepObject';
$params[$name]['explode'] = true;
$encoding[$name]['items']['explode'] = true;
$encoding[$name]['items']['style'] = 'deepObject';
$encoding[$name]['explode'] = true;
$encoding[$name]['style'] = 'deepObject';
- //$encoding[$name]['items']['style'] = 'deepObject';
}
} else {
$param['name'] = $p['name'];
$param['in'] = 'query';
- $param['required'] = 'false';
+ $param['required'] = false;
$param['description'] = $p['comment'] ?? '';
$param['schema']['type'] = $this->type($p['type'] ?? 'integer');
@@ -237,15 +284,13 @@ class Index extends Base {
foreach ($this->tables[$param['name']] as $col) {
$properties[$col['name']] = ['type' => $this->type($col['t'])];
- if ($col['d'] === NULL || $col['d'] == 'NULL') {
+ if ($col['d'] === null || $col['d'] == 'NULL') {
$properties[$col['name']]['required'] = true;
} else {
$properties[$col['name']]['required'] = false;
}
}
- //$param['name'] .= '[]';
-
if ($param['name'] == 'post_content') {
$param['schema']['type'] = 'array';
$param['schema']['items']['type'] = 'object';
@@ -257,7 +302,7 @@ class Index extends Base {
}
}
- if (! isset($getParams[$param['name']])) {
+ if (!isset($getParams[$param['name']])) {
$getParams[$param['name']] = $param;
}
}
@@ -270,8 +315,8 @@ class Index extends Base {
'application/x-www-form-urlencoded' => [
'encoding' => $encoding,
'schema' => [
- 'type' => 'object',
- 'properties' => $params,
+ 'type' => 'object',
+ 'properties' => $params,
],
],
],
@@ -291,14 +336,17 @@ class Index extends Base {
$paths[$route] = $data;
}
- list($paths) = Event :: trigger(__CLASS__,__FUNCTION__, $paths);
+ [$paths] = Event :: trigger(__CLASS__, __FUNCTION__, $paths);
return $paths;
- $this->response->setType('json');
- $this->response->output($paths);
}
- function schemas() {
+ /**
+ * Build OpenAPI schemas from database table metadata.
+ *
+ * @return array<string, mixed>
+ */
+ public function schemas(): array {
$db = \Vvveb\System\Db::getInstance();
$tables = $db->getTableNames(DB_NAME);
@@ -309,17 +357,20 @@ class Index extends Base {
$cols = [];
foreach ($meta as $column) {
+ $rawType = strtolower($column['t'] ?? 'integer');
$col = [];
$col['name'] = $column['name'] ?? '';
$col['description'] = $column['c'] ?? '';
- $col['type'] = $this->type($column['t'] ?? 'integer');
+ $col['type'] = $this->type($rawType);
- switch ($col['type']) {
- case 'datetime':
- $col['format'] = 'date-time';
- }
+ if ($rawType === 'datetime' || $rawType === 'timestamp' || $rawType === 'date') {
+ $col['format'] = 'date-time';
+ }
+
+ //n holds IS_NULLABLE on mysqli/pgsql ('YES'/'NO') and NOT NULL flag on sqlite (1/0)
+ $nullable = $column['n'] ?? null;
- if (isset($column['c']) && $column['c'] == 'YES') {
+ if ($nullable === 'YES' || $nullable === 0 || $nullable === '0') {
$col['type'] = [$col['type'], 'null'];
}
@@ -336,22 +387,26 @@ class Index extends Base {
$schemas[$table] = $data;
}
- //var_export($schemas);
- list($schemas) = Event :: trigger(__CLASS__,__FUNCTION__, $schemas);
+ [$schemas] = Event :: trigger(__CLASS__, __FUNCTION__, $schemas);
return $schemas;
- $this->response->setType('json');
- $this->response->output($schemas);
}
- public static function getControllerList($app = APP) {
+ /**
+ * Get a list of all controller JSON files for the REST app.
+ *
+ * @param string $app
+ *
+ * @return array<int, string>
+ */
+ public static function getControllerList(string $app = APP): array {
$files = [];
$path = [DIR_ROOT . $app . '/controller/*', DIR_PLUGINS . '*/' . $app . '/controller/*'];
while (count($path) > 0) {
$next = array_shift($path);
- //echo $next . "\n";
- foreach (glob("$next/*.json") as $file) {
+
+ foreach (glob("$next/*.json") ?: [] as $file) {
if (is_dir($file)) {
$path[] = $file;
}
@@ -362,32 +417,39 @@ class Index extends Base {
}
}
- list($files) = Event :: trigger(__CLASS__,__FUNCTION__, $files);
+ [$files] = Event :: trigger(__CLASS__, __FUNCTION__, $files);
return $files;
}
- function renderJson() {
+ /**
+ * Render the OpenAPI JSON template and return it as an array.
+ *
+ * @return array<string, mixed>
+ */
+ public function renderJson(): array {
$htmlView = new View();
- //$htmlView = clone $this->view;
$htmlView->setTheme();
- $htmlView->set(['seo' => []]);
$htmlView->template('openapi.json');
$xml = $htmlView->render(true, false, true);
if ($xml) {
$sxml = \simplexml_load_string($xml, null, LIBXML_NOCDATA | LIBXML_DTDATTR);
- $array = reconstructJson($sxml, true);
- return $array;
- $json = json_encode($array, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
- echo $json;
+ return reconstructJson($sxml, true);
}
+
+ return [];
}
- function api() {
+ /**
+ * Generate and output the full OpenAPI specification.
+ *
+ * @return void
+ */
+ public function api(): void {
$cache = Cache::getInstance();
- $json = $cache->cache(APP,'openapi',function () {
+ $json = $cache->cache(APP, 'openapi', function() {
$site = siteSettings();
$data = Sites :: getSiteData();
@@ -395,14 +457,14 @@ class Index extends Base {
$json['paths'] = $this->paths();
$json['components']['schemas'] = $this->schemas();
- $site = siteSettings(SITE_ID, $this->global['language_id']);
+ $site = siteSettings(SITE_ID, $this->global['language_id']);
$urlParams = ['host' => $data['host'], 'scheme' => isSecure() ? 'https' : 'http'];
- $url = url('/',$urlParams);
+ $url = url('/', $urlParams);
- $json['info']['title'] = $site['description']['title'];
+ $json['info']['title'] = $site['description']['title'];
$json['info']['contact']['email'] = $site['contact-email'];
- $json['info']['contact']['url'] = $url;
- $json['servers'][0]['url'] = url('',$urlParams);
+ $json['info']['contact']['url'] = $url;
+ $json['servers'][0]['url'] = url('', $urlParams);
return $json;
}, 259200);
@@ -411,7 +473,12 @@ class Index extends Base {
$this->response->output($json);
}
- function index() {
- return $this->api();
+ /**
+ * Main index action - delegates to api().
+ *
+ * @return void
+ */
+ public function index(): void {
+ $this->api();
}
}
diff --git a/rest/controller/listing.php b/rest/controller/listing.php
old mode 100644
new mode 100755
index fe36ae8..9984ce8
--- a/rest/controller/listing.php
+++ b/rest/controller/listing.php
@@ -27,26 +27,32 @@ use Vvveb\System\Traits\Crud as CrudTrait;
use Vvveb\System\Traits\Listing as ListingTrait;
class Listing extends Base {
- use ListingTrait, CrudTrait {
+ use CrudTrait, ListingTrait {
ListingTrait::index as get;
CrudTrait::delete insteadof ListingTrait;
}
- function __construct() {
+ /**
+ * Constructor - sets default redirect and fullPost flags.
+ */
+ public function __construct() {
$this->redirect = false;
$this->fullPost = true;
}
- function post() {
+ /**
+ * Create a new resource with validation.
+ *
+ * @return array<string, mixed>
+ */
+ public function post(): array {
$model = model($this->type);
$data = $this->request->post ?? [];
- if ($model) {
- $errors = $model->validate($data, 'add', $this->type);
+ $errors = $model->validate($data, 'add', $this->type);
- if ($errors) {
- $this->notFound(['errors' => $errors], 500);
- }
+ if ($errors) {
+ $this->notFound(['errors' => $errors], 500);
}
$this->redirect = false;
@@ -55,7 +61,12 @@ class Listing extends Base {
return $this->save();
}
- function index() {
+ /**
+ * Retrieve a list of resources with pagination headers.
+ *
+ * @return array<int, mixed>
+ */
+ public function index(): array {
$results = $this->get();
$this->view->success[] = '%s(s) deleted!';
diff --git a/rest/controller/rest.php b/rest/controller/rest.php
old mode 100644
new mode 100755
index 1d2e4c6..5970390
--- a/rest/controller/rest.php
+++ b/rest/controller/rest.php
@@ -22,19 +22,30 @@
namespace Vvveb\Controller;
-use function Vvveb\getCurrency;
+use function Vvveb\isModel;
use function Vvveb\model;
+
use Vvveb\System\Cart\Currency;
use Vvveb\System\Cart\Tax;
use Vvveb\System\Images;
#[\AllowDynamicProperties]
class Rest extends Base {
- private $method = 'GET';
-
- private function processResource(&$resource) {
+ /**
+ * @var string HTTP request method
+ */
+ private string $method = 'GET';
+
+ /**
+ * Process a single resource: apply image URLs, price formatting, and strip passwords.
+ *
+ * @param array<string, mixed> $resource
+ *
+ * @return array<string, mixed>
+ */
+ private function processResource(array &$resource): array {
if (isset($resource['images'])) {
- $resource['images'] = json_decode($resource['images'], 1);
+ $resource['images'] = json_decode($resource['images'], true);
foreach ($resource['images'] as &$image) {
$image = Images::image($image, $this->resource, $this->options['image_size'] ?? 'medium');
@@ -56,7 +67,7 @@ class Rest extends Base {
if (isset($resource['price'])) {
$tax = Tax::getInstance();
$currency = Currency::getInstance();
- $currentCurrency = getCurrency();
+ $currentCurrency = $this->global['currency'] ?? 'usd';
$resource['price_tax'] = $tax->addTaxes($resource['price'], $resource['tax_type_id']);
$resource['price_tax_formatted'] = $currency->format($resource['price_tax']);
@@ -67,28 +78,53 @@ class Rest extends Base {
return $resource;
}
- function index() {
- $this->method = $this->request->method;
+ /**
+ * Main REST index action: routes GET/POST/PUT/DELETE to the appropriate model operations.
+ *
+ * @return void
+ */
+ public function index(): void {
+ //honor the _method override the same way init() does, some servers don't support put/delete
+ $this->method = $this->request->get['_method'] ?? $this->request->getMethod();
$this->resource = $this->request->get['resource'] ?? false;
$this->id = $this->request->get['id'] ?? false;
$this->slug = $this->request->get['slug'] ?? false;
$this->options = $this->request->get ?? [];
- $page = $this->request->get['page'] ?? 1;
- $limit = $this->request->get['limit'] ?? 10;
- $this->global['start'] = ($page - 1) * $limit;
- $this->global['limit'] = $limit;
+ $page = $this->request->get['page'] ?? 1;
+ $limit = $this->request->get['limit'] ?? 10;
+ $this->global['start'] = ($page - 1) * $limit;
+ $this->global['limit'] = $limit;
unset($this->options['resource'], $this->options['id']);
+ $model = null;
+
if ($this->resource) {
- $this->resource = rtrim($this->resource, 's');
- $model = model(rtrim($this->resource, 's')); //singular for model name
+ //resolve the model name: clients may pass singular or plural, try both;
+ //never use rtrim which eats valid trailing s (ex: address -> addre)
+ $candidates = [];
+
+ if (str_ends_with($this->resource, 's')) {
+ $candidates[] = substr($this->resource, 0, -1);
+ }
+
+ $candidates[] = $this->resource;
- if (! $model) {
- return;
+ foreach ($candidates as $candidate) {
+ if (isModel($candidate)) {
+ $model = model($candidate);
+ $this->resource = $candidate;
+ break;
+ }
+ }
+
+ if (!$model) {
+ $this->notFound();
}
+ } else {
+ $this->notFound();
}
$output = [];
@@ -97,7 +133,7 @@ class Rest extends Base {
switch ($this->method) {
case 'GET':
if ($this->id || $this->slug) {
- $options =[];
+ $options = [];
if ($this->id) {
$resource_id = $this->resource . '_id';
@@ -108,46 +144,52 @@ class Rest extends Base {
$options['slug'] = $this->slug;
}
- $output = $model->get($options + $this->options + $this->global);
+ $output = $model->get($options + $this->options + $this->global);
- if ($output ||
- (isset($output[$this->resource . '_id']) ||
- (isset($output[$this->resource]) ||
- $output[$this->resource]))) {
+ if ($output
+ && (isset($output[$this->resource . '_id']) || isset($output[$this->resource]))) {
if (isset($output[$this->resource])) {
$output = $output[$this->resource];
}
$output = $this->processResource($output);
} else {
- return $this->notFound();
+ $this->notFound();
}
} else {
$result = $model->getAll($this->options + $this->global);
- if (isset($result[$this->resource . 's'])) {
- $collection = $result[$this->resource . 's'];
+ //models return rows under the table key, accept plural as well
+ $collection = null;
+
+ foreach ([$this->resource, $this->resource . 's'] as $collectionKey) {
+ if (isset($result[$collectionKey]) && is_array($result[$collectionKey])) {
+ $collection = $result[$collectionKey];
+ break;
+ }
+ }
+ if ($collection !== null) {
foreach ($collection as $id => &$resource) {
$output[] = $this->processResource($resource);
}
} else {
- return $this->notFound();
+ $this->notFound();
}
}
- break;
+ break;
case 'POST':
- break;
+ break;
case 'PUT':
- break;
+ break;
case 'DELETE':
$this->action = 'delete';
- break;
+ break;
}
$this->response->output($output);