ver. 0.251 - migrate Dictionaries to Domain/Controller and remove legacy classes

This commit is contained in:
2026-02-10 00:04:32 +01:00
parent 3bab9f9e8a
commit fe4e98d9bd
17 changed files with 788 additions and 307 deletions

View File

@@ -0,0 +1,273 @@
<?php
namespace Domain\Dictionaries;
class DictionariesRepository
{
private const MAX_PER_PAGE = 100;
private const CACHE_TTL = 86400;
private const CACHE_SUBDIR = 'dictionaries';
private $db;
public function __construct($db)
{
$this->db = $db;
}
public function listForAdmin(
array $filters,
string $sortColumn = 'id',
string $sortDir = 'ASC',
int $page = 1,
int $perPage = 15
): array {
$allowedSortColumns = [
'id' => 'u.id',
'text' => 'text',
];
$sortSql = $allowedSortColumns[$sortColumn] ?? 'u.id';
$sortDir = strtoupper(trim($sortDir)) === 'DESC' ? 'DESC' : 'ASC';
$page = max(1, $page);
$perPage = min(self::MAX_PER_PAGE, max(1, $perPage));
$offset = ($page - 1) * $perPage;
$where = ['1=1'];
$params = [];
$text = trim((string)($filters['text'] ?? ''));
if (strlen($text) > 255) {
$text = substr($text, 0, 255);
}
if ($text !== '') {
$where[] = 'EXISTS (SELECT 1 FROM pp_units_langs AS ul2 WHERE ul2.unit_id = u.id AND ul2.text LIKE :text)';
$params[':text'] = '%' . $text . '%';
}
$whereSql = implode(' AND ', $where);
$sqlCount = "
SELECT COUNT(0)
FROM pp_units AS u
WHERE {$whereSql}
";
$stmtCount = $this->db->query($sqlCount, $params);
$countRows = $stmtCount ? $stmtCount->fetchAll() : [];
$total = isset($countRows[0][0]) ? (int)$countRows[0][0] : 0;
$sql = "
SELECT
u.*,
(
SELECT ul.text
FROM pp_units_langs AS ul
INNER JOIN pp_langs AS l ON l.id = ul.lang_id
WHERE ul.unit_id = u.id AND ul.text <> ''
ORDER BY l.o ASC
LIMIT 1
) AS text
FROM pp_units AS u
WHERE {$whereSql}
ORDER BY {$sortSql} {$sortDir}, u.id {$sortDir}
LIMIT {$perPage} OFFSET {$offset}
";
$stmt = $this->db->query($sql, $params);
$items = $stmt ? $stmt->fetchAll() : [];
return [
'items' => is_array($items) ? $items : [],
'total' => $total,
];
}
public function allUnits(): array
{
$sql = "
SELECT
u.*,
(
SELECT ul.text
FROM pp_units_langs AS ul
INNER JOIN pp_langs AS l ON l.id = ul.lang_id
WHERE ul.unit_id = u.id AND ul.text <> ''
ORDER BY l.o ASC
LIMIT 1
) AS text
FROM pp_units AS u
ORDER BY u.id ASC
";
$stmt = $this->db->query($sql);
$rows = $stmt ? $stmt->fetchAll(\PDO::FETCH_ASSOC) : [];
if (!is_array($rows)) {
return [];
}
$units = [];
foreach ($rows as $row) {
$units[(int)$row['id']] = $row;
}
return $units;
}
public function find(int $unitId): ?array
{
$unit = $this->db->get('pp_units', '*', ['id' => $unitId]);
if (!$unit) {
return null;
}
$unit['languages'] = [];
$translations = $this->db->select('pp_units_langs', '*', [
'unit_id' => $unitId,
'ORDER' => ['lang_id' => 'ASC', 'id' => 'ASC'],
]);
if (is_array($translations)) {
foreach ($translations as $row) {
$unit['languages'][(string)$row['lang_id']] = $row;
}
}
return $unit;
}
public function save(array $data)
{
$unitId = isset($data['id']) ? (int)$data['id'] : 0;
if ($unitId <= 0) {
$this->db->insert('pp_units', []);
$unitId = (int)$this->db->id();
if ($unitId <= 0) {
return false;
}
}
$translations = $this->normalizeTranslations($data);
foreach ($translations as $langId => $text) {
$this->upsertTranslation($unitId, $langId, $text);
}
$this->clearCache();
return $unitId;
}
public function delete(int $unitId): bool
{
if ($unitId <= 0) {
return false;
}
$this->db->delete('pp_units_langs', ['unit_id' => $unitId]);
$result = $this->db->delete('pp_units', ['id' => $unitId]);
$this->clearCache();
return $result !== false;
}
public function getUnitNameById(int $unitId, $langId): string
{
$langId = trim((string)$langId);
if ($unitId <= 0 || $langId === '') {
return '';
}
$cacheKey = "get_name_by_id:$unitId:$langId";
$unitName = $this->cacheFetch($cacheKey);
if ($unitName === false) {
$unitName = $this->db->get('pp_units_langs', 'text', [
'AND' => [
'unit_id' => $unitId,
'lang_id' => $langId,
],
]);
$this->cacheStore($cacheKey, $unitName ?: '');
}
return (string)$unitName;
}
private function normalizeTranslations(array $data): array
{
$translations = [];
if (isset($data['translations']) && is_array($data['translations'])) {
foreach ($data['translations'] as $langId => $fields) {
$translations[(string)$langId] = trim((string)($fields['text'] ?? ''));
}
return $translations;
}
if (isset($data['text']) && is_array($data['text'])) {
foreach ($data['text'] as $langId => $text) {
$translations[(string)$langId] = trim((string)$text);
}
}
return $translations;
}
private function upsertTranslation(int $unitId, $langId, string $text): void
{
$langId = trim((string)$langId);
if ($langId === '') {
return;
}
$translationId = $this->db->get('pp_units_langs', 'id', [
'AND' => [
'unit_id' => $unitId,
'lang_id' => $langId,
],
]);
if ($translationId) {
$this->db->update('pp_units_langs', [
'text' => $text,
], [
'id' => (int)$translationId,
]);
return;
}
$this->db->insert('pp_units_langs', [
'unit_id' => $unitId,
'lang_id' => $langId,
'text' => $text,
]);
}
private function clearCache(): void
{
if (class_exists('\S') && method_exists('\S', 'delete_dir')) {
\S::delete_dir('../temp/dictionaries');
}
}
private function cacheFetch(string $key)
{
if (!class_exists('\Cache') || !method_exists('\Cache', 'fetch')) {
return false;
}
return \Cache::fetch($key, self::CACHE_SUBDIR);
}
private function cacheStore(string $key, string $value): void
{
if (!class_exists('\Cache') || !method_exists('\Cache', 'store')) {
return;
}
\Cache::store($key, $value, self::CACHE_TTL, self::CACHE_SUBDIR);
}
}

