Compare commits

...

2 commits

Author SHA1 Message Date
Benjamin Renard
4907442122
Example: use AttrSet and cleanup way to handle item status possible values 2024-02-18 19:40:58 +01:00
Benjamin Renard
dfbb4d6f9c
Add Db AttrSet 2024-02-18 19:40:12 +01:00
10 changed files with 95 additions and 50 deletions

View file

@ -66,7 +66,7 @@ function cli_list($command_args) {
case '-s':
case '--status':
$i++;
if(!check_status($command_args[$i]))
if(!Item :: check_status($command_args[$i]))
Cli :: usage('Invalid -s/--status clause');
$params['filters']['status'] = $command_args[$i];
break;
@ -124,7 +124,7 @@ Cli :: add_command(
" - ".implode("\n - ", Item :: possible_orders()),
___("-r|--reverse Reverse order"),
___("-s|--status Filter on status. Possible values:"),
" - ".implode("\n - ", array_keys($status_list)),
" - ".implode("\n - ", array_keys(Item :: statuses())),
)
);

View file

@ -57,16 +57,6 @@ $sentry_span = new SentrySpan('core.init', 'Core initialization');
require_once('functions.php');
// Nomenclatures
$status_list = array (
'pending' => ___('Pending'),
'validated' => ___('Validated'),
'refused' => ___('Refused'),
'archived' => ___('Archived'),
);
foreach($status_list as $key => $value)
$status_list[$key] = _($value);
require_once('cli.php');
require_once('templates.php');
require_once('views/index.php');

View file

