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

@@ -95,7 +95,7 @@ $perPage = (int)($list->pagination['per_page'] ?? 15);
</form>
<div class="table-responsive">
<table class="table table-hover table-striped table-bordered mbn">
<table class="table table-hover table-striped table-bordered mbn table-list-table">
<thead>
<tr>
<?php foreach ($list->columns as $column): ?>
@@ -230,6 +230,12 @@ $perPage = (int)($list->pagination['per_page'] ?? 15);
</div>
<style type="text/css">
.table-list-table th:first-child,
.table-list-table td:first-child {
width: 70px;
white-space: nowrap;
}
.jconfirm.table-list-confirm-dialog .jconfirm-row {
min-height: 100vh;
display: flex;

View File

@@ -1,91 +1 @@
<script type="text/javascript" src="/libraries/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="/libraries/ckeditor/adapters/jquery.js"></script>
<?
global $db;
ob_start();
?>
<div id="settings-tabs">
<ul class="resp-tabs-list settings-tabs">
<li><i class="fa fa-file"></i>Treść</li>
</ul>
<div class="resp-tabs-container settings-tabs">
<div>
<div id="languages-main">
<ul class="resp-tabs-list languages-main htabs">
<? if ( is_array( $this -> languages ) ): foreach ( $this -> languages as $lg ):?>
<? if ( $lg['status'] ):?>
<li><?= $lg['name'];?></a></li>
<? endif;?>
<? endforeach; endif;?>
</ul>
<div class="resp-tabs-container languages-main">
<? if ( is_array( $this -> languages ) ): foreach ( $this -> languages as $lg ):?>
<? if ( $lg['status'] ):?>
<div>
<?= \Html::input(
array(
'label' => 'Tekst',
'name' => 'text[' . $lg['id'] . ']',
'id' => 'text_' . $lg['id'],
'value' => $this -> unit['languages'][ $lg['id'] ]['text'],
'inline' => true
)
);?>
</div>
<? endif;?>
<? endforeach; endif;?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<?
$out = ob_get_clean();
$grid = new \gridEdit;
$grid -> id = 'unit-edit';
$grid -> gdb_opt = $gdb;
$grid -> include_plugins = true;
$grid -> title = 'Edycja jednostki miary';
$grid -> fields = [
[
'db' => 'id',
'type' => 'hidden',
'value' => $this -> unit['id']
]
];
$grid -> actions = [
'save' => [ 'url' => '/admin/dictionaries/unit_save/', 'back_url' => '/admin/dictionaries/view_list/' ],
'cancel' => [ 'url' => '/admin/dictionaries/view_list/' ]
];
$grid -> external_code = $out;
$grid -> persist_edit = true;
$grid -> id_param = 'id';
echo $grid -> draw();
?>
<script type="text/javascript">
$( function()
{
disable_menu();
$( '#settings-tabs' ).easyResponsiveTabs({
width: 'auto',
fit: true,
tabidentify: 'settings-tabs',
type: 'vertical'
});
$( '#languages-main' ).easyResponsiveTabs({
width: 'auto',
fit: true,
tabidentify: 'languages-main'
});
});
</script>
<script>CKEDITOR.dtd.$removeEmpty['span'] = false;</script>
<?= \Tpl::view('components/form-edit', ['form' => $this->form]); ?>

View File

@@ -1,67 +1,5 @@
<?php
global $gdb;
<?= \Tpl::view('components/table-list', ['list' => $this->viewModel]); ?>
$grid = new \grid( 'pp_dictionaries_units' );
$grid -> gdb_opt = $gdb;
$grid -> sql = 'SELECT *'
. 'FROM ( '
. 'SELECT '
. 'id,'
. '( SELECT text FROM pp_units_langs AS psl, pp_langs AS pl WHERE lang_id = pl.id AND unit_id = ps.id AND text != \'\' ORDER BY o ASC LIMIT 1 ) AS text '
. 'FROM '
. 'pp_units AS ps '
. ') AS q1 '
. 'WHERE '
. '1=1 [where] '
. 'ORDER BY '
. '[order_p1] [order_p2]';
$grid -> sql_count = 'SELECT '
. 'COUNT(0) FROM ( '
. 'SELECT '
. 'id,'
. '( SELECT text FROM pp_units_langs AS psl, pp_langs AS pl WHERE lang_id = pl.id AND unit_id = ps.id AND text != \'\' ORDER BY o ASC LIMIT 1 ) AS text '
. 'FROM '
. 'pp_units AS ps '
. ') AS q1 '
. 'WHERE '
. '1=1 [where] ';
$grid -> debug = true;
$grid -> order = [ 'column' => 'id', 'type' => 'ASC' ];
$grid -> search = [
[ 'name' => 'Tekst', 'db' => 'text', 'type' => 'text' ]
];
$grid -> columns_view = [
[
'name' => 'Lp.',
'th' => [ 'class' => 'g-lp' ],
'td' => [ 'class' => 'g-center' ],
'autoincrement' => true
],
[
'name' => 'Tekst',
'db' => 'text',
'php' => 'echo "<a href=\'/admin/dictionaries/unit_edit/id=[id]\'>[text]</a>";',
'sort' => true
],
[
'name' => 'Edytuj',
'action' => [ 'type' => 'edit', 'url' => '/admin/dictionaries/unit_edit/id=[id]' ],
'th' => [ 'class' => 'g-center', 'style' => 'width: 70px;' ],
'td' => [ 'class' => 'g-center' ]
],
[
'name' => 'Usuń',
'action' => [ 'type' => 'delete', 'url' => '/admin/dictionaries/unit_delete/id=[id]' ],
'th' => [ 'class' => 'g-center', 'style' => 'width: 70px;' ],
'td' => [ 'class' => 'g-center' ]
]
];
$grid -> buttons = [
[
'label' => 'Dodaj jednostkę miary',
'url' => '/admin/dictionaries/unit_edit/',
'icon' => 'fa-plus-circle',
'class' => 'btn-success'
]
];
echo $grid -> draw();
<?php if (!empty($this->viewModel->customScriptView)): ?>
<?= \Tpl::view($this->viewModel->customScriptView, ['list' => $this->viewModel]); ?>
<?php endif; ?>

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;
}
}

