Formats an array of permissions into a JSON encoded string suitable for the database

@param  array $aRules An array of rules to set

@return string
517256
public function processRules($aRules)
    {
        if (empty($aRules)) {
            return null;
        }

        $aOut = [];

        //  Min/max length
        $aOut['min'] = !empty($aRules['min']) ? (int) $aRules['min'] : null;
        $aOut['max'] = !empty($aRules['max']) ? (int) $aRules['max'] : null;

        //  Expiration
        $aOut['expiresAfter'] = !empty($aRules['expires_after']) ? (int) $aRules['expires_after'] : null;

        //  Requirements
        $aOut['requirements'] = [];
        if (!empty($aRules['requirements'])) {
            $aOut['requirements']['symbol']      = in_array('symbol', $aRules['requirements']);
            $aOut['requirements']['number']      = in_array('number', $aRules['requirements']);
            $aOut['requirements']['lower_alpha'] = in_array('lower_alpha', $aRules['requirements']);
            $aOut['requirements']['upper_alpha'] = in_array('upper_alpha', $aRules['requirements']);
            $aOut['requirements']                = array_filter($aOut['requirements']);
        }

        //  Banned words
        $aOut['banned'] = [];
        if (!empty($aRules['banned'])) {
            $aRules['banned'] = trim($aRules['banned']);
            $aOut['banned']   = explode(',', $aRules['banned']);
            $aOut['banned']   = array_map('trim', $aOut['banned']);
            $aOut['banned']   = array_map('strtolower', $aOut['banned']);
            $aOut['banned']   = array_filter($aOut['banned']);
        }
        $aOut = array_filter($aOut);

        return empty($aOut) ? null : json_encode($aOut);
    }
454061
private function format_filter($filters = array()) {
    $filters_merged = array();
    foreach ($filters as $ky => $vl) {
      $filters_merged[] = $ky . ':' . $vl;
    }

    return implode(',', $filters_merged);
  }
313335
public function jsonCommand($services = [], $table_pattern = '')
    {
        foreach ($services ?: $this->_getDbServices() as $service) {
            /** @var \ManaPHP\DbInterface $db */
            $db = $this->_di->getShared($service);
            foreach ($this->_getTables($service, $table_pattern) as $table) {
                $fileName = "@tmp/db_json/$service/$table.json";

                $this->console->progress(['`:table` processing...', 'table' => $table], '');

                $this->filesystem->dirCreate(dirname($fileName));
                $rows = $db->fetchAll("SELECT * FROM [$table]");
                $file = fopen($this->alias->resolve($fileName), 'wb');

                $startTime = microtime(true);
                foreach ($rows as $row) {
                    fwrite($file, json_encode($row) . PHP_EOL);
                }
                fclose($file);

                $this->console->progress([
                    'write to `:file` success: :count [:time]',
                    'file' => $fileName,
                    'count' => count($rows),
                    'time' => round(microtime(true) - $startTime, 4)
                ]);
            }
        }
    }
779822
public function getRules()
    {
        if (!$this->rules) {
            return '[]';
        }
        $results = '[' . PHP_EOL;

        foreach ($this->getSchemaParser()->toArray() as $column => $value) {
            $results .= "\t\t'{$column}'\t=>'\t{$value}'," . PHP_EOL;
        }

        return $results . "\t" . ']';
    }
325970
protected function generateRules($rules)
    {
        return collect($rules)->mapWithKeys(function ($rules, $key) {
            return [$this->attribute . '.' . $key => $rules];
        })->toArray();
    }
1101719
public function givePermissionTo(...$permissions)
    {
        $permissions = collect($permissions)
            ->flatten()
            ->map(function ($permission) {
                if (empty($permission)) {
                    return false;
                }

                return $this->getStoredPermission($permission);
            })
            ->filter(function ($permission) {
                return $permission instanceof Permission;
            })
            ->each(function ($permission) {
                $this->ensureModelSharesGuard($permission);
            })
            ->map->id
            ->all();

        $model = $this->getModel();

        if ($model->exists) {
            $this->permissions()->sync($permissions, false);
            $model->load('permissions');
        } else {
            $class = \get_class($model);

            $class::saved(
                function ($object) use ($permissions, $model) {
                    static $modelLastFiredOn;
                    if ($modelLastFiredOn !== null && $modelLastFiredOn === $model) {
                        return;
                    }
                    $object->permissions()->sync($permissions, false);
                    $object->load('permissions');
                    $modelLastFiredOn = $object;
                }
            );
        }

        $this->forgetCachedPermissions();

        return $this;
    }
516358
public static function createFromData($permissions)
    {
        return array_map(function ($permission) {
            if (is_array($permission)) {
                return PermissionFactory::createFromArray($permission);
            } else {
                return PermissionFactory::createFromObject($permission);
            }
        }, $permissions);
    }
