Example: use AttrSet and cleanup way to handle item status possible values

This commit is contained in:
Benjamin Renard 2024-02-18 19:40:58 +01:00
parent dfbb4d6f9c
commit 4907442122
Signed by: bn8
GPG key ID: 3E2E1CE1907115BC
9 changed files with 48 additions and 50 deletions

View file

@ -66,7 +66,7 @@ function cli_list($command_args) {
case '-s': case '-s':
case '--status': case '--status':
$i++; $i++;
if(!check_status($command_args[$i])) if(!Item :: check_status($command_args[$i]))
Cli :: usage('Invalid -s/--status clause'); Cli :: usage('Invalid -s/--status clause');
$params['filters']['status'] = $command_args[$i]; $params['filters']['status'] = $command_args[$i];
break; break;
@ -124,7 +124,7 @@ Cli :: add_command(
" - ".implode("\n - ", Item :: possible_orders()), " - ".implode("\n - ", Item :: possible_orders()),
___("-r|--reverse Reverse order"), ___("-r|--reverse Reverse order"),
___("-s|--status Filter on status. Possible values:"), ___("-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'); 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('cli.php');
require_once('templates.php'); require_once('templates.php');
require_once('views/index.php'); require_once('views/index.php');

View file

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

View file

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

View file

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

View file

@ -9,9 +9,3 @@ parameters:
- EesyPHP\UrlRequest - EesyPHP\UrlRequest
- EesyPHP\Auth\User - EesyPHP\Auth\User
treatPhpDocTypesAsCertain: false 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\AttrBool;
use EesyPHP\Db\AttrInt; use EesyPHP\Db\AttrInt;
use EesyPHP\Db\AttrSet;
use EesyPHP\Db\AttrStr; use EesyPHP\Db\AttrStr;
use EesyPHP\Db\AttrTimestamp; use EesyPHP\Db\AttrTimestamp;
use EesyPHP\Db\DbObject; use EesyPHP\Db\DbObject;
@ -32,12 +33,43 @@ class Item extends DbObject {
protected const DEFAULT_ORDER_DIRECTION = 'DESC'; protected const DEFAULT_ORDER_DIRECTION = 'DESC';
protected const POSSIBLE_ORDERS = ['id', 'name', 'date', 'status']; 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() { protected static function get_schema() {
return [ return [
'id' => new AttrInt(['autoincrement' => true]), 'id' => new AttrInt(['autoincrement' => true]),
'name' => new AttrStr(['required' => true]), 'name' => new AttrStr(['required' => true]),
'date' => new AttrTimestamp(['default' => 'time']), '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(), 'description' => new AttrStr(),
]; ];
} }

View file

@ -20,7 +20,7 @@
<div class="col-sm-10"> <div class="col-sm-10">
<select name="status" id="status" required <select name="status" id="status" required
class="form-select{if array_key_exists('status', $field_errors)} is-invalid{else if $submitted} is-valid{/if}"> 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> </select>
{if array_key_exists('status', $field_errors)} {if array_key_exists('status', $field_errors)}
<div class="invalid-feedback">{$field_errors['status']}</div> <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> <label class="input-group-text" for="status">{t}Status{/t}</label>
<select name="status" id="status" <select name="status" id="status"
class="form-select{if isset($status_error) && $status_error} is-invalid{/if}"> 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> </select>
</div> </div>
</div> </div>