View File

@@ -1,6 +1,7 @@
<? global $lang_id;?>
<? global $lang_id, $mdb;?>
<?
$attributes = \shop\Product::get_product_attributes( $this -> product['product_combinations'] );
$dictionariesRepository = new \Domain\Dictionaries\DictionariesRepository( $mdb );
?>
<script class="footer" type="text/javascript">
function fradio_label_click( element, refresh )
@@ -67,7 +68,7 @@
</div>
<? if ( $this -> product -> weight > 0 && $this -> product -> product_unit_id ):?>
<div class="price_weight">
<?= \shop\Shop::shortPrice( $this -> product -> price_brutto / $this -> product -> weight );?> <span class="small">zł</span> / <?= \front\factory\Dictionaries::get_name_by_id( $this -> product -> product_unit_id, $this -> lang_id );?>
<?= \shop\Shop::shortPrice( $this -> product -> price_brutto / $this -> product -> weight );?> <span class="small">zł</span> / <?= $dictionariesRepository -> getUnitNameById( (int)$this -> product -> product_unit_id, $this -> lang_id );?>
</div>
<? endif;?>
<? endif;?>

View File

@@ -0,0 +1,159 @@
<?php
namespace Tests\Unit\Domain\Dictionaries;
use PHPUnit\Framework\TestCase;
use Domain\Dictionaries\DictionariesRepository;
class DictionariesRepositoryTest extends TestCase
{
public function testFindReturnsUnitWithTranslations(): void
{
$mockDb = $this->createMock(\medoo::class);
$mockDb->expects($this->once())
->method('get')
->with('pp_units', '*', ['id' => 5])
->willReturn(['id' => 5]);
$mockDb->expects($this->once())
->method('select')
->with('pp_units_langs', '*', [
'unit_id' => 5,
'ORDER' => ['lang_id' => 'ASC', 'id' => 'ASC'],
])
->willReturn([
['lang_id' => 1, 'text' => 'kg'],
['lang_id' => 2, 'text' => 'kg'],
]);
$repository = new DictionariesRepository($mockDb);
$unit = $repository->find(5);
$this->assertIsArray($unit);
$this->assertEquals(5, $unit['id']);
$this->assertArrayHasKey('languages', $unit);
$this->assertEquals('kg', $unit['languages'][1]['text']);
}
public function testFindReturnsNullWhenUnitNotFound(): void
{
$mockDb = $this->createMock(\medoo::class);
$mockDb->method('get')->willReturn(false);
$repository = new DictionariesRepository($mockDb);
$this->assertNull($repository->find(999));
}
public function testSaveInsertsNewUnitAndTranslationsForStringLanguageId(): void
{
$mockDb = $this->createMock(\medoo::class);
// insert: 1x pp_units + 1x pp_units_langs
$mockDb->expects($this->exactly(2))
->method('insert');
$mockDb->expects($this->once())
->method('id')
->willReturn(12);
$mockDb->expects($this->once())
->method('get')
->with('pp_units_langs', 'id', [
'AND' => [
'unit_id' => 12,
'lang_id' => 'pl',
],
])
->willReturn(false);
$repository = new DictionariesRepository($mockDb);
$savedId = $repository->save([
'translations' => [
'pl' => ['text' => 'szt.'],
],
]);
$this->assertSame(12, $savedId);
}
public function testDeleteRemovesUnitAndTranslations(): void
{
$mockDb = $this->createMock(\medoo::class);
$mockDb->expects($this->exactly(2))
->method('delete')
->withConsecutive(
['pp_units_langs', ['unit_id' => 7]],
['pp_units', ['id' => 7]]
)
->willReturnOnConsecutiveCalls(
$this->createMock(\PDOStatement::class),
$this->createMock(\PDOStatement::class)
);
$repository = new DictionariesRepository($mockDb);
$this->assertTrue($repository->delete(7));
}
public function testGetUnitNameByIdReturnsTextFromDatabase(): void
{
$mockDb = $this->createMock(\medoo::class);
$mockDb->expects($this->once())
->method('get')
->with('pp_units_langs', 'text', [
'AND' => [
'unit_id' => 2,
'lang_id' => 1,
],
])
->willReturn('kg');
$repository = new DictionariesRepository($mockDb);
$this->assertSame('kg', $repository->getUnitNameById(2, 1));
}
public function testGetUnitNameByIdSupportsStringLanguageId(): void
{
$mockDb = $this->createMock(\medoo::class);
$mockDb->expects($this->once())
->method('get')
->with('pp_units_langs', 'text', [
'AND' => [
'unit_id' => 2,
'lang_id' => 'pl',
],
])
->willReturn('kg');
$repository = new DictionariesRepository($mockDb);
$this->assertSame('kg', $repository->getUnitNameById(2, 'pl'));
}
public function testAllUnitsReturnsArrayIndexedById(): void
{
$mockDb = $this->createMock(\medoo::class);
$stmt = $this->createMock(\PDOStatement::class);
$stmt->expects($this->once())
->method('fetchAll')
->with(\PDO::FETCH_ASSOC)
->willReturn([
['id' => 3, 'text' => 'kg'],
['id' => 4, 'text' => 'l'],
]);
$mockDb->expects($this->once())
->method('query')
->willReturn($stmt);
$repository = new DictionariesRepository($mockDb);
$units = $repository->allUnits();
$this->assertArrayHasKey(3, $units);
$this->assertSame('kg', $units[3]['text']);
$this->assertArrayHasKey(4, $units);
}
}