@ -6,15 +6,9 @@ use EesyPHP\Session;
use EesyPHP\Tpl;
use EesyPHP\Url;
use function EesyPHP\vardump;
use EesyPHPExample\Db\Item;
/*
* Check values helpers
*/
function check_status($status) {
global $status_list;
return array_key_exists($status, $status_list);
}
use function EesyPHP\vardump;
/*
* Handling item POST data
@ -41,7 +35,7 @@ function handle_item_post_data(&$info, $enabled_fields=null, $required_fields=nu
// status
if (!$enabled_fields || in_array('status', $enabled_fields)) {
if (isset($_POST['status']) && check_status($_POST['status'])) {
if (isset($_POST['status']) && Item :: check_status($_POST['status'])) {
$info['status'] = $_POST['status'];
}
else {

View file

@ -7,6 +7,7 @@ use EesyPHP\Log;
use EesyPHP\Tpl;
use EesyPHP\Url;
use EesyPHPExample\Db\Item;
use function EesyPHP\format_size;
@ -25,19 +26,15 @@ Tpl :: enable_security_mode(
);
function define_common_template_variables($event) {
global $status_list, $admin;
Tpl :: assign(
'status_list',
isset($status_list) && is_array($status_list)?
$status_list:array()
);
global $admin;
Tpl :: assign('statuses', Item :: statuses());
Tpl :: assign('admin', isset($admin) && $admin);
}
Hook :: register('before_displaying_template', 'define_common_template_variables');
// Templates functions
function smarty_item_status($params) {
global $status_list;
$statuses = Item :: statuses();
$status2class = array (
'pending' => 'info',
'validated' => 'success',
@ -51,8 +48,8 @@ function smarty_item_status($params) {
$class='danger';
echo "<span class='badge bg-$class'>";
echo (
array_key_exists($params['item']->status, $status_list)?
$status_list[$params['item']->status]:
array_key_exists($params['item']->status, $statuses)?
$statuses[$params['item']->status]:
"Inconnu (".$params['item']->status.")"
);
echo "</span>";

View file

@ -19,8 +19,6 @@ if (php_sapi_name() == "cli")
* @return void
*/
function handle_search($request) {
global $status_list;
// Manage params
if(
(isset($_REQUEST['clear']) && $_REQUEST['clear']=='true') ||
@ -38,9 +36,8 @@ function handle_search($request) {
}
Log :: debug('Request params : '.vardump($_REQUEST));
$status_list['all'] = _('Any');
if (isset($_REQUEST['status'])) {
if (check_status($_REQUEST['status']) || $_REQUEST['status'] == 'all')
if (Item :: check_status($_REQUEST['status'], true))
$_SESSION['search']['filters']['status'] = $_REQUEST['status'];
else
Tpl :: assign('status_error', true);
@ -103,7 +100,7 @@ function handle_search($request) {
Tpl :: assign('result', $result);
Tpl :: assign('search', $_SESSION['search']);
Tpl :: assign('nbs_by_page', $nbs_by_page);
Tpl :: assign('status_list', $status_list);
Tpl :: assign('status_choices', Item :: statuses(true));
Tpl :: add_css_file(
'lib/bootstrap5-dialog/css/bootstrap-dialog.min.css',
@ -149,8 +146,6 @@ Url :: add_url_handler('|^item/(?P<id>[0-9]+)$|', 'handle_show');
* @return void
*/
function handle_create($request) {
global $status_list;
$info = array();
$field_errors = handle_item_post_data($info);
if (isset($_POST['submit']) && empty($field_errors)) {
@ -171,15 +166,12 @@ function handle_create($request) {
Tpl :: assign('submited', isset($_POST['submit']));
Tpl :: assign('info', $info);
Tpl :: assign('field_errors', $field_errors);
Tpl :: assign('status_list', $status_list);
Tpl :: display("form.tpl", _("New"));
}
Url :: add_url_handler('|^item/new$|', 'handle_create');
function handle_modify($request) {
global $status_list;
$item = Item :: get_from_url($request -> id);
if(!$item)
Url :: error_404();
@ -217,7 +209,6 @@ function handle_modify($request) {
Tpl :: assign('info', (!empty($info)?$info:$item));
Tpl :: assign('item_id', $item->id);
Tpl :: assign('field_errors', $field_errors);
Tpl :: assign('status_list', $status_list);
Tpl :: display("form.tpl", _("Element %s: Modification"), $item->name);
}

View file

@ -9,9 +9,3 @@ parameters:
- EesyPHP\UrlRequest
- EesyPHP\Auth\User
treatPhpDocTypesAsCertain: false
ignoreErrors:
-
message: "#Variable \\$status_list might not be defined\\.#"
paths:
- includes/cli.php

View file

@ -9,6 +9,7 @@ use EesyPHP\Tpl;
use EesyPHP\Db\AttrBool;
use EesyPHP\Db\AttrInt;
use EesyPHP\Db\AttrSet;
use EesyPHP\Db\AttrStr;
use EesyPHP\Db\AttrTimestamp;
use EesyPHP\Db\DbObject;
@ -32,12 +33,43 @@ class Item extends DbObject {
protected const DEFAULT_ORDER_DIRECTION = 'DESC';
protected const POSSIBLE_ORDERS = ['id', 'name', 'date', 'status'];
/**
* Get status possible values with their translated label
* @param boolean $with_all_choice Set to true to add the 'all' value (optional, default: false)
* @return array<string,string>
*/
public static function statuses($with_all_choice=false) {
$statuses = array (
'pending' => _('Pending'),
'validated' => _('Validated'),
'refused' => _('Refused'),
'archived' => _('Archived'),
);
if ($with_all_choice)
$statuses['all'] = _('Any');
return $statuses;
}
/**
* Check item status value
* @param mixed $value Value to check
* @param boolean $allow_all Set to true to allow the 'all' value (optional, default: false)
* @return boolean
*/
public static function check_status($value, $allow_all=false) {
return array_key_exists($value, self :: statuses($allow_all));
}
protected static function get_schema() {
return [
'id' => new AttrInt(['autoincrement' => true]),
'name' => new AttrStr(['required' => true]),
'date' => new AttrTimestamp(['default' => 'time']),
'status' => new AttrStr(['required' => true, 'default' => 'pending']),
'status' => new AttrSet([
'required' => true,
'default' => 'pending',
'possible_values' => array_keys(self :: statuses()),
]),
'description' => new AttrStr(),
];
}

View file

@ -20,7 +20,7 @@
<div class="col-sm-10">
<select name="status" id="status" required
class="form-select{if array_key_exists('status', $field_errors)} is-invalid{else if $submitted} is-valid{/if}">
{html_options options=$status_list selected=$info->status}
{html_options options=$statuses selected=$info->status}
</select>
{if array_key_exists('status', $field_errors)}
<div class="invalid-feedback">{$field_errors['status']}</div>

View file

@ -15,7 +15,7 @@
<label class="input-group-text" for="status">{t}Status{/t}</label>
<select name="status" id="status"
class="form-select{if isset($status_error) && $status_error} is-invalid{/if}">
{html_options options=$status_list selected=$search.filters.status}
{html_options options=$status_choices selected=$search.filters.status}
</select>
</div>
</div>

47
src/Db/AttrSet.php Normal file
View file

@ -0,0 +1,47 @@
<?php
namespace EesyPHP\Db;
class AttrSet extends Attr {
/**
* Possible values
* @var array<mixed>
*/
protected $possible_values = [];
/**
* Compute attribute value from DB
* @param string|null $value The value as retrieved from debug
* @return string|null The attribute value
*/
public function from_db($value) {
$value = parent::from_db($value);
if (is_null($value))
return null;
if (!in_array($value, $this -> possible_values))
throw new DbException(
"Unexpected value '%s' retrieved from database. Should be one of the following values: %s",
$value, implode(', ', $this -> possible_values)
);
return $value;
}
/**
* Compute attribute value for DB
* @param string|null $value The value as handled in PHP
* @return string|null The attribute value as stored in DB
*/
public function to_db($value) {
$value = parent::from_db($value);
if (is_null($value))
return null;
if (!in_array($value, $this -> possible_values))
throw new DbException(
"Unexpected value '%s'. Should be one of the following values: %s",
$value, implode(', ', $this -> possible_values)
);
return $value;
}
}