401711
public function permissions($permissions = null)
    {
        if (!$this->protect()) {
            return $this;
        }

        if ($permissions === null) {
            return $this->_allow;
        }

        if (is_string($permissions) && $permissions == 'all') {
            $permissions = true;
        }

        if (is_string($permissions) && $permissions == 'none') {
            $permissions = false;
        }

        if (is_array($permissions)) {
            foreach ($permissions as $permission) {
                if (!in_array($permission, $this->_availablePermissions)) {
                    throw new Exception(sprintf('Invalid permission: %s', $permission));
                }

                if (!$this->crypto()->permissionImplemented($permission)) {
                    throw new Exception(sprintf('Permission not implemented in crypto engine: %s', $permission));
                }
            }
        }

        $this->_allow = $permissions;

        return $this;
    }
989138
public function setPermissions($permissions)
    {
        if (! is_array($permissions)) {
            $permissions = [$permissions];
        }

        $this->permissions = $permissions;

        return $this;
    }
319870
protected function arrayToCss(array $rules)
    {
        $strings = [];

        foreach ($rules as $key => $value) {
            $strings[] = $key . ': ' . $value;
        }

        return implode('; ', $strings);
    }
318705
public function setPermissionsAttribute(array $permissions = [])
    {
        foreach ($permissions as $key => $value) {
            $permissions[$key] = (bool) $value;
        }
        $this->attributes['permissions'] = json_encode($permissions ?? []);
    }
306120
protected function setDirPermissions($permissions)
    {
        $permissions = (int) $permissions;

        if (! (0b100000000 & $permissions)) {
            throw new InvalidArgumentException(sprintf(
                'Invalid permissions "%s" for directories. '
                . 'Directories will not available for reading.',
                decoct($permissions)
            ));
        }
        if (! (0b010000000 & $permissions)) {
            throw new InvalidArgumentException(sprintf(
                'Invalid permissions "%s" for directories. '
                . 'Directories will not available for writing.',
                decoct($permissions)
            ));
        }
        if (! (0b001000000 & $permissions)) {
            throw new InvalidArgumentException(sprintf(
                'Invalid permissions "%s" for directories. '
                . 'The content of directories will not available.',
                decoct($permissions)
            ));
        }
        $this->dirPermissions = $permissions;
    }
1281114
function permissions($Role, $OnlyIDs = true)
	{
	    if (! is_numeric ($Role))
	        $Role = $this->returnId($Role);

		if ($OnlyIDs)
		{
			$Res = Jf::sql ( "SELECT PermissionID AS `ID` FROM {$this->tablePrefix()}rolepermissions WHERE RoleID=? ORDER BY PermissionID", $Role );
			if (is_array ( $Res ))
			{
				$out = array ();
				foreach ( $Res as $R )
					$out [] = $R ['ID'];
				return $out;
			}
			else
				return null;
		} else {
	        return Jf::sql ( "SELECT `TP`.ID, `TP`.Title, `TP`.Description FROM {$this->tablePrefix()}permissions AS `TP`
		        LEFT JOIN {$this->tablePrefix()}rolepermissions AS `TR` ON (`TR`.PermissionID=`TP`.ID)
		        WHERE RoleID=? ORDER BY TP.ID", $Role );
		}
	}
1209313
protected function getStoredPermission($permissions)
    {
        $permissionClass = $this->getPermissionClass();

        if (is_numeric($permissions)) {
            return $permissionClass->findById($permissions, $this->getDefaultGuardName());
        }

        if (is_string($permissions)) {
            return $permissionClass->findByName($permissions, $this->getDefaultGuardName());
        }

        if (is_array($permissions)) {
            return $permissionClass
                ->whereIn('name', $permissions)
                ->whereIn('guard_name', $this->getGuardNames())
                ->get();
        }

        return $permissions;
    }
836433
public static function prepareHeaderArrayForPrint(array $arrHeaders)
    {
        $strResult = '';
        $i = 0;

        foreach ($arrHeaders as $strKey => $strValue)
        {
            $strResult .= "$strKey: $strValue";

            if ($i++ != count($arrHeaders) - 1)
            {
                $strResult .= PHP_EOL;
            }
        }

        return $strResult;
    }
402952
protected function outputFormatTableRole(array $items)
    {
        $header = array(
            $this->text('ID'),
            $this->text('Name'),
            $this->text('Redirect'),
            $this->text('Permissions'),
            $this->text('Enabled')
        );

        $rows = array();

        foreach ($items as $item) {
            $rows[] = array(
                $item['role_id'],
                $item['name'],
                $item['redirect'],
                count($item['permissions']),
                empty($item['status']) ? $this->text('No') : $this->text('Yes')
            );
        }

        $this->outputFormatTable($rows, $header);
    }
666208
public function setPermissionsAttribute($permissions)
    {
        $module = lcfirst($this->attributes['name']);

        $roles = array();

        //prefix the permission with the module name ex: user.create
        foreach ($permissions as $key => $value)
        {
            $roles[] = $module . '.' . $value;
        }

        $this->attributes['permissions'] = ( ! empty($roles)) ? json_encode($roles) : '';
    }