View File

@@ -0,0 +1,64 @@
<?php
namespace Tests\Unit\admin\Controllers;
use PHPUnit\Framework\TestCase;
use admin\Controllers\DictionariesController;
use Domain\Dictionaries\DictionariesRepository;
class DictionariesControllerTest extends TestCase
{
private $mockRepository;
private $controller;
protected function setUp(): void
{
$this->mockRepository = $this->createMock(DictionariesRepository::class);
$this->controller = new DictionariesController($this->mockRepository);
}
public function testConstructorAcceptsRepository(): void
{
$controller = new DictionariesController($this->mockRepository);
$this->assertInstanceOf(DictionariesController::class, $controller);
}
public function testHasListMethod(): void
{
$this->assertTrue(method_exists($this->controller, 'list'));
}
public function testHasEditMethod(): void
{
$this->assertTrue(method_exists($this->controller, 'edit'));
}
public function testHasSaveMethod(): void
{
$this->assertTrue(method_exists($this->controller, 'save'));
}
public function testHasDeleteMethod(): void
{
$this->assertTrue(method_exists($this->controller, 'delete'));
}
public function testActionMethodReturnTypes(): void
{
$reflection = new \ReflectionClass($this->controller);
$this->assertEquals('string', (string)$reflection->getMethod('list')->getReturnType());
$this->assertEquals('string', (string)$reflection->getMethod('edit')->getReturnType());
$this->assertEquals('void', (string)$reflection->getMethod('save')->getReturnType());
$this->assertEquals('void', (string)$reflection->getMethod('delete')->getReturnType());
}
public function testConstructorRequiresDictionariesRepository(): void
{
$reflection = new \ReflectionClass(DictionariesController::class);
$constructor = $reflection->getConstructor();
$params = $constructor->getParameters();
$this->assertCount(1, $params);
$this->assertEquals('Domain\Dictionaries\DictionariesRepository', $params[0]->getType()->getName());
}
}