View File

@@ -0,0 +1,253 @@
<?php
namespace admin\Controllers;
use Domain\Dictionaries\DictionariesRepository;
use admin\ViewModels\Forms\FormAction;
use admin\ViewModels\Forms\FormEditViewModel;
use admin\ViewModels\Forms\FormField;
use admin\ViewModels\Forms\FormTab;
use admin\Support\Forms\FormRequestHandler;
class DictionariesController
{
private DictionariesRepository $repository;
private FormRequestHandler $formHandler;
public function __construct(DictionariesRepository $repository)
{
$this->repository = $repository;
$this->formHandler = new FormRequestHandler();
}
public function list(): string
{
$sortableColumns = ['id', 'text'];
$filterDefinitions = [
[
'key' => 'text',
'label' => 'Tekst',
'type' => 'text',
],
];
$listRequest = \admin\Support\TableListRequestFactory::fromRequest(
$filterDefinitions,
$sortableColumns,
'id'
);
$sortDir = $listRequest['sortDir'];
if (trim((string)\S::get('sort')) === '') {
$sortDir = 'ASC';
}
$result = $this->repository->listForAdmin(
$listRequest['filters'],
$listRequest['sortColumn'],
$sortDir,
$listRequest['page'],
$listRequest['perPage']
);
$rows = [];
$lp = ($listRequest['page'] - 1) * $listRequest['perPage'] + 1;
foreach ($result['items'] as $item) {
$id = (int)$item['id'];
$text = trim((string)($item['text'] ?? ''));
$rows[] = [
'lp' => $lp++ . '.',
'text' => '<a href="/admin/dictionaries/unit_edit/id=' . $id . '">' . htmlspecialchars($text, ENT_QUOTES, 'UTF-8') . '</a>',
'_actions' => [
[
'label' => 'Edytuj',
'url' => '/admin/dictionaries/unit_edit/id=' . $id,
'class' => 'btn btn-xs btn-primary',
],
[
'label' => 'Usun',
'url' => '/admin/dictionaries/unit_delete/id=' . $id,
'class' => 'btn btn-xs btn-danger',
'confirm' => 'Na pewno chcesz usunac wybrana jednostke miary?',
],
],
];
}
$total = (int)$result['total'];
$totalPages = max(1, (int)ceil($total / $listRequest['perPage']));
$viewModel = new \admin\ViewModels\Common\PaginatedTableViewModel(
[
['key' => 'lp', 'label' => 'Lp.', 'class' => 'text-center', 'sortable' => false],
['key' => 'text', 'sort_key' => 'text', 'label' => 'Tekst', 'sortable' => true, 'raw' => true],
],
$rows,
$listRequest['viewFilters'],
[
'column' => $listRequest['sortColumn'],
'dir' => $sortDir,
],
[
'page' => $listRequest['page'],
'per_page' => $listRequest['perPage'],
'total' => $total,
'total_pages' => $totalPages,
],
array_merge($listRequest['queryFilters'], [
'sort' => $listRequest['sortColumn'],
'dir' => $sortDir,
'per_page' => $listRequest['perPage'],
]),
$listRequest['perPageOptions'],
$sortableColumns,
'/admin/dictionaries/view_list/',
'Brak danych w tabeli.',
'/admin/dictionaries/unit_edit/',
'Dodaj jednostke miary'
);
return \Tpl::view('dictionaries/units-list', [
'viewModel' => $viewModel,
]);
}
public function edit(): string
{
$unitId = (int)\S::get('id');
$unit = $this->repository->find($unitId) ?? ['id' => 0, 'languages' => []];
$languages = \admin\factory\Languages::languages_list();
$validationErrors = $_SESSION['form_errors'][$this->getFormId()] ?? null;
if ($validationErrors) {
unset($_SESSION['form_errors'][$this->getFormId()]);
}
$viewModel = $this->buildFormViewModel($unit, $languages, $validationErrors);
return \Tpl::view('dictionaries/unit-edit', ['form' => $viewModel]);
}
public function save(): void
{
$legacyValues = \S::get('values');
if ($legacyValues) {
$values = json_decode($legacyValues, true);
$response = ['status' => 'error', 'msg' => 'Podczas zapisywania jednostki miary wystapil blad.'];
if (is_array($values)) {
$savedId = $this->repository->save([
'id' => (int)($values['id'] ?? 0),
'text' => (array)($values['text'] ?? []),
]);
if ($savedId) {
$response = ['status' => 'ok', 'msg' => 'Jednostka miary zostala zapisana.', 'id' => $savedId];
}
}
echo json_encode($response);
exit;
}
$unitId = (int)\S::get('id');
$unit = $this->repository->find($unitId) ?? ['id' => 0, 'languages' => []];
$languages = \admin\factory\Languages::languages_list();
$viewModel = $this->buildFormViewModel($unit, $languages);
$result = $this->formHandler->handleSubmit($viewModel, $_POST);
if (!$result['success']) {
$_SESSION['form_errors'][$this->getFormId()] = $result['errors'];
echo json_encode(['success' => false, 'errors' => $result['errors']]);
exit;
}
$data = $result['data'];
$data['id'] = $unitId ?: null;
$savedId = $this->repository->save($data);
if ($savedId) {
echo json_encode([
'success' => true,
'id' => $savedId,
'message' => 'Jednostka miary zostala zapisana.',
]);
exit;
}
echo json_encode([
'success' => false,
'errors' => ['general' => 'Blad podczas zapisywania do bazy.'],
]);
exit;
}
public function delete(): void
{
$unitId = (int)\S::get('id');
if ($this->repository->delete($unitId)) {
\S::alert('Jednostka miary zostala usunieta.');
}
header('Location: /admin/dictionaries/view_list/');
exit;
}
private function buildFormViewModel(array $unit, array $languages, ?array $errors = null): FormEditViewModel
{
$unitId = (int)($unit['id'] ?? 0);
$isNew = $unitId <= 0;
$data = [
'id' => $unitId,
'languages' => [],
];
if (isset($unit['languages']) && is_array($unit['languages'])) {
foreach ($unit['languages'] as $langId => $translation) {
$data['languages'][(string)$langId] = [
'text' => (string)($translation['text'] ?? ''),
];
}
}
$tabs = [
new FormTab('content', 'Tresc', 'fa-file'),
];
$fields = [
FormField::langSection('translations', 'content', [
FormField::text('text', [
'label' => 'Tekst',
]),
]),
];
$actionUrl = '/admin/dictionaries/unit_save/' . ($isNew ? '' : ('id=' . $unitId));
$actions = [
FormAction::save($actionUrl, '/admin/dictionaries/view_list/'),
FormAction::cancel('/admin/dictionaries/view_list/'),
];
return new FormEditViewModel(
$this->getFormId(),
$isNew ? 'Nowa jednostka miary' : 'Edycja jednostki miary',
$data,
$fields,
$tabs,
$actions,
'POST',
$actionUrl,
'/admin/dictionaries/view_list/',
true,
['id' => $unitId],
$languages,
$errors
);
}
private function getFormId(): string
{
return 'dictionaries-unit-edit';
}
}

