如何使用 Codeigniter 4 和 Shield 权限构建 HTML 表格

问题描述 投票:0回答:0

使用 Codeigniter 4.3.3、Shield 1.0.0-beta.5 和 MySQL

我确定我把这个复杂化了......我想使用 auth_permissions_users 表和 2 个左侧导航表 sidebar_modules 和 sidebar_modules_sub 构建一个 html 表。

默认情况下,Shield 喜欢使用存储在 auth_permissions_users 表中的 Group.Permission IE:admin.useredit、admin.useradd 等...我将使用传统的 controller.permission 方法,这就是其他表的原因。

对于桅杆部分,我可以正常工作,但似乎应该有更简单的方法......我在 helpers 文件夹中的 array_helper.php 中构建了一个函数。该函数将拆分 controller.permission,按控制器对它们进行分组,然后根据它找到的内容构建表。虽然我说它有效,但我有 2 个问题:

#1 - 我想要表格 IE 中的 5 行:|控制器 |创建 |阅读 |更新 |删除 |所以如果没有向用户提供权限,我必须填写任何空白。

#2 - 需要弄清楚如何以它们在表格中完全正确的方式对它们进行排序,这样我就可以添加一个 jQuery 元素来单击并根据需要更改用户的权限。它们并不总是以相同的顺序输入数据库表

来自 Shield 的数据使用 $user->getPermissions();

Array
(
    [0] => admin.read
    [1] => usergroups.read
    [2] => usergroups.create
    [3] => usergroups.update
    [4] => usergroups.delete
    [5] => users.read
    [6] => users.update
    [7] => users.create
    [8] => activitylogs.read
    [9] => authgroups.read
    [10] => authgroups.create
    [11] => authgroups.update
    [12] => authgroups.delete
)

我也写了另一个查询,但似乎与权限排序的结果相同

SELECT DISTINCT 
  SUBSTRING_INDEX(SUBSTRING_INDEX(`permission`,'.', 1),'.', -1) AS `controllers`,
  SUBSTRING_INDEX(SUBSTRING_INDEX(`permission`,'.', 2),'.', -1) AS `permissions`,
  `auth_permissions_users`.`permission`,
  `modules`.`slug` AS `modules`,
  `sub_modules`.`slug` AS `sub_modules`
FROM
  `auth_permissions_users`
  LEFT JOIN `sidebar_modules` AS `modules` ON (`modules`.`slug` = SUBSTRING_INDEX(`permission`,'.', 1))
  LEFT JOIN `sidebar_modules_sub` AS `sub_modules` ON (`sub_modules`.`slug` = SUBSTRING_INDEX(`permission`,'.', 1))

我在侧边栏表格中使用“slug”来识别控制器。在路由中,我将显示方法 userGroups 的 user_groups。和菜单语言文件中的 user_groups。输出如下所示:

array_helper.php

if (!function_exists('array_reorder_keys')) {
    
    /**
     * function array_reorder_keys
     * reorder the keys of an array in order of specified keynames; all other nodes not in $keynames will come after last $keyname, in normal array order
     * @param array &$array - the array to reorder
     * @param mixed $keynames - a csv or array of keynames, in the order that keys should be reordered
     * 
     * $seed_array = array('foo'=>'bar', 'someotherkey'=>'whatev', 'bar'=>'baz', 'baz'=>'foo', 'anotherkey'=>'anotherval');
     * 
     * array_reorder_keys($seed_array, 'baz,foo,bar'); 
     * 
     * @returns array('baz'=>'foo', 'foo'=>'bar', 'bar'=>'baz', 'someotherkey'=>'whatev', 'anotherkey'=>'anotherval' );
     * 
     */
    
    function array_reorder_keys(&$array, $keynames){
        if(empty($array) || !is_array($array) || empty($keynames)) return;
        if(!is_array($keynames)) $keynames = explode(',',$keynames);
        if(!empty($keynames)) $keynames = array_reverse($keynames);
        foreach($keynames as $n){
            if(array_key_exists($n, $array)){
                $newarray = array($n=>$array[$n]); //copy the node before unsetting
                unset($array[$n]); //remove the node
                $array = $newarray + array_filter($array); //combine copy with filtered array
            }
        }
    }
}