BIN
updates/0.20/ver_0.251.zip Normal file

Binary file not shown.

View File

@@ -0,0 +1,3 @@
F: ../autoload/admin/controls/class.Dictionaries.php
F: ../autoload/admin/factory/class.Dictionaries.php
F: ../autoload/front/factory/class.Dictionaries.php

View File

@@ -1,3 +1,11 @@
<b>ver. 0.251 - 09.02.2026</b><br />
- NEW - migracja modulu Dictionaries do nowej architektury (Domain + admin Controller + DI)
- UPDATE - lista i formularz Dictionaries przepiete na nowe komponenty (`components/table-list`, `components/form-edit`)
- UPDATE - dodano globalne ograniczenie szerokosci pierwszej kolumny (Lp.) w `components/table-list`
- FIX - zapis tlumaczen jednostek obsluguje `lang_id` jako string (`pl`, `en`)
- UPDATE - usunieto legacy klasy Dictionaries: `admin\\controls`, `admin\\factory`, `front\\factory`
- UPDATE - przepieto uzycia na `Domain\\Dictionaries\\DictionariesRepository` (`shop-product`, `shop_product` admin)
<hr>
<b>ver. 0.250</b><br />
- UPDATE - refaktoryzacja Settings: `Domain\\Settings\\SettingsRepository` ma bezposredni dostep do bazy (bez delegacji do `admin\\factory\\Settings`)
- UPDATE - przepieto pozostale uzycia `admin\\factory\\Settings` na `Domain\\Settings\\SettingsRepository` (`admin\\controls\\Settings`, `admin\\controls\\Newsletter`, `front\\factory\\Newsletter`)

View File

@@ -1,5 +1,5 @@
<?
$current_ver = 250;
$current_ver = 251;
for ($i = 1; $i <= $current_ver; $i++)
{