View File

@@ -227,6 +227,13 @@ class Site
new \Domain\Product\ProductRepository( $mdb )
);
},
'Dictionaries' => function() {
global $mdb;
return new \admin\Controllers\DictionariesController(
new \Domain\Dictionaries\DictionariesRepository( $mdb )
);
},
];
return self::$newControllers;
@@ -267,6 +274,9 @@ class Site
'clear_cache_ajax' => 'clearCacheAjax',
'settings_save' => 'save',
'products_list' => 'list',
'unit_edit' => 'edit',
'unit_save' => 'save',
'unit_delete' => 'delete',
];
public static function route()

View File

@@ -1,39 +0,0 @@
<?php
namespace admin\controls;
class Dictionaries {
public static function view_list()
{
return \Tpl::view( 'dictionaries/units-list' );
}
public static function unit_edit()
{
return \Tpl::view( 'dictionaries/unit-edit', [
'unit' => \admin\factory\Dictionaries::unit_details( \S::get( 'id' )),
'languages' => \admin\factory\Languages::languages_list(),
] );
}
static public function unit_save()
{
$response = [ 'status' => 'error', 'msg' => 'Podczas zapisywania jednostki miary wystąpił błąd. Proszę spróbować ponownie.' ];
$values = json_decode( \S::get( 'values' ), true );
if ( $id = \admin\factory\Dictionaries::unit_save( $values['id'], $values['text']) )
$response = [ 'status' => 'ok', 'msg' => 'Jednostka miary została zapisana.', 'id' => $id ];
echo json_encode( $response );
exit;
}
static public function unit_delete()
{
if ( \admin\factory\Dictionaries::unit_delete( \S::get( 'id' ) ) )
\S::alert( 'Jesdnostka miary została usunięta.' );
header( 'Location: /admin/dictionaries/view_list/' );
exit;
}
}

