Add view classes for articles, banners, languages, menu, newsletter, containers, shop categories, clients, payment methods, products, and search

- Created Articles.php for rendering article views including full articles, miniature lists, and news sections.
- Added Banners.php for handling banner displays.
- Introduced Languages.php for rendering language options.
- Implemented Menu.php for dynamic menu rendering.
- Developed Newsletter.php for newsletter view rendering.
- Created Scontainers.php for rendering specific containers.
- Added ShopCategory.php for category descriptions and product listings.
- Introduced ShopClient.php for managing client-related views such as address editing and order history.
- Implemented ShopPaymentMethod.php for displaying payment methods in the basket.
- Created ShopProduct.php for generating product URLs.
- Added ShopSearch.php for rendering a simple search form.
- Added .htaccess file to enhance security by restricting access to sensitive files and directories.
This commit is contained in:
2026-02-21 23:00:15 +01:00
parent b51244c1d6
commit 3ecbe628dc
435 changed files with 44107 additions and 31270 deletions

148
autoload/api/ApiRouter.php Normal file
View File

@@ -0,0 +1,148 @@
<?php
namespace api;
use Domain\Settings\SettingsRepository;
class ApiRouter
{
private $db;
private $settingsRepo;
public function __construct($db, SettingsRepository $settingsRepo)
{
$this->db = $db;
$this->settingsRepo = $settingsRepo;
}
public function handle(): void
{
if (!headers_sent()) {
header('Content-Type: application/json; charset=utf-8');
}
try {
if (!$this->authenticate()) {
self::sendError('UNAUTHORIZED', 'Invalid or missing API key', 401);
return;
}
$endpoint = trim((string)($_GET['endpoint'] ?? ''));
$action = trim((string)($_GET['action'] ?? ''));
if ($endpoint === '' || $action === '') {
self::sendError('BAD_REQUEST', 'Missing endpoint or action parameter', 400);
return;
}
$controller = $this->resolveController($endpoint);
if ($controller === null) {
self::sendError('NOT_FOUND', 'Unknown endpoint: ' . $endpoint, 404);
return;
}
if (!method_exists($controller, $action)) {
self::sendError('NOT_FOUND', 'Unknown action: ' . $action, 404);
return;
}
$controller->$action();
} catch (\Exception $e) {
self::sendError('INTERNAL_ERROR', 'Internal server error', 500);
}
}
private function authenticate(): bool
{
$headerKey = isset($_SERVER['HTTP_X_API_KEY']) ? $_SERVER['HTTP_X_API_KEY'] : '';
if ($headerKey === '') {
return false;
}
$storedKey = $this->settingsRepo->getSingleValue('api_key');
if ($storedKey === '') {
return false;
}
return hash_equals($storedKey, $headerKey);
}
private function resolveController(string $endpoint)
{
$factories = $this->getControllerFactories();
if (!isset($factories[$endpoint])) {
return null;
}
return $factories[$endpoint]();
}
private function getControllerFactories(): array
{
$db = $this->db;
return [
'orders' => function () use ($db) {
$orderRepo = new \Domain\Order\OrderRepository($db);
$settingsRepo = new \Domain\Settings\SettingsRepository($db);
$productRepo = new \Domain\Product\ProductRepository($db);
$transportRepo = new \Domain\Transport\TransportRepository($db);
$service = new \Domain\Order\OrderAdminService($orderRepo, $productRepo, $settingsRepo, $transportRepo);
return new Controllers\OrdersApiController($service, $orderRepo);
},
'products' => function () use ($db) {
$productRepo = new \Domain\Product\ProductRepository($db);
return new Controllers\ProductsApiController($productRepo);
},
'dictionaries' => function () use ($db) {
$statusRepo = new \Domain\ShopStatus\ShopStatusRepository($db);
$transportRepo = new \Domain\Transport\TransportRepository($db);
$paymentRepo = new \Domain\PaymentMethod\PaymentMethodRepository($db);
return new Controllers\DictionariesApiController($statusRepo, $transportRepo, $paymentRepo);
},
];
}
// =========================================================================
// Static response helpers
// =========================================================================
public static function sendSuccess($data): void
{
http_response_code(200);
echo json_encode(['status' => 'ok', 'data' => $data], JSON_UNESCAPED_UNICODE);
}
public static function sendError(string $code, string $message, int $httpCode = 400): void
{
http_response_code($httpCode);
echo json_encode([
'status' => 'error',
'code' => $code,
'message' => $message,
], JSON_UNESCAPED_UNICODE);
}
public static function getJsonBody(): ?array
{
$raw = file_get_contents('php://input');
if ($raw === '' || $raw === false) {
return null;
}
$data = json_decode($raw, true);
return is_array($data) ? $data : null;
}
public static function requireMethod(string $method): bool
{
$requestMethod = isset($_SERVER['REQUEST_METHOD']) ? strtoupper($_SERVER['REQUEST_METHOD']) : 'GET';
if ($requestMethod !== strtoupper($method)) {
self::sendError('METHOD_NOT_ALLOWED', 'Method ' . $requestMethod . ' not allowed, expected ' . strtoupper($method), 405);
return false;
}
return true;
}
}