if (!function_exists('buildPermissionsTable')) {
    
    /**
     * Assumes Codeigniter - Shield - Creates a table row(s) to populate the Permissions Table.
     * This builds from the Shield auth_permissions_users DB Table
     * @param $user->getPermissions() should be stored like: "group.value" or "controller.permission" 
     *
     * This function will split from the "." and populate the table with:
     *      Group - Permission - Permission - Permission - Permission
     *      Controller - Permission - Permission - Permission - Permission
     *      ** Currently set to Create - Read - Update - Delete
     * 
     * @param $array = $user->getPermissions();
     * @param $permissionTable = buildPermissionsTable($array);
     * @param echo $permissionTable = build out HTML Table.
     * 
     * @return array|msg Returns a HTML Table array or `No Data` if `$array` is invalid or empty.
     * 
     * 
     */
    
    function buildPermissionsTable(array $array) {
        
        $pTableHeader = PHP_EOL .'<table class="table table-sm table-bordered table-striped table-hover" style="width: 100%;">'. PHP_EOL .'<thead>'. PHP_EOL .'<tr>'. PHP_EOL .'<th><strong>'. lang('App.controller') .'</strong>:</th>'. PHP_EOL .'<th>Create</th>'. PHP_EOL .'<th>Read</th>'. PHP_EOL .'<th>Update</th>'. PHP_EOL .'<th>Delete</th>'. PHP_EOL .'</thead>'.PHP_EOL .'<tbody>'. PHP_EOL;
        $pTableFooter = PHP_EOL .'</tbody>'.PHP_EOL .'</table>';
        
        if (!$array) {
            $pTableBody = PHP_EOL .'<tr>'. PHP_EOL .'<td colspan="5" class="text-center">No Data Provided...</td>'. PHP_EOL .'</tr>'. PHP_EOL;
            return $pTableHeader . $pTableBody . $pTableFooter;
        }
        
        $permData1 = [];
        $permData2 = [];
        foreach ($array as $key) {
            list($a, $b) = explode('.', $key);
            array_push($permData1, [
                'controller' => $a,
                'permission' => $b,
            ]);
        }
        
        $perms                      = array_group_by($permData1, 'controller');
        
        foreach ($perms as $key => $value):
            
            $a = array_count_values(array_column($value, 'controller'))[$key];
        
            // We want to fill the table with values 
            // if missing since we need a total of 4
            
            for($i=$a;$i<4;$i++)
            {
                array_push($permData2, [
                    'controller'    => $key,
                    'permission'    => 'none',
                ]);
            }            
            
        endforeach;

        $permData                   = array_merge($permData1,$permData2);
        $permissions                = array_group_by($permData, 'controller');
        $pTableBody                 = '';
        
        foreach ($permissions as $key => $value):                                    
            $pTableBody .=  PHP_EOL .'<tr>'. PHP_EOL;
            $pTableBody .= '<td><strong>'. strtoupper($key) .'</strong></td>'. PHP_EOL;

            // $r is to see the place the controller.permission is sitting
            // need to remove when done testing
            $r=0;
            
            foreach ($value as $module): 
                
                ++$r;
                
                if($module['permission']=='create')
                {
                    $pTableBody .= '<td class="text-center text-success"><i class="fas fa-check fa-xl"></i><br>'. $r.'--'.$module['controller'] .'.'. $module['permission'].'</td>'. PHP_EOL;
                    continue;
                }
                if($module['permission']=='read')
                {
                    $pTableBody .= '<td class="text-center text-success"><i class="fas fa-check fa-xl"></i><br>'. $r.'--'.$module['controller'] .'.'. $module['permission'].'</td>'. PHP_EOL;
                    continue;
                }
                if($module['permission']=='update')
                {
                    $pTableBody .= '<td class="text-center text-success"><i class="fas fa-check fa-xl"></i><br>'. $r.'--'.$module['controller'] .'.'. $module['permission'].'</td>'. PHP_EOL;
                    continue;
                }
                if($module['permission']=='delete')
                {
                    $pTableBody .= '<td class="text-center text-success"><i class="fas fa-check fa-xl"></i><br>'. $r.'--'.$module['controller'] .'.'. $module['permission'].'</td>'. PHP_EOL;
                    continue;
                } 
                else
                {
                    $pTableBody .= '<td class="text-center text-danger"><i class="fas fa-remove fa-xl"></i><br>'. $r.'--'.$module['controller'] .'.'. $module['permission'].'</td>'. PHP_EOL;
                    continue;
                }
            endforeach;

        $pTableBody .= '</tr>'. PHP_EOL;
        endforeach;
        
        return $pTableHeader . $pTableBody . $pTableFooter;
    }
    
}

这是表格现在的样子,请注意它们的顺序不正确。它应该与列标题正确对齐:

|控制器 |创建 |阅读 |更新 |删除 |

mysql html-table codeigniter-4 user-permissions
© www.soinside.com 2019 - 2024. All rights reserved.