View File

@@ -230,7 +230,7 @@ class ShopProduct
// edycja produktu
public static function product_edit() {
global $user;
global $user, $mdb;
if ( !$user ) {
header( 'Location: /admin/' );
@@ -249,7 +249,7 @@ class ShopProduct
'dlang' => \front\factory\Languages::default_language(),
'sets' => \shop\ProductSet::sets_list(),
'producers' => \admin\factory\ShopProducer::all(),
'units' => \admin\factory\Dictionaries::all_units(),
'units' => ( new \Domain\Dictionaries\DictionariesRepository( $mdb ) ) -> allUnits(),
'user' => $user
] );
}

View File

@@ -1,89 +0,0 @@
<?
namespace admin\factory;
class Dictionaries
{
static public function all_units()
{
global $mdb;
$results = $mdb -> select( 'pp_units', '*' );
foreach ( $results as $row )
{
$resutls2 = $mdb -> query( 'SELECT text FROM pp_units_langs AS psl, pp_langs AS pl WHERE unit_id = ' . $row['id'] . ' AND lang_id = pl.id AND text != \'\' ORDER BY o ASC LIMIT 1' ) -> fetchAll( \PDO::FETCH_ASSOC );
$row['text'] = $resutls2[0]['text'];
$units[ $row['id'] ] = $row;
}
return $units;
}
static public function unit_details( $unit_id )
{
global $mdb;
$unit = $mdb -> get( 'pp_units', '*', [ 'id' => (int)$unit_id ] );
$results = $mdb -> select( 'pp_units_langs', '*', [ 'unit_id' => (int)$unit_id ] );
if ( is_array( $results ) ) foreach ( $results as $row )
$unit['languages'][ $row['lang_id'] ] = $row;
return $unit;
}
static public function unit_save( $unit_id, $text )
{
global $mdb;
if ( !$unit_id )
{
$mdb -> insert( 'pp_units', array());
$id = $mdb -> id();
if ( $id )
{
foreach ( $text as $key => $val )
{
$mdb -> insert( 'pp_units_langs', [
'unit_id' => (int)$id,
'lang_id' => $key,
'text' => $text[$key]
] );
}
\S::delete_dir( '../temp/' );
return $id;
}
}
else
{
foreach ( $text as $key => $val )
{
if ( $translation_id = $mdb -> get( 'pp_units_langs', 'id', [ 'AND' => [ 'unit_id' => $unit_id, 'lang_id' => $key ] ] ) )
$mdb -> update( 'pp_units_langs', [
'lang_id' => $key,
'text' => $text[$key]
], [
'id' => $translation_id
] );
else
$mdb -> insert( 'pp_units_langs', [
'unit_id' => (int)$unit_id,
'lang_id' => $key,
'text' => $text[$key]
] );
}
\S::delete_dir( '../temp/dictionaries' );
return $unit_id;
}
}
static public function unit_delete( $unit_id )
{
global $mdb;
return $mdb -> delete( 'pp_units', [ 'id' => (int)$unit_id ] );
}
}

View File

@@ -1,16 +0,0 @@
<?
namespace front\factory;
class Dictionaries
{
static public function get_name_by_id( int $unit_id, $lang_id )
{
global $mdb;
if ( !$unit_name = \Cache::fetch( "get_name_by_id:$unit_id:$lang_id", "dictionaries" ) )
{
$unit_name = $mdb -> get( 'pp_units_langs', 'text', [ 'AND' => [ 'unit_id' => $unit_id, 'lang_id' => $lang_id ] ] );
\Cache::store( "get_name_by_id:$unit_id:$lang_id", $unit_name, 86400, "dictionaries" );
}
return $unit_name;
}
}