View File

@@ -0,0 +1,82 @@
<?php
namespace api\Controllers;
use api\ApiRouter;
use Domain\ShopStatus\ShopStatusRepository;
use Domain\Transport\TransportRepository;
use Domain\PaymentMethod\PaymentMethodRepository;
class DictionariesApiController
{
private $statusRepo;
private $transportRepo;
private $paymentRepo;
public function __construct(
ShopStatusRepository $statusRepo,
TransportRepository $transportRepo,
PaymentMethodRepository $paymentRepo
) {
$this->statusRepo = $statusRepo;
$this->transportRepo = $transportRepo;
$this->paymentRepo = $paymentRepo;
}
public function statuses(): void
{
if (!ApiRouter::requireMethod('GET')) {
return;
}
$statuses = $this->statusRepo->allStatuses();
$result = [];
foreach ($statuses as $id => $name) {
$result[] = [
'id' => (int)$id,
'name' => (string)$name,
];
}
ApiRouter::sendSuccess($result);
}
public function transports(): void
{
if (!ApiRouter::requireMethod('GET')) {
return;
}
$transports = $this->transportRepo->allActive();
$result = [];
foreach ($transports as $transport) {
$result[] = [
'id' => (int)($transport['id'] ?? 0),
'name' => (string)($transport['name_visible'] ?? $transport['name'] ?? ''),
'cost' => (float)($transport['cost'] ?? 0),
];
}
ApiRouter::sendSuccess($result);
}
public function payment_methods(): void
{
if (!ApiRouter::requireMethod('GET')) {
return;
}
$methods = $this->paymentRepo->allActive();
$result = [];
foreach ($methods as $method) {
$result[] = [
'id' => (int)($method['id'] ?? 0),
'name' => (string)($method['name'] ?? ''),
];
}
ApiRouter::sendSuccess($result);
}
}

View File

@@ -0,0 +1,154 @@
<?php
namespace api\Controllers;
use api\ApiRouter;
use Domain\Order\OrderAdminService;
use Domain\Order\OrderRepository;
class OrdersApiController
{
private $service;
private $orderRepo;
public function __construct(OrderAdminService $service, OrderRepository $orderRepo)
{
$this->service = $service;
$this->orderRepo = $orderRepo;
}
public function list(): void
{
if (!ApiRouter::requireMethod('GET')) {
return;
}
$filters = [
'status' => isset($_GET['status']) ? $_GET['status'] : '',
'paid' => isset($_GET['paid']) ? $_GET['paid'] : '',
'date_from' => isset($_GET['date_from']) ? $_GET['date_from'] : '',
'date_to' => isset($_GET['date_to']) ? $_GET['date_to'] : '',
'updated_since' => isset($_GET['updated_since']) ? $_GET['updated_since'] : '',
'number' => isset($_GET['number']) ? $_GET['number'] : '',
'client' => isset($_GET['client']) ? $_GET['client'] : '',
];
$page = max(1, (int)(isset($_GET['page']) ? $_GET['page'] : 1));
$perPage = max(1, min(100, (int)(isset($_GET['per_page']) ? $_GET['per_page'] : 50)));
$result = $this->orderRepo->listForApi($filters, $page, $perPage);
ApiRouter::sendSuccess($result);
}
public function get(): void
{
if (!ApiRouter::requireMethod('GET')) {
return;
}
$id = (int)(isset($_GET['id']) ? $_GET['id'] : 0);
if ($id <= 0) {
ApiRouter::sendError('BAD_REQUEST', 'Missing or invalid id parameter', 400);
return;
}
$order = $this->orderRepo->findForApi($id);
if ($order === null) {
ApiRouter::sendError('NOT_FOUND', 'Order not found', 404);
return;
}
ApiRouter::sendSuccess($order);
}
public function change_status(): void
{
if (!ApiRouter::requireMethod('PUT')) {
return;
}
$id = (int)(isset($_GET['id']) ? $_GET['id'] : 0);
if ($id <= 0) {
ApiRouter::sendError('BAD_REQUEST', 'Missing or invalid id parameter', 400);
return;
}
$body = ApiRouter::getJsonBody();
if ($body === null || !isset($body['status_id'])) {
ApiRouter::sendError('BAD_REQUEST', 'Missing status_id in request body', 400);
return;
}
$statusId = (int)$body['status_id'];
$sendEmail = !empty($body['send_email']);
$order = $this->orderRepo->findRawById($id);
if ($order === null) {
ApiRouter::sendError('NOT_FOUND', 'Order not found', 404);
return;
}
$result = $this->service->changeStatus($id, $statusId, $sendEmail);
ApiRouter::sendSuccess([
'order_id' => $id,
'status_id' => $statusId,
'changed' => !empty($result['result']),
]);
}
public function set_paid(): void
{
if (!ApiRouter::requireMethod('PUT')) {
return;
}
$id = (int)(isset($_GET['id']) ? $_GET['id'] : 0);
if ($id <= 0) {
ApiRouter::sendError('BAD_REQUEST', 'Missing or invalid id parameter', 400);
return;
}
$order = $this->orderRepo->findRawById($id);
if ($order === null) {
ApiRouter::sendError('NOT_FOUND', 'Order not found', 404);
return;
}
$body = ApiRouter::getJsonBody();
$sendEmail = ($body !== null && !empty($body['send_email']));
$this->service->setOrderAsPaid($id, $sendEmail);
ApiRouter::sendSuccess([
'order_id' => $id,
'paid' => 1,
]);
}
public function set_unpaid(): void
{
if (!ApiRouter::requireMethod('PUT')) {
return;
}
$id = (int)(isset($_GET['id']) ? $_GET['id'] : 0);
if ($id <= 0) {
ApiRouter::sendError('BAD_REQUEST', 'Missing or invalid id parameter', 400);
return;
}
$order = $this->orderRepo->findRawById($id);
if ($order === null) {
ApiRouter::sendError('NOT_FOUND', 'Order not found', 404);
return;
}
$this->service->setOrderAsUnpaid($id);
ApiRouter::sendSuccess([
'order_id' => $id,
'paid' => 0,
]);
}
}

View File

@@ -0,0 +1,251 @@
<?php
namespace api\Controllers;
use api\ApiRouter;
use Domain\Product\ProductRepository;
class ProductsApiController
{
private $productRepo;
public function __construct(ProductRepository $productRepo)
{
$this->productRepo = $productRepo;
}
public function list(): void
{
if (!ApiRouter::requireMethod('GET')) {
return;
}
$filters = [
'search' => isset($_GET['search']) ? $_GET['search'] : '',
'status' => isset($_GET['status']) ? $_GET['status'] : '',
'promoted' => isset($_GET['promoted']) ? $_GET['promoted'] : '',
];
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'id';
$sortDir = isset($_GET['sort_dir']) ? $_GET['sort_dir'] : 'DESC';
$page = max(1, (int)(isset($_GET['page']) ? $_GET['page'] : 1));
$perPage = max(1, min(100, (int)(isset($_GET['per_page']) ? $_GET['per_page'] : 50)));
$result = $this->productRepo->listForApi($filters, $sort, $sortDir, $page, $perPage);
ApiRouter::sendSuccess($result);
}
public function get(): void
{
if (!ApiRouter::requireMethod('GET')) {
return;
}
$id = (int)(isset($_GET['id']) ? $_GET['id'] : 0);
if ($id <= 0) {
ApiRouter::sendError('BAD_REQUEST', 'Missing or invalid id parameter', 400);
return;
}
$product = $this->productRepo->findForApi($id);
if ($product === null) {
ApiRouter::sendError('NOT_FOUND', 'Product not found', 404);
return;
}
ApiRouter::sendSuccess($product);
}
public function create(): void
{
if (!ApiRouter::requireMethod('POST')) {
return;
}
$body = ApiRouter::getJsonBody();
if ($body === null) {
ApiRouter::sendError('BAD_REQUEST', 'Missing or invalid JSON body', 400);
return;
}
if (empty($body['languages']) || !is_array($body['languages'])) {
ApiRouter::sendError('BAD_REQUEST', 'Missing languages (at least one language with name is required)', 400);
return;
}
$hasName = false;
foreach ($body['languages'] as $lang) {
if (is_array($lang) && !empty($lang['name'])) {
$hasName = true;
break;
}
}
if (!$hasName) {
ApiRouter::sendError('BAD_REQUEST', 'At least one language must have a name', 400);
return;
}
if (!isset($body['price_brutto'])) {
ApiRouter::sendError('BAD_REQUEST', 'Missing price_brutto', 400);
return;
}
$formData = $this->mapApiToFormData($body);
$productId = $this->productRepo->saveProduct($formData);
if ($productId === null) {
ApiRouter::sendError('INTERNAL_ERROR', 'Failed to create product', 500);
return;
}
http_response_code(201);
echo json_encode([
'status' => 'ok',
'data' => ['id' => $productId],
], JSON_UNESCAPED_UNICODE);
}
public function update(): void
{
if (!ApiRouter::requireMethod('PUT')) {
return;
}
$id = (int)(isset($_GET['id']) ? $_GET['id'] : 0);
if ($id <= 0) {
ApiRouter::sendError('BAD_REQUEST', 'Missing or invalid id parameter', 400);
return;
}
$existing = $this->productRepo->find($id);
if ($existing === null) {
ApiRouter::sendError('NOT_FOUND', 'Product not found', 404);
return;
}
$body = ApiRouter::getJsonBody();
if ($body === null) {
ApiRouter::sendError('BAD_REQUEST', 'Missing or invalid JSON body', 400);
return;
}
$formData = $this->mapApiToFormData($body, $existing);
$formData['id'] = $id;
$this->productRepo->saveProduct($formData);
$updated = $this->productRepo->findForApi($id);
ApiRouter::sendSuccess($updated);
}
/**
* Mapuje dane z JSON API na format oczekiwany przez saveProduct().
*
* @param array $body Dane z JSON body
* @param array|null $existing Istniejące dane produktu (partial update)
* @return array Dane w formacie formularza
*/
private function mapApiToFormData(array $body, ?array $existing = null): array
{
$d = [];
// Status/promoted — saveProduct expects 'on' for checkboxes
if (isset($body['status'])) {
$d['status'] = $body['status'] ? 'on' : '';
} elseif ($existing !== null) {
$d['status'] = !empty($existing['status']) ? 'on' : '';
}
if (isset($body['promoted'])) {
$d['promoted'] = $body['promoted'] ? 'on' : '';
} elseif ($existing !== null) {
$d['promoted'] = !empty($existing['promoted']) ? 'on' : '';
}
if (isset($body['stock_0_buy'])) {
$d['stock_0_buy'] = $body['stock_0_buy'] ? 'on' : '';
} elseif ($existing !== null) {
$d['stock_0_buy'] = !empty($existing['stock_0_buy']) ? 'on' : '';
}
// Numeric fields — direct mapping
$numericFields = [
'price_brutto', 'price_netto', 'price_brutto_promo', 'price_netto_promo',
'vat', 'quantity', 'weight',
];
foreach ($numericFields as $field) {
if (isset($body[$field])) {
$d[$field] = $body[$field];
} elseif ($existing !== null && isset($existing[$field])) {
$d[$field] = $existing[$field];
}
}
// String fields — direct mapping
$stringFields = [
'sku', 'ean', 'custom_label_0', 'custom_label_1', 'custom_label_2',
'custom_label_3', 'custom_label_4', 'wp',
];
foreach ($stringFields as $field) {
if (isset($body[$field])) {
$d[$field] = $body[$field];
} elseif ($existing !== null && isset($existing[$field])) {
$d[$field] = $existing[$field];
}
}
// Foreign keys
if (isset($body['set_id'])) {
$d['set'] = $body['set_id'];
} elseif ($existing !== null && isset($existing['set_id'])) {
$d['set'] = $existing['set_id'];
}
if (isset($body['producer_id'])) {
$d['producer_id'] = $body['producer_id'];
} elseif ($existing !== null && isset($existing['producer_id'])) {
$d['producer_id'] = $existing['producer_id'];
}
if (isset($body['product_unit_id'])) {
$d['product_unit'] = $body['product_unit_id'];
} elseif ($existing !== null && isset($existing['product_unit_id'])) {
$d['product_unit'] = $existing['product_unit_id'];
}
// Languages: body.languages.pl.name → d['name']['pl']
if (isset($body['languages']) && is_array($body['languages'])) {
$langFields = [
'name', 'short_description', 'description', 'meta_description',
'meta_keywords', 'meta_title', 'seo_link', 'copy_from',
'warehouse_message_zero', 'warehouse_message_nonzero',
'tab_name_1', 'tab_description_1', 'tab_name_2', 'tab_description_2',
'canonical', 'security_information',
];
foreach ($body['languages'] as $langId => $langData) {
if (!is_array($langData)) {
continue;
}
foreach ($langFields as $field) {
if (isset($langData[$field])) {
$d[$field][$langId] = $langData[$field];
}
}
}
}
// Categories
if (isset($body['categories']) && is_array($body['categories'])) {
$d['categories'] = $body['categories'];
}
// Related products
if (isset($body['products_related']) && is_array($body['products_related'])) {
$d['products_related'] = $body['products_related'];
}
return $d;
}
}