repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Validation.php
system/Language/en/Validation.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ // Validation language settings return [ // Core Messages 'noRuleSets' => 'No rule sets specified in Validation configuration.', 'ruleNotFound' => '"{0}" is not a valid rule.', 'groupNotFound' => '"{0}" is not a validation rules group.', 'groupNotArray' => '"{0}" rule group must be an array.', 'invalidTemplate' => '"{0}" is not a valid Validation template.', // Rule Messages 'alpha' => 'The {field} field may only contain alphabetical characters.', 'alpha_dash' => 'The {field} field may only contain alphanumeric, underscore, and dash characters.', 'alpha_numeric' => 'The {field} field may only contain alphanumeric characters.', 'alpha_numeric_punct' => 'The {field} field may contain only alphanumeric characters, spaces, and ~ ! # $ % & * - _ + = | : . characters.', 'alpha_numeric_space' => 'The {field} field may only contain alphanumeric and space characters.', 'alpha_space' => 'The {field} field may only contain alphabetical characters and spaces.', 'decimal' => 'The {field} field must contain a decimal number.', 'differs' => 'The {field} field must differ from the {param} field.', 'equals' => 'The {field} field must be exactly: {param}.', 'exact_length' => 'The {field} field must be exactly {param} characters in length.', 'field_exists' => 'The {field} field must exist.', 'greater_than' => 'The {field} field must contain a number greater than {param}.', 'greater_than_equal_to' => 'The {field} field must contain a number greater than or equal to {param}.', 'hex' => 'The {field} field may only contain hexadecimal characters.', 'in_list' => 'The {field} field must be one of: {param}.', 'integer' => 'The {field} field must contain an integer.', 'is_natural' => 'The {field} field must only contain digits.', 'is_natural_no_zero' => 'The {field} field must only contain digits and must be greater than zero.', 'is_not_unique' => 'The {field} field must contain a previously existing value in the database.', 'is_unique' => 'The {field} field must contain a unique value.', 'less_than' => 'The {field} field must contain a number less than {param}.', 'less_than_equal_to' => 'The {field} field must contain a number less than or equal to {param}.', 'matches' => 'The {field} field does not match the {param} field.', 'max_length' => 'The {field} field cannot exceed {param} characters in length.', 'min_length' => 'The {field} field must be at least {param} characters in length.', 'not_equals' => 'The {field} field cannot be: {param}.', 'not_in_list' => 'The {field} field must not be one of: {param}.', 'numeric' => 'The {field} field must contain only numbers.', 'regex_match' => 'The {field} field is not in the correct format.', 'required' => 'The {field} field is required.', 'required_with' => 'The {field} field is required when {param} is present.', 'required_without' => 'The {field} field is required when {param} is not present.', 'string' => 'The {field} field must be a valid string.', 'timezone' => 'The {field} field must be a valid timezone.', 'valid_base64' => 'The {field} field must be a valid base64 string.', 'valid_email' => 'The {field} field must contain a valid email address.', 'valid_emails' => 'The {field} field must contain all valid email addresses.', 'valid_ip' => 'The {field} field must contain a valid IP.', 'valid_url' => 'The {field} field must contain a valid URL.', 'valid_url_strict' => 'The {field} field must contain a valid URL.', 'valid_date' => 'The {field} field must contain a valid date.', 'valid_json' => 'The {field} field must contain a valid json.', // Credit Cards 'valid_cc_num' => '{field} does not appear to be a valid credit card number.', // Files 'uploaded' => '{field} is not a valid uploaded file.', 'max_size' => '{field} is too large of a file.', 'is_image' => '{field} is not a valid, uploaded image file.', 'mime_in' => '{field} does not have a valid mime type.', 'ext_in' => '{field} does not have a valid file extension.', 'max_dims' => '{field} is either not an image, or it is too wide or tall.', 'min_dims' => '{field} is either not an image, or it is not wide or tall enough.', ];
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Cache.php
system/Language/en/Cache.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ // Cache language settings return [ 'unableToWrite' => 'Cache unable to write to "{0}".', 'invalidHandlers' => 'Cache config must have an array of $validHandlers.', 'noBackup' => 'Cache config must have a handler and backupHandler set.', 'handlerNotFound' => 'Cache config has an invalid handler or backup handler specified.', ];
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/RESTful.php
system/Language/en/RESTful.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ // RESTful language settings return [ 'notImplemented' => '"{0}" action not implemented.', ];
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Migrations.php
system/Language/en/Migrations.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ // Migration language settings return [ // Migration Runner 'missingTable' => 'Migrations table must be set.', 'disabled' => 'Migrations have been loaded but are disabled or setup incorrectly.', 'notFound' => 'Migration file not found: ', 'batchNotFound' => 'Target batch not found: ', 'empty' => 'No Migration files found', 'gap' => 'There is a gap in the migration sequence near version number: ', 'classNotFound' => 'The migration class "%s" could not be found.', 'missingMethod' => 'The migration class is missing an "%s" method.', // Migration Command 'migHelpLatest' => "\t\tMigrates database to latest available migration.", 'migHelpCurrent' => "\t\tMigrates database to version set as 'current' in configuration.", 'migHelpVersion' => "\tMigrates database to version {v}.", 'migHelpRollback' => "\tRuns all migrations 'down' to version 0.", 'migHelpRefresh' => "\t\tUninstalls and re-runs all migrations to freshen database.", 'migHelpSeed' => "\tRuns the seeder named [name].", 'migCreate' => "\tCreates a new migration named [name]", 'nameMigration' => 'Name the migration file', 'migNumberError' => 'Migration number must be three digits, and there must not be any gaps in the sequence.', 'rollBackConfirm' => 'Are you sure you want to rollback?', 'refreshConfirm' => 'Are you sure you want to refresh?', 'latest' => 'Running all new migrations...', 'generalFault' => 'Migration failed!', 'migrated' => 'Migrations complete.', 'migInvalidVersion' => 'Invalid version number provided.', 'toVersionPH' => 'Migrating to version %s...', 'toVersion' => 'Migrating to current version...', 'rollingBack' => 'Rolling back migrations to batch: ', 'noneFound' => 'No migrations were found.', 'migSeeder' => 'Seeder name', 'migMissingSeeder' => 'You must provide a seeder name.', 'nameSeeder' => 'Name the seeder file', 'removed' => 'Rolling back: ', 'added' => 'Running: ', // Migrate Status 'namespace' => 'Namespace', 'filename' => 'Filename', 'version' => 'Version', 'group' => 'Group', 'on' => 'Migrated On: ', 'batch' => 'Batch', ];
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Pager.php
system/Language/en/Pager.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ // Pager language settings return [ 'pageNavigation' => 'Page navigation', 'first' => 'First', 'previous' => 'Previous', 'next' => 'Next', 'last' => 'Last', 'older' => 'Older', 'newer' => 'Newer', 'invalidTemplate' => '"{0}" is not a valid Pager template.', 'invalidPaginationGroup' => '"{0}" is not a valid Pagination group.', ];
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Session.php
system/Language/en/Session.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ // Session language settings return [ 'missingDatabaseTable' => '"sessionSavePath" must have the table name for the Database Session Handler to work.', 'invalidSavePath' => 'Session: Configured save path "{0}" is not a directory, does not exist or cannot be created.', 'writeProtectedSavePath' => 'Session: Configured save path "{0}" is not writable by the PHP process.', 'emptySavePath' => 'Session: No save path configured.', 'invalidSavePathFormat' => 'Session: Invalid Redis save path format: "{0}"', // @deprecated 'invalidSameSiteSetting' => 'Session: The SameSite setting must be None, Lax, Strict, or a blank string. Given: "{0}"', ];
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/View.php
system/Language/en/View.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ // View language settings return [ 'invalidCellMethod' => '{class}::{method} is not a valid method.', 'missingCellParameters' => '{class}::{method} has no params.', 'invalidCellParameter' => '"{0}" is not a valid param name.', 'noCellClass' => 'No view cell class provided.', 'invalidCellClass' => 'Unable to locate view cell class: "{0}".', 'tagSyntaxError' => 'You have a syntax error in your Parser tags: "{0}"', 'invalidDecoratorClass' => '"{0}" is not a valid View Decorator.', ];
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Files.php
system/Language/en/Files.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ // Files language settings return [ 'fileNotFound' => 'File not found: "{0}"', 'cannotMove' => 'Could not move file "{0}" to "{1}". Reason: {2}', 'expectedDirectory' => '{0} expects a valid directory.', 'expectedFile' => '{0} expects a valid file.', ];
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/ListCommands.php
system/Commands/ListCommands.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; /** * CI Help command for the spark script. * * Lists the basic usage information for the spark script, * and provides a way to list help for other commands. */ class ListCommands extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'CodeIgniter'; /** * The Command's name * * @var string */ protected $name = 'list'; /** * the Command's short description * * @var string */ protected $description = 'Lists the available commands.'; /** * the Command's usage * * @var string */ protected $usage = 'list'; /** * the Command's Arguments * * @var array<string, string> */ protected $arguments = []; /** * the Command's Options * * @var array<string, string> */ protected $options = [ '--simple' => 'Prints a list of the commands with no other info', ]; /** * Displays the help for the spark cli script itself. * * @return int */ public function run(array $params) { $commands = $this->commands->getCommands(); ksort($commands); // Check for 'simple' format return array_key_exists('simple', $params) || CLI::getOption('simple') === true ? $this->listSimple($commands) : $this->listFull($commands); } /** * Lists the commands with accompanying info. * * @return int */ protected function listFull(array $commands) { // Sort into buckets by group $groups = []; foreach ($commands as $title => $command) { if (! isset($groups[$command['group']])) { $groups[$command['group']] = []; } $groups[$command['group']][$title] = $command; } $length = max(array_map(strlen(...), array_keys($commands))); ksort($groups); // Display it all... foreach ($groups as $group => $commands) { CLI::write($group, 'yellow'); foreach ($commands as $name => $command) { $name = $this->setPad($name, $length, 2, 2); $output = CLI::color($name, 'green'); if (isset($command['description'])) { $output .= CLI::wrap($command['description'], 125, strlen($name)); } CLI::write($output); } if ($group !== array_key_last($groups)) { CLI::newLine(); } } return EXIT_SUCCESS; } /** * Lists the commands only. * * @return int */ protected function listSimple(array $commands) { foreach (array_keys($commands) as $title) { CLI::write($title); } return EXIT_SUCCESS; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Help.php
system/Commands/Help.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands; use CodeIgniter\CLI\BaseCommand; /** * CI Help command for the spark script. * * Lists the basic usage information for the spark script, * and provides a way to list help for other commands. */ class Help extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'CodeIgniter'; /** * The Command's name * * @var string */ protected $name = 'help'; /** * the Command's short description * * @var string */ protected $description = 'Displays basic usage information.'; /** * the Command's usage * * @var string */ protected $usage = 'help [<command_name>]'; /** * the Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'command_name' => 'The command name [default: "help"]', ]; /** * the Command's Options * * @var array<string, string> */ protected $options = []; /** * Displays the help for spark commands. */ public function run(array $params) { $command = array_shift($params); $command ??= 'help'; $commands = $this->commands->getCommands(); if (! $this->commands->verifyCommand($command, $commands)) { return; } $class = new $commands[$command]['class']($this->logger, $this->commands); $class->showHelp(); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/ControllerGenerator.php
system/Commands/Generators/ControllerGenerator.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Generators; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\CLI\GeneratorTrait; use CodeIgniter\Controller; use CodeIgniter\RESTful\ResourceController; use CodeIgniter\RESTful\ResourcePresenter; /** * Generates a skeleton controller file. */ class ControllerGenerator extends BaseCommand { use GeneratorTrait; /** * The Command's Group * * @var string */ protected $group = 'Generators'; /** * The Command's Name * * @var string */ protected $name = 'make:controller'; /** * The Command's Description * * @var string */ protected $description = 'Generates a new controller file.'; /** * The Command's Usage * * @var string */ protected $usage = 'make:controller <name> [options]'; /** * The Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'name' => 'The controller class name.', ]; /** * The Command's Options * * @var array<string, string> */ protected $options = [ '--bare' => 'Extends from CodeIgniter\Controller instead of BaseController.', '--restful' => 'Extends from a RESTful resource, Options: [controller, presenter]. Default: "controller".', '--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".', '--suffix' => 'Append the component title to the class name (e.g. User => UserController).', '--force' => 'Force overwrite existing file.', ]; /** * Actually execute a command. */ public function run(array $params) { $this->component = 'Controller'; $this->directory = 'Controllers'; $this->template = 'controller.tpl.php'; $this->classNameLang = 'CLI.generator.className.controller'; $this->generateClass($params); } /** * Prepare options and do the necessary replacements. */ protected function prepare(string $class): string { $bare = $this->getOption('bare'); $rest = $this->getOption('restful'); $useStatement = trim(APP_NAMESPACE, '\\') . '\Controllers\BaseController'; $extends = 'BaseController'; // Gets the appropriate parent class to extend. if ($bare || $rest) { if ($bare) { $useStatement = Controller::class; $extends = 'Controller'; } elseif ($rest) { $rest = is_string($rest) ? $rest : 'controller'; if (! in_array($rest, ['controller', 'presenter'], true)) { // @codeCoverageIgnoreStart $rest = CLI::prompt(lang('CLI.generator.parentClass'), ['controller', 'presenter'], 'required'); CLI::newLine(); // @codeCoverageIgnoreEnd } if ($rest === 'controller') { $useStatement = ResourceController::class; $extends = 'ResourceController'; } elseif ($rest === 'presenter') { $useStatement = ResourcePresenter::class; $extends = 'ResourcePresenter'; } } } return $this->parseTemplate( $class, ['{useStatement}', '{extends}'], [$useStatement, $extends], ['type' => $rest], ); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/ModelGenerator.php
system/Commands/Generators/ModelGenerator.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Generators; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\CLI\GeneratorTrait; /** * Generates a skeleton Model file. */ class ModelGenerator extends BaseCommand { use GeneratorTrait; /** * The Command's Group * * @var string */ protected $group = 'Generators'; /** * The Command's Name * * @var string */ protected $name = 'make:model'; /** * The Command's Description * * @var string */ protected $description = 'Generates a new model file.'; /** * The Command's Usage * * @var string */ protected $usage = 'make:model <name> [options]'; /** * The Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'name' => 'The model class name.', ]; /** * The Command's Options * * @var array<string, string> */ protected $options = [ '--table' => 'Supply a table name. Default: "the lowercased plural of the class name".', '--dbgroup' => 'Database group to use. Default: "default".', '--return' => 'Return type, Options: [array, object, entity]. Default: "array".', '--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".', '--suffix' => 'Append the component title to the class name (e.g. User => UserModel).', '--force' => 'Force overwrite existing file.', ]; /** * Actually execute a command. */ public function run(array $params) { $this->component = 'Model'; $this->directory = 'Models'; $this->template = 'model.tpl.php'; $this->classNameLang = 'CLI.generator.className.model'; $this->generateClass($params); } /** * Prepare options and do the necessary replacements. */ protected function prepare(string $class): string { $table = $this->getOption('table'); $dbGroup = $this->getOption('dbgroup'); $return = $this->getOption('return'); $baseClass = class_basename($class); if (preg_match('/^(\S+)Model$/i', $baseClass, $match) === 1) { $baseClass = $match[1]; } $table = is_string($table) ? $table : plural(strtolower($baseClass)); $return = is_string($return) ? $return : 'array'; if (! in_array($return, ['array', 'object', 'entity'], true)) { // @codeCoverageIgnoreStart $return = CLI::prompt(lang('CLI.generator.returnType'), ['array', 'object', 'entity'], 'required'); CLI::newLine(); // @codeCoverageIgnoreEnd } if ($return === 'entity') { $return = str_replace('Models', 'Entities', $class); if (preg_match('/^(\S+)Model$/i', $return, $match) === 1) { $return = $match[1]; if ($this->getOption('suffix')) { $return .= 'Entity'; } } $return = '\\' . trim($return, '\\') . '::class'; $this->call('make:entity', array_merge([$baseClass], $this->params)); } else { $return = "'{$return}'"; } return $this->parseTemplate($class, ['{dbGroup}', '{table}', '{return}'], [$dbGroup, $table, $return], compact('dbGroup')); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/SeederGenerator.php
system/Commands/Generators/SeederGenerator.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Generators; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\GeneratorTrait; /** * Generates a skeleton seeder file. */ class SeederGenerator extends BaseCommand { use GeneratorTrait; /** * The Command's Group * * @var string */ protected $group = 'Generators'; /** * The Command's Name * * @var string */ protected $name = 'make:seeder'; /** * The Command's Description * * @var string */ protected $description = 'Generates a new seeder file.'; /** * The Command's Usage * * @var string */ protected $usage = 'make:seeder <name> [options]'; /** * The Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'name' => 'The seeder class name.', ]; /** * The Command's Options * * @var array<string, string> */ protected $options = [ '--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".', '--suffix' => 'Append the component title to the class name (e.g. User => UserSeeder).', '--force' => 'Force overwrite existing file.', ]; /** * Actually execute a command. */ public function run(array $params) { $this->component = 'Seeder'; $this->directory = 'Database\Seeds'; $this->template = 'seeder.tpl.php'; $this->classNameLang = 'CLI.generator.className.seeder'; $this->generateClass($params); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/ValidationGenerator.php
system/Commands/Generators/ValidationGenerator.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Generators; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\GeneratorTrait; /** * Generates a skeleton Validation file. */ class ValidationGenerator extends BaseCommand { use GeneratorTrait; /** * The Command's Group * * @var string */ protected $group = 'Generators'; /** * The Command's Name * * @var string */ protected $name = 'make:validation'; /** * The Command's Description * * @var string */ protected $description = 'Generates a new validation file.'; /** * The Command's Usage * * @var string */ protected $usage = 'make:validation <name> [options]'; /** * The Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'name' => 'The validation class name.', ]; /** * The Command's Options * * @var array<string, string> */ protected $options = [ '--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".', '--suffix' => 'Append the component title to the class name (e.g. User => UserValidation).', '--force' => 'Force overwrite existing file.', ]; /** * Actually execute a command. */ public function run(array $params) { $this->component = 'Validation'; $this->directory = 'Validation'; $this->template = 'validation.tpl.php'; $this->classNameLang = 'CLI.generator.className.validation'; $this->generateClass($params); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/MigrationGenerator.php
system/Commands/Generators/MigrationGenerator.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Generators; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\CLI\GeneratorTrait; use Config\Database; use Config\Migrations; use Config\Session as SessionConfig; /** * Generates a skeleton migration file. */ class MigrationGenerator extends BaseCommand { use GeneratorTrait; /** * The Command's Group * * @var string */ protected $group = 'Generators'; /** * The Command's Name * * @var string */ protected $name = 'make:migration'; /** * The Command's Description * * @var string */ protected $description = 'Generates a new migration file.'; /** * The Command's Usage * * @var string */ protected $usage = 'make:migration <name> [options]'; /** * The Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'name' => 'The migration class name.', ]; /** * The Command's Options * * @var array<string, string> */ protected $options = [ '--session' => 'Generates the migration file for database sessions.', '--table' => 'Table name to use for database sessions. Default: "ci_sessions".', '--dbgroup' => 'Database group to use for database sessions. Default: "default".', '--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".', '--suffix' => 'Append the component title to the class name (e.g. User => UserMigration).', ]; /** * Actually execute a command. */ public function run(array $params) { $this->component = 'Migration'; $this->directory = 'Database\Migrations'; $this->template = 'migration.tpl.php'; if (array_key_exists('session', $params) || CLI::getOption('session')) { $table = $params['table'] ?? CLI::getOption('table') ?? 'ci_sessions'; $params[0] = "_create_{$table}_table"; } $this->classNameLang = 'CLI.generator.className.migration'; $this->generateClass($params); } /** * Prepare options and do the necessary replacements. */ protected function prepare(string $class): string { $data = []; $data['session'] = false; if ($this->getOption('session')) { $table = $this->getOption('table'); $DBGroup = $this->getOption('dbgroup'); $data['session'] = true; $data['table'] = is_string($table) ? $table : 'ci_sessions'; $data['DBGroup'] = is_string($DBGroup) ? $DBGroup : 'default'; $data['DBDriver'] = config(Database::class)->{$data['DBGroup']}['DBDriver']; $data['matchIP'] = config(SessionConfig::class)->matchIP; } return $this->parseTemplate($class, [], [], $data); } /** * Change file basename before saving. */ protected function basename(string $filename): string { return gmdate(config(Migrations::class)->timestampFormat) . basename($filename); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/ConfigGenerator.php
system/Commands/Generators/ConfigGenerator.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Generators; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\GeneratorTrait; /** * Generates a skeleton config file. */ class ConfigGenerator extends BaseCommand { use GeneratorTrait; /** * The Command's Group * * @var string */ protected $group = 'Generators'; /** * The Command's Name * * @var string */ protected $name = 'make:config'; /** * The Command's Description * * @var string */ protected $description = 'Generates a new config file.'; /** * The Command's Usage * * @var string */ protected $usage = 'make:config <name> [options]'; /** * The Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'name' => 'The config class name.', ]; /** * The Command's Options * * @var array<string, string> */ protected $options = [ '--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".', '--suffix' => 'Append the component title to the class name (e.g. User => UserConfig).', '--force' => 'Force overwrite existing file.', ]; /** * Actually execute a command. */ public function run(array $params) { $this->component = 'Config'; $this->directory = 'Config'; $this->template = 'config.tpl.php'; $this->classNameLang = 'CLI.generator.className.config'; $this->generateClass($params); } /** * Prepare options and do the necessary replacements. */ protected function prepare(string $class): string { $namespace = $this->getOption('namespace') ?? APP_NAMESPACE; if ($namespace === APP_NAMESPACE) { $class = substr($class, strlen($namespace . '\\')); } return $this->parseTemplate($class); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/EntityGenerator.php
system/Commands/Generators/EntityGenerator.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Generators; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\GeneratorTrait; /** * Generates a skeleton Entity file. */ class EntityGenerator extends BaseCommand { use GeneratorTrait; /** * The Command's Group * * @var string */ protected $group = 'Generators'; /** * The Command's Name * * @var string */ protected $name = 'make:entity'; /** * The Command's Description * * @var string */ protected $description = 'Generates a new entity file.'; /** * The Command's Usage * * @var string */ protected $usage = 'make:entity <name> [options]'; /** * The Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'name' => 'The entity class name.', ]; /** * The Command's Options * * @var array<string, string> */ protected $options = [ '--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".', '--suffix' => 'Append the component title to the class name (e.g. User => UserEntity).', '--force' => 'Force overwrite existing file.', ]; /** * Actually execute a command. */ public function run(array $params) { $this->component = 'Entity'; $this->directory = 'Entities'; $this->template = 'entity.tpl.php'; $this->classNameLang = 'CLI.generator.className.entity'; $this->generateClass($params); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/ScaffoldGenerator.php
system/Commands/Generators/ScaffoldGenerator.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Generators; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\CLI\GeneratorTrait; /** * Generates a complete set of scaffold files. */ class ScaffoldGenerator extends BaseCommand { use GeneratorTrait; /** * The Command's Group * * @var string */ protected $group = 'Generators'; /** * The Command's Name * * @var string */ protected $name = 'make:scaffold'; /** * The Command's Description * * @var string */ protected $description = 'Generates a complete set of scaffold files.'; /** * The Command's Usage * * @var string */ protected $usage = 'make:scaffold <name> [options]'; /** * The Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'name' => 'The class name', ]; /** * The Command's Options * * @var array<string, string> */ protected $options = [ '--bare' => 'Add the "--bare" option to controller component.', '--restful' => 'Add the "--restful" option to controller component.', '--table' => 'Add the "--table" option to the model component.', '--dbgroup' => 'Add the "--dbgroup" option to model component.', '--return' => 'Add the "--return" option to the model component.', '--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".', '--suffix' => 'Append the component title to the class name.', '--force' => 'Force overwrite existing file.', ]; /** * Actually execute a command. */ public function run(array $params) { $this->params = $params; $options = []; if ($this->getOption('namespace')) { $options['namespace'] = $this->getOption('namespace'); } if ($this->getOption('suffix')) { $options['suffix'] = null; } if ($this->getOption('force')) { $options['force'] = null; } $controllerOpts = []; if ($this->getOption('bare')) { $controllerOpts['bare'] = null; } elseif ($this->getOption('restful')) { $controllerOpts['restful'] = $this->getOption('restful'); } $modelOpts = [ 'table' => $this->getOption('table'), 'dbgroup' => $this->getOption('dbgroup'), 'return' => $this->getOption('return'), ]; $class = $params[0] ?? CLI::getSegment(2); // Call those commands! $this->call('make:controller', array_merge([$class], $controllerOpts, $options)); $this->call('make:model', array_merge([$class], $modelOpts, $options)); $this->call('make:migration', array_merge([$class], $options)); $this->call('make:seeder', array_merge([$class], $options)); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/CellGenerator.php
system/Commands/Generators/CellGenerator.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Generators; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\GeneratorTrait; use Config\Generators; /** * Generates a skeleton Cell and its view. */ class CellGenerator extends BaseCommand { use GeneratorTrait; /** * The Command's Group * * @var string */ protected $group = 'Generators'; /** * The Command's Name * * @var string */ protected $name = 'make:cell'; /** * The Command's Description * * @var string */ protected $description = 'Generates a new Controlled Cell file and its view.'; /** * The Command's Usage * * @var string */ protected $usage = 'make:cell <name> [options]'; /** * The Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'name' => 'The Controlled Cell class name.', ]; /** * The Command's Options * * @var array<string, string> */ protected $options = [ '--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".', '--force' => 'Force overwrite existing file.', ]; /** * Actually execute a command. */ public function run(array $params) { $this->component = 'Cell'; $this->directory = 'Cells'; $params = array_merge($params, ['suffix' => null]); $this->templatePath = config(Generators::class)->views[$this->name]['class']; $this->template = 'cell.tpl.php'; $this->classNameLang = 'CLI.generator.className.cell'; $this->generateClass($params); $this->templatePath = config(Generators::class)->views[$this->name]['view']; $this->template = 'cell_view.tpl.php'; $this->classNameLang = 'CLI.generator.viewName.cell'; $className = $this->qualifyClassName(); $viewName = decamelize(class_basename($className)); $viewName = preg_replace( '/([a-z][a-z0-9_\/\\\\]+)(_cell)$/i', '$1', $viewName, ) ?? $viewName; $namespace = substr($className, 0, strrpos($className, '\\') + 1); $this->generateView($namespace . $viewName, $params); return 0; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/CommandGenerator.php
system/Commands/Generators/CommandGenerator.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Generators; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\CLI\GeneratorTrait; /** * Generates a skeleton command file. */ class CommandGenerator extends BaseCommand { use GeneratorTrait; /** * The Command's Group * * @var string */ protected $group = 'Generators'; /** * The Command's Name * * @var string */ protected $name = 'make:command'; /** * The Command's Description * * @var string */ protected $description = 'Generates a new spark command.'; /** * The Command's Usage * * @var string */ protected $usage = 'make:command <name> [options]'; /** * The Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'name' => 'The command class name.', ]; /** * The Command's Options * * @var array<string, string> */ protected $options = [ '--command' => 'The command name. Default: "command:name"', '--type' => 'The command type. Options [basic, generator]. Default: "basic".', '--group' => 'The command group. Default: [basic -> "App", generator -> "Generators"].', '--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".', '--suffix' => 'Append the component title to the class name (e.g. User => UserCommand).', '--force' => 'Force overwrite existing file.', ]; /** * Actually execute a command. */ public function run(array $params) { $this->component = 'Command'; $this->directory = 'Commands'; $this->template = 'command.tpl.php'; $this->classNameLang = 'CLI.generator.className.command'; $this->generateClass($params); } /** * Prepare options and do the necessary replacements. */ protected function prepare(string $class): string { $command = $this->getOption('command'); $group = $this->getOption('group'); $type = $this->getOption('type'); $command = is_string($command) ? $command : 'command:name'; $type = is_string($type) ? $type : 'basic'; if (! in_array($type, ['basic', 'generator'], true)) { // @codeCoverageIgnoreStart $type = CLI::prompt(lang('CLI.generator.commandType'), ['basic', 'generator'], 'required'); CLI::newLine(); // @codeCoverageIgnoreEnd } if (! is_string($group)) { $group = $type === 'generator' ? 'Generators' : 'App'; } return $this->parseTemplate( $class, ['{group}', '{command}'], [$group, $command], ['type' => $type], ); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/TestGenerator.php
system/Commands/Generators/TestGenerator.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Generators; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\CLI\GeneratorTrait; /** * Generates a skeleton command file. */ class TestGenerator extends BaseCommand { use GeneratorTrait; /** * The Command's Group * * @var string */ protected $group = 'Generators'; /** * The Command's Name * * @var string */ protected $name = 'make:test'; /** * The Command's Description * * @var string */ protected $description = 'Generates a new test file.'; /** * The Command's Usage * * @var string */ protected $usage = 'make:test <name> [options]'; /** * The Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'name' => 'The test class name.', ]; /** * The Command's Options * * @var array<string, string> */ protected $options = [ '--namespace' => 'Set root namespace. Default: "Tests".', '--force' => 'Force overwrite existing file.', ]; /** * Actually execute a command. */ public function run(array $params) { // Ensure tests are always suffixed with 'Test' $params['suffix'] = null; $this->component = 'Test'; $this->template = 'test.tpl.php'; $this->classNameLang = 'CLI.generator.className.test'; $autoload = service('autoloader'); $autoload->addNamespace('CodeIgniter', TESTPATH . 'system'); $autoload->addNamespace('Tests', ROOTPATH . 'tests'); $this->generateClass($params); } /** * Gets the namespace from input or the default namespace. */ protected function getNamespace(): string { if ($this->namespace !== null) { return $this->namespace; } if ($this->getOption('namespace') !== null) { return trim( str_replace( '/', '\\', $this->getOption('namespace'), ), '\\', ); } $class = $this->normalizeInputClassName(); $classPaths = explode('\\', $class); $namespaces = service('autoloader')->getNamespace(); while ($classPaths !== []) { array_pop($classPaths); $namespace = implode('\\', $classPaths); foreach (array_keys($namespaces) as $prefix) { if ($prefix === $namespace) { // The input classname is FQCN, and use the namespace. return $namespace; } } } return 'Tests'; } /** * Builds the test file path from the class name. * * @param string $class namespaced classname. */ protected function buildPath(string $class): string { $namespace = $this->getNamespace(); $base = $this->searchTestFilePath($namespace); if ($base === null) { CLI::error( lang('CLI.namespaceNotDefined', [$namespace]), 'light_gray', 'red', ); CLI::newLine(); return ''; } $realpath = realpath($base); $base = ($realpath !== false) ? $realpath : $base; $file = $base . DIRECTORY_SEPARATOR . str_replace( '\\', DIRECTORY_SEPARATOR, trim(str_replace($namespace . '\\', '', $class), '\\'), ) . '.php'; return implode( DIRECTORY_SEPARATOR, array_slice( explode(DIRECTORY_SEPARATOR, $file), 0, -1, ), ) . DIRECTORY_SEPARATOR . $this->basename($file); } /** * Returns test file path for the namespace. */ private function searchTestFilePath(string $testNamespace): ?string { /** @var list<non-empty-string> $testPaths */ $testPaths = service('autoloader')->getNamespace($testNamespace); foreach ($testPaths as $candidate) { if (str_contains($candidate, DIRECTORY_SEPARATOR . 'tests' . DIRECTORY_SEPARATOR)) { return $candidate; } } return null; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/FilterGenerator.php
system/Commands/Generators/FilterGenerator.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Generators; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\GeneratorTrait; /** * Generates a skeleton Filter file. */ class FilterGenerator extends BaseCommand { use GeneratorTrait; /** * The Command's Group * * @var string */ protected $group = 'Generators'; /** * The Command's Name * * @var string */ protected $name = 'make:filter'; /** * The Command's Description * * @var string */ protected $description = 'Generates a new filter file.'; /** * The Command's Usage * * @var string */ protected $usage = 'make:filter <name> [options]'; /** * The Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'name' => 'The filter class name.', ]; /** * The Command's Options * * @var array<string, string> */ protected $options = [ '--namespace' => 'Set root namespace. Default: "APP_NAMESPACE".', '--suffix' => 'Append the component title to the class name (e.g. User => UserFilter).', '--force' => 'Force overwrite existing file.', ]; /** * Actually execute a command. */ public function run(array $params) { $this->component = 'Filter'; $this->directory = 'Filters'; $this->template = 'filter.tpl.php'; $this->classNameLang = 'CLI.generator.className.filter'; $this->generateClass($params); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/Views/config.tpl.php
system/Commands/Generators/Views/config.tpl.php
<@php namespace {namespace}; use CodeIgniter\Config\BaseConfig; class {class} extends BaseConfig { // }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/Views/cell_view.tpl.php
system/Commands/Generators/Views/cell_view.tpl.php
<div> <!-- Your HTML here --> </div>
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/Views/filter.tpl.php
system/Commands/Generators/Views/filter.tpl.php
<@php namespace {namespace}; use CodeIgniter\Filters\FilterInterface; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; class {class} implements FilterInterface { /** * Do whatever processing this filter needs to do. * By default it should not return anything during * normal execution. However, when an abnormal state * is found, it should return an instance of * CodeIgniter\HTTP\Response. If it does, script * execution will end and that Response will be * sent back to the client, allowing for error pages, * redirects, etc. * * @param RequestInterface $request * @param array|null $arguments * * @return RequestInterface|ResponseInterface|string|void */ public function before(RequestInterface $request, $arguments = null) { // } /** * Allows After filters to inspect and modify the response * object as needed. This method does not allow any way * to stop execution of other after filters, short of * throwing an Exception or Error. * * @param RequestInterface $request * @param ResponseInterface $response * @param array|null $arguments * * @return ResponseInterface|void */ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { // } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/Views/entity.tpl.php
system/Commands/Generators/Views/entity.tpl.php
<@php namespace {namespace}; use CodeIgniter\Entity\Entity; class {class} extends Entity { protected $datamap = []; protected $dates = ['created_at', 'updated_at', 'deleted_at']; protected $casts = []; }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/Views/seeder.tpl.php
system/Commands/Generators/Views/seeder.tpl.php
<@php namespace {namespace}; use CodeIgniter\Database\Seeder; class {class} extends Seeder { public function run() { // } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/Views/test.tpl.php
system/Commands/Generators/Views/test.tpl.php
<@php namespace {namespace}; use CodeIgniter\Test\CIUnitTestCase; class {class} extends CIUnitTestCase { protected function setUp(): void { parent::setUp(); } public function testExample(): void { // } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/Views/migration.tpl.php
system/Commands/Generators/Views/migration.tpl.php
<@php namespace {namespace}; use CodeIgniter\Database\Migration; class {class} extends Migration { <?php if ($session): ?> protected $DBGroup = '<?= $DBGroup ?>'; public function up() { $this->forge->addField([ 'id' => ['type' => 'VARCHAR', 'constraint' => 128, 'null' => false], <?php if ($DBDriver === 'MySQLi'): ?> 'ip_address' => ['type' => 'VARCHAR', 'constraint' => 45, 'null' => false], 'timestamp timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL', 'data' => ['type' => 'BLOB', 'null' => false], <?php elseif ($DBDriver === 'Postgre'): ?> 'ip_address inet NOT NULL', 'timestamp timestamptz DEFAULT CURRENT_TIMESTAMP NOT NULL', "data bytea DEFAULT '' NOT NULL", <?php endif; ?> ]); <?php if ($matchIP) : ?> $this->forge->addKey(['id', 'ip_address'], true); <?php else: ?> $this->forge->addKey('id', true); <?php endif ?> $this->forge->addKey('timestamp'); $this->forge->createTable('<?= $table ?>', true); } public function down() { $this->forge->dropTable('<?= $table ?>', true); } <?php else: ?> public function up() { // } public function down() { // } <?php endif ?> }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/Views/cell.tpl.php
system/Commands/Generators/Views/cell.tpl.php
<@php namespace {namespace}; use CodeIgniter\View\Cells\Cell; class {class} extends Cell { // }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/Views/command.tpl.php
system/Commands/Generators/Views/command.tpl.php
<@php namespace {namespace}; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; <?php if ($type === 'generator'): ?> use CodeIgniter\CLI\GeneratorTrait; <?php endif ?> class {class} extends BaseCommand { <?php if ($type === 'generator'): ?> use GeneratorTrait; <?php endif ?> /** * The Command's Group * * @var string */ protected $group = '{group}'; /** * The Command's Name * * @var string */ protected $name = '{command}'; /** * The Command's Description * * @var string */ protected $description = ''; /** * The Command's Usage * * @var string */ protected $usage = '{command} [arguments] [options]'; /** * The Command's Arguments * * @var array */ protected $arguments = []; /** * The Command's Options * * @var array */ protected $options = []; /** * Actually execute a command. * * @param array $params */ public function run(array $params) { <?php if ($type === 'generator'): ?> $this->component = 'Command'; $this->directory = 'Commands'; $this->template = 'command.tpl.php'; $this->execute($params); <?php else: ?> // <?php endif ?> } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/Views/model.tpl.php
system/Commands/Generators/Views/model.tpl.php
<@php namespace {namespace}; use CodeIgniter\Model; class {class} extends Model { <?php if (is_string($dbGroup)): ?> protected $DBGroup = '{dbGroup}'; <?php endif; ?> protected $table = '{table}'; protected $primaryKey = 'id'; protected $useAutoIncrement = true; protected $returnType = {return}; protected $useSoftDeletes = false; protected $protectFields = true; protected $allowedFields = []; protected bool $allowEmptyInserts = false; protected bool $updateOnlyChanged = true; protected array $casts = []; protected array $castHandlers = []; // Dates protected $useTimestamps = false; protected $dateFormat = 'datetime'; protected $createdField = 'created_at'; protected $updatedField = 'updated_at'; protected $deletedField = 'deleted_at'; // Validation protected $validationRules = []; protected $validationMessages = []; protected $skipValidation = false; protected $cleanValidationRules = true; // Callbacks protected $allowCallbacks = true; protected $beforeInsert = []; protected $afterInsert = []; protected $beforeUpdate = []; protected $afterUpdate = []; protected $beforeFind = []; protected $afterFind = []; protected $beforeDelete = []; protected $afterDelete = []; }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/Views/validation.tpl.php
system/Commands/Generators/Views/validation.tpl.php
<@php namespace {namespace}; class {class} { // public function custom_rule(): bool // { // return true; // } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Generators/Views/controller.tpl.php
system/Commands/Generators/Views/controller.tpl.php
<@php namespace {namespace}; use {useStatement}; use CodeIgniter\HTTP\ResponseInterface; class {class} extends {extends} { <?php if ($type === 'controller'): ?> /** * Return an array of resource objects, themselves in array format. * * @return ResponseInterface */ public function index() { // } /** * Return the properties of a resource object. * * @param int|string|null $id * * @return ResponseInterface */ public function show($id = null) { // } /** * Return a new resource object, with default properties. * * @return ResponseInterface */ public function new() { // } /** * Create a new resource object, from "posted" parameters. * * @return ResponseInterface */ public function create() { // } /** * Return the editable properties of a resource object. * * @param int|string|null $id * * @return ResponseInterface */ public function edit($id = null) { // } /** * Add or update a model resource, from "posted" properties. * * @param int|string|null $id * * @return ResponseInterface */ public function update($id = null) { // } /** * Delete the designated resource object from the model. * * @param int|string|null $id * * @return ResponseInterface */ public function delete($id = null) { // } <?php elseif ($type === 'presenter'): ?> /** * Present a view of resource objects. * * @return ResponseInterface */ public function index() { // } /** * Present a view to present a specific resource object. * * @param int|string|null $id * * @return ResponseInterface */ public function show($id = null) { // } /** * Present a view to present a new single resource object. * * @return ResponseInterface */ public function new() { // } /** * Process the creation/insertion of a new resource object. * This should be a POST. * * @return ResponseInterface */ public function create() { // } /** * Present a view to edit the properties of a specific resource object. * * @param int|string|null $id * * @return ResponseInterface */ public function edit($id = null) { // } /** * Process the updating, full or partial, of a specific resource object. * This should be a POST. * * @param int|string|null $id * * @return ResponseInterface */ public function update($id = null) { // } /** * Present a view to confirm the deletion of a specific resource object. * * @param int|string|null $id * * @return ResponseInterface */ public function remove($id = null) { // } /** * Process the deletion of a specific resource object. * * @param int|string|null $id * * @return ResponseInterface */ public function delete($id = null) { // } <?php else: ?> public function index() { // } <?php endif ?> }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Translation/LocalizationFinder.php
system/Commands/Translation/LocalizationFinder.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Translation; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Helpers\Array\ArrayHelper; use Config\App; use Locale; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use SplFileInfo; /** * @see \CodeIgniter\Commands\Translation\LocalizationFinderTest */ class LocalizationFinder extends BaseCommand { protected $group = 'Translation'; protected $name = 'lang:find'; protected $description = 'Find and save available phrases to translate.'; protected $usage = 'lang:find [options]'; protected $arguments = []; protected $options = [ '--locale' => 'Specify locale (en, ru, etc.) to save files.', '--dir' => 'Directory to search for translations relative to APPPATH.', '--show-new' => 'Show only new translations in table. Does not write to files.', '--verbose' => 'Output detailed information.', ]; /** * Flag for output detailed information */ private bool $verbose = false; /** * Flag for showing only translations, without saving */ private bool $showNew = false; private string $languagePath; public function run(array $params) { $this->verbose = array_key_exists('verbose', $params); $this->showNew = array_key_exists('show-new', $params); $optionLocale = $params['locale'] ?? null; $optionDir = $params['dir'] ?? null; $currentLocale = Locale::getDefault(); $currentDir = APPPATH; $this->languagePath = $currentDir . 'Language'; if (ENVIRONMENT === 'testing') { $currentDir = SUPPORTPATH . 'Services' . DIRECTORY_SEPARATOR; $this->languagePath = SUPPORTPATH . 'Language'; } if (is_string($optionLocale)) { if (! in_array($optionLocale, config(App::class)->supportedLocales, true)) { CLI::error( 'Error: "' . $optionLocale . '" is not supported. Supported locales: ' . implode(', ', config(App::class)->supportedLocales), ); return EXIT_USER_INPUT; } $currentLocale = $optionLocale; } if (is_string($optionDir)) { $tempCurrentDir = realpath($currentDir . $optionDir); if ($tempCurrentDir === false) { CLI::error('Error: Directory must be located in "' . $currentDir . '"'); return EXIT_USER_INPUT; } if ($this->isSubDirectory($tempCurrentDir, $this->languagePath)) { CLI::error('Error: Directory "' . $this->languagePath . '" restricted to scan.'); return EXIT_USER_INPUT; } $currentDir = $tempCurrentDir; } $this->process($currentDir, $currentLocale); CLI::write('All operations done!'); return EXIT_SUCCESS; } private function process(string $currentDir, string $currentLocale): void { $tableRows = []; $countNewKeys = 0; $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($currentDir)); $files = iterator_to_array($iterator, true); ksort($files); [ 'foundLanguageKeys' => $foundLanguageKeys, 'badLanguageKeys' => $badLanguageKeys, 'countFiles' => $countFiles, ] = $this->findLanguageKeysInFiles($files); ksort($foundLanguageKeys); $languageDiff = []; $languageFoundGroups = array_unique(array_keys($foundLanguageKeys)); foreach ($languageFoundGroups as $langFileName) { $languageStoredKeys = []; $languageFilePath = $this->languagePath . DIRECTORY_SEPARATOR . $currentLocale . DIRECTORY_SEPARATOR . $langFileName . '.php'; if (is_file($languageFilePath)) { // Load old localization $languageStoredKeys = require $languageFilePath; } $languageDiff = ArrayHelper::recursiveDiff($foundLanguageKeys[$langFileName], $languageStoredKeys); $countNewKeys += ArrayHelper::recursiveCount($languageDiff); if ($this->showNew) { $tableRows = array_merge($this->arrayToTableRows($langFileName, $languageDiff), $tableRows); } else { $newLanguageKeys = array_replace_recursive($foundLanguageKeys[$langFileName], $languageStoredKeys); if ($languageDiff !== []) { if (file_put_contents($languageFilePath, $this->templateFile($newLanguageKeys)) === false) { $this->writeIsVerbose('Lang file ' . $langFileName . ' (error write).', 'red'); } else { $this->writeIsVerbose('Lang file "' . $langFileName . '" successful updated!', 'green'); } } } } if ($this->showNew && $tableRows !== []) { sort($tableRows); CLI::table($tableRows, ['File', 'Key']); } if (! $this->showNew && $countNewKeys > 0) { CLI::write('Note: You need to run your linting tool to fix coding standards issues.', 'white', 'red'); } $this->writeIsVerbose('Files found: ' . $countFiles); $this->writeIsVerbose('New translates found: ' . $countNewKeys); $this->writeIsVerbose('Bad translates found: ' . count($badLanguageKeys)); if ($this->verbose && $badLanguageKeys !== []) { $tableBadRows = []; foreach ($badLanguageKeys as $value) { $tableBadRows[] = [$value[1], $value[0]]; } ArrayHelper::sortValuesByNatural($tableBadRows, 0); CLI::table($tableBadRows, ['Bad Key', 'Filepath']); } } /** * @param SplFileInfo|string $file * * @return array<string, array> */ private function findTranslationsInFile($file): array { $foundLanguageKeys = []; $badLanguageKeys = []; if (is_string($file) && is_file($file)) { $file = new SplFileInfo($file); } $fileContent = file_get_contents($file->getRealPath()); preg_match_all('/lang\(\'([._a-z0-9\-]+)\'\)/ui', $fileContent, $matches); if ($matches[1] === []) { return compact('foundLanguageKeys', 'badLanguageKeys'); } foreach ($matches[1] as $phraseKey) { $phraseKeys = explode('.', $phraseKey); // Language key not have Filename or Lang key if (count($phraseKeys) < 2) { $badLanguageKeys[] = [mb_substr($file->getRealPath(), mb_strlen(ROOTPATH)), $phraseKey]; continue; } $languageFileName = array_shift($phraseKeys); $isEmptyNestedArray = ($languageFileName !== '' && $phraseKeys[0] === '') || ($languageFileName === '' && $phraseKeys[0] !== '') || ($languageFileName === '' && $phraseKeys[0] === ''); if ($isEmptyNestedArray) { $badLanguageKeys[] = [mb_substr($file->getRealPath(), mb_strlen(ROOTPATH)), $phraseKey]; continue; } if (count($phraseKeys) === 1) { $foundLanguageKeys[$languageFileName][$phraseKeys[0]] = $phraseKey; } else { $childKeys = $this->buildMultiArray($phraseKeys, $phraseKey); $foundLanguageKeys[$languageFileName] = array_replace_recursive($foundLanguageKeys[$languageFileName] ?? [], $childKeys); } } return compact('foundLanguageKeys', 'badLanguageKeys'); } private function isIgnoredFile(SplFileInfo $file): bool { if ($file->isDir() || $this->isSubDirectory($file->getRealPath(), $this->languagePath)) { return true; } return $file->getExtension() !== 'php'; } private function templateFile(array $language = []): string { if ($language !== []) { $languageArrayString = var_export($language, true); $code = <<<PHP <?php return {$languageArrayString}; PHP; return $this->replaceArraySyntax($code); } return <<<'PHP' <?php return []; PHP; } private function replaceArraySyntax(string $code): string { $tokens = token_get_all($code); $newTokens = $tokens; foreach ($tokens as $i => $token) { if (is_array($token)) { [$tokenId, $tokenValue] = $token; // Replace "array (" if ( $tokenId === T_ARRAY && $tokens[$i + 1][0] === T_WHITESPACE && $tokens[$i + 2] === '(' ) { $newTokens[$i][1] = '['; $newTokens[$i + 1][1] = ''; $newTokens[$i + 2] = ''; } // Replace indent if ($tokenId === T_WHITESPACE && preg_match('/\n([ ]+)/u', $tokenValue, $matches)) { $newTokens[$i][1] = "\n{$matches[1]}{$matches[1]}"; } } // Replace ")" elseif ($token === ')') { $newTokens[$i] = ']'; } } $output = ''; foreach ($newTokens as $token) { $output .= $token[1] ?? $token; } return $output; } /** * Create multidimensional array from another keys */ private function buildMultiArray(array $fromKeys, string $lastArrayValue = ''): array { $newArray = []; $lastIndex = array_pop($fromKeys); $current = &$newArray; foreach ($fromKeys as $value) { $current[$value] = []; $current = &$current[$value]; } $current[$lastIndex] = $lastArrayValue; return $newArray; } /** * Convert multi arrays to specific CLI table rows (flat array) */ private function arrayToTableRows(string $langFileName, array $array): array { $rows = []; foreach ($array as $value) { if (is_array($value)) { $rows = array_merge($rows, $this->arrayToTableRows($langFileName, $value)); continue; } if (is_string($value)) { $rows[] = [$langFileName, $value]; } } return $rows; } /** * Show details in the console if the flag is set */ private function writeIsVerbose(string $text = '', ?string $foreground = null, ?string $background = null): void { if ($this->verbose) { CLI::write($text, $foreground, $background); } } private function isSubDirectory(string $directory, string $rootDirectory): bool { return 0 === strncmp($directory, $rootDirectory, strlen($directory)); } /** * @param list<SplFileInfo> $files * * @return array{'foundLanguageKeys': array<string, array<string, string>>, 'badLanguageKeys': array<int, array<int, string>>, 'countFiles': int} */ private function findLanguageKeysInFiles(array $files): array { $foundLanguageKeys = []; $badLanguageKeys = []; $countFiles = 0; foreach ($files as $file) { if ($this->isIgnoredFile($file)) { continue; } $this->writeIsVerbose('File found: ' . mb_substr($file->getRealPath(), mb_strlen(APPPATH))); $countFiles++; $findInFile = $this->findTranslationsInFile($file); $foundLanguageKeys = array_replace_recursive($findInFile['foundLanguageKeys'], $foundLanguageKeys); $badLanguageKeys = array_merge($findInFile['badLanguageKeys'], $badLanguageKeys); } return compact('foundLanguageKeys', 'badLanguageKeys', 'countFiles'); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Translation/LocalizationSync.php
system/Commands/Translation/LocalizationSync.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Translation; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Exceptions\LogicException; use Config\App; use ErrorException; use FilesystemIterator; use Locale; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use SplFileInfo; /** * @see \CodeIgniter\Commands\Translation\LocalizationSyncTest */ class LocalizationSync extends BaseCommand { protected $group = 'Translation'; protected $name = 'lang:sync'; protected $description = 'Synchronize translation files from one language to another.'; protected $usage = 'lang:sync [options]'; protected $arguments = []; protected $options = [ '--locale' => 'The original locale (en, ru, etc.).', '--target' => 'Target locale (en, ru, etc.).', ]; private string $languagePath; public function run(array $params) { $optionTargetLocale = ''; $optionLocale = $params['locale'] ?? Locale::getDefault(); $this->languagePath = APPPATH . 'Language'; if (isset($params['target']) && $params['target'] !== '') { $optionTargetLocale = $params['target']; } if (! in_array($optionLocale, config(App::class)->supportedLocales, true)) { CLI::error( 'Error: "' . $optionLocale . '" is not supported. Supported locales: ' . implode(', ', config(App::class)->supportedLocales), ); return EXIT_USER_INPUT; } if ($optionTargetLocale === '') { CLI::error( 'Error: "--target" is not configured. Supported locales: ' . implode(', ', config(App::class)->supportedLocales), ); return EXIT_USER_INPUT; } if (! in_array($optionTargetLocale, config(App::class)->supportedLocales, true)) { CLI::error( 'Error: "' . $optionTargetLocale . '" is not supported. Supported locales: ' . implode(', ', config(App::class)->supportedLocales), ); return EXIT_USER_INPUT; } if ($optionTargetLocale === $optionLocale) { CLI::error( 'Error: You cannot have the same values for "--target" and "--locale".', ); return EXIT_USER_INPUT; } if (ENVIRONMENT === 'testing') { $this->languagePath = SUPPORTPATH . 'Language'; } if ($this->process($optionLocale, $optionTargetLocale) === EXIT_ERROR) { return EXIT_ERROR; } CLI::write('All operations done!'); return EXIT_SUCCESS; } private function process(string $originalLocale, string $targetLocale): int { $originalLocaleDir = $this->languagePath . DIRECTORY_SEPARATOR . $originalLocale; $targetLocaleDir = $this->languagePath . DIRECTORY_SEPARATOR . $targetLocale; if (! is_dir($originalLocaleDir)) { CLI::error( 'Error: The "' . clean_path($originalLocaleDir) . '" directory was not found.', ); return EXIT_ERROR; } // Unifying the error - mkdir() may cause an exception. try { if (! is_dir($targetLocaleDir) && ! mkdir($targetLocaleDir, 0775)) { throw new ErrorException(); } } catch (ErrorException $e) { CLI::error( 'Error: The target directory "' . clean_path($targetLocaleDir) . '" cannot be accessed.', ); return EXIT_ERROR; } $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $originalLocaleDir, FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS, ), ); /** * @var array<non-empty-string, SplFileInfo> $files */ $files = iterator_to_array($iterator, true); ksort($files); foreach ($files as $originalLanguageFile) { if ($originalLanguageFile->getExtension() !== 'php') { continue; } $targetLanguageFile = $targetLocaleDir . DIRECTORY_SEPARATOR . $originalLanguageFile->getFilename(); $targetLanguageKeys = []; $originalLanguageKeys = include $originalLanguageFile; if (is_file($targetLanguageFile)) { $targetLanguageKeys = include $targetLanguageFile; } $targetLanguageKeys = $this->mergeLanguageKeys($originalLanguageKeys, $targetLanguageKeys, $originalLanguageFile->getBasename('.php')); $content = "<?php\n\nreturn " . var_export($targetLanguageKeys, true) . ";\n"; file_put_contents($targetLanguageFile, $content); } return EXIT_SUCCESS; } /** * @param array<string, array<string,mixed>|string|null> $originalLanguageKeys * @param array<string, array<string,mixed>|string|null> $targetLanguageKeys * * @return array<string, array<string,mixed>|string|null> */ private function mergeLanguageKeys(array $originalLanguageKeys, array $targetLanguageKeys, string $prefix = ''): array { $mergedLanguageKeys = []; foreach ($originalLanguageKeys as $key => $value) { $placeholderValue = $prefix !== '' ? $prefix . '.' . $key : $key; if (is_string($value)) { // Keep the old value // TODO: The value type may not match the original one if (array_key_exists($key, $targetLanguageKeys)) { $mergedLanguageKeys[$key] = $targetLanguageKeys[$key]; continue; } // Set new key with placeholder $mergedLanguageKeys[$key] = $placeholderValue; } elseif (is_array($value)) { if (! array_key_exists($key, $targetLanguageKeys)) { $mergedLanguageKeys[$key] = $this->mergeLanguageKeys($value, [], $placeholderValue); continue; } $mergedLanguageKeys[$key] = $this->mergeLanguageKeys($value, $targetLanguageKeys[$key], $placeholderValue); } else { throw new LogicException('Value for the key "' . $placeholderValue . '" is of the wrong type. Only "array" or "string" is allowed.'); } } return $mergedLanguageKeys; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Encryption/GenerateKey.php
system/Commands/Encryption/GenerateKey.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Encryption; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Config\DotEnv; use CodeIgniter\Encryption\Encryption; /** * Generates a new encryption key. */ class GenerateKey extends BaseCommand { /** * The Command's group. * * @var string */ protected $group = 'Encryption'; /** * The Command's name. * * @var string */ protected $name = 'key:generate'; /** * The Command's usage. * * @var string */ protected $usage = 'key:generate [options]'; /** * The Command's short description. * * @var string */ protected $description = 'Generates a new encryption key and writes it in an `.env` file.'; /** * The command's options * * @var array<string, string> */ protected $options = [ '--force' => 'Force overwrite existing key in `.env` file.', '--length' => 'The length of the random string that should be returned in bytes. Defaults to 32.', '--prefix' => 'Prefix to prepend to encoded key (either hex2bin or base64). Defaults to hex2bin.', '--show' => 'Shows the generated key in the terminal instead of storing in the `.env` file.', ]; /** * Actually execute the command. */ public function run(array $params) { $prefix = $params['prefix'] ?? CLI::getOption('prefix'); if (in_array($prefix, [null, true], true)) { $prefix = 'hex2bin'; } elseif (! in_array($prefix, ['hex2bin', 'base64'], true)) { $prefix = CLI::prompt('Please provide a valid prefix to use.', ['hex2bin', 'base64'], 'required'); // @codeCoverageIgnore } $length = $params['length'] ?? CLI::getOption('length'); if (in_array($length, [null, true], true)) { $length = 32; } $encodedKey = $this->generateRandomKey($prefix, $length); if (array_key_exists('show', $params) || (bool) CLI::getOption('show')) { CLI::write($encodedKey, 'yellow'); CLI::newLine(); return; } if (! $this->setNewEncryptionKey($encodedKey, $params)) { CLI::write('Error in setting new encryption key to .env file.', 'light_gray', 'red'); CLI::newLine(); return; } // force DotEnv to reload the new env vars putenv('encryption.key'); unset($_ENV['encryption.key'], $_SERVER['encryption.key']); $dotenv = new DotEnv(ROOTPATH); $dotenv->load(); CLI::write('Application\'s new encryption key was successfully set.', 'green'); CLI::newLine(); } /** * Generates a key and encodes it. */ protected function generateRandomKey(string $prefix, int $length): string { $key = Encryption::createKey($length); if ($prefix === 'hex2bin') { return 'hex2bin:' . bin2hex($key); } return 'base64:' . base64_encode($key); } /** * Sets the new encryption key in your .env file. * * @param array<int|string, string|null> $params */ protected function setNewEncryptionKey(string $key, array $params): bool { $currentKey = env('encryption.key', ''); if ($currentKey !== '' && ! $this->confirmOverwrite($params)) { // Not yet testable since it requires keyboard input return false; // @codeCoverageIgnore } return $this->writeNewEncryptionKeyToFile($currentKey, $key); } /** * Checks whether to overwrite existing encryption key. * * @param array<int|string, string|null> $params */ protected function confirmOverwrite(array $params): bool { return (array_key_exists('force', $params) || CLI::getOption('force')) || CLI::prompt('Overwrite existing key?', ['n', 'y']) === 'y'; } /** * Writes the new encryption key to .env file. */ protected function writeNewEncryptionKeyToFile(string $oldKey, string $newKey): bool { $baseEnv = ROOTPATH . 'env'; $envFile = ROOTPATH . '.env'; if (! is_file($envFile)) { if (! is_file($baseEnv)) { CLI::write('Both default shipped `env` file and custom `.env` are missing.', 'yellow'); CLI::write('Here\'s your new key instead: ' . CLI::color($newKey, 'yellow')); CLI::newLine(); return false; } copy($baseEnv, $envFile); } $oldFileContents = (string) file_get_contents($envFile); $replacementKey = "\nencryption.key = {$newKey}"; if (! str_contains($oldFileContents, 'encryption.key')) { return file_put_contents($envFile, $replacementKey, FILE_APPEND) !== false; } $newFileContents = preg_replace($this->keyPattern($oldKey), $replacementKey, $oldFileContents); if ($newFileContents === $oldFileContents) { $newFileContents = preg_replace( '/^[#\s]*encryption.key[=\s]*(?:hex2bin\:[a-f0-9]{64}|base64\:(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?)$/m', $replacementKey, $oldFileContents, ); } return file_put_contents($envFile, $newFileContents) !== false; } /** * Get the regex of the current encryption key. */ protected function keyPattern(string $oldKey): string { $escaped = preg_quote($oldKey, '/'); if ($escaped !== '') { $escaped = "[{$escaped}]*"; } return "/^[#\\s]*encryption.key[=\\s]*{$escaped}$/m"; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Database/Migrate.php
system/Commands/Database/Migrate.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Database; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use Throwable; /** * Runs all new migrations. */ class Migrate extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'Database'; /** * The Command's name * * @var string */ protected $name = 'migrate'; /** * the Command's short description * * @var string */ protected $description = 'Locates and runs all new migrations against the database.'; /** * the Command's usage * * @var string */ protected $usage = 'migrate [options]'; /** * the Command's Options * * @var array<string, string> */ protected $options = [ '-n' => 'Set migration namespace', '-g' => 'Set database group', '--all' => 'Set for all namespaces, will ignore (-n) option', ]; /** * Ensures that all migrations have been run. */ public function run(array $params) { $runner = service('migrations'); $runner->clearCliMessages(); CLI::write(lang('Migrations.latest'), 'yellow'); $namespace = $params['n'] ?? CLI::getOption('n'); $group = $params['g'] ?? CLI::getOption('g'); try { if (array_key_exists('all', $params) || CLI::getOption('all')) { $runner->setNamespace(null); } elseif ($namespace) { $runner->setNamespace($namespace); } if (! $runner->latest($group)) { CLI::error(lang('Migrations.generalFault'), 'light_gray', 'red'); // @codeCoverageIgnore } $messages = $runner->getCliMessages(); foreach ($messages as $message) { CLI::write($message); } CLI::write(lang('Migrations.migrated'), 'green'); // @codeCoverageIgnoreStart } catch (Throwable $e) { $this->showError($e); // @codeCoverageIgnoreEnd } } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Database/Seed.php
system/Commands/Database/Seed.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Database; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Database\Seeder; use Config\Database; use Throwable; /** * Runs the specified Seeder file to populate the database * with some data. */ class Seed extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'Database'; /** * The Command's name * * @var string */ protected $name = 'db:seed'; /** * the Command's short description * * @var string */ protected $description = 'Runs the specified seeder to populate known data into the database.'; /** * the Command's usage * * @var string */ protected $usage = 'db:seed <seeder_name>'; /** * the Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'seeder_name' => 'The seeder name to run', ]; /** * Passes to Seeder to populate the database. */ public function run(array $params) { $seeder = new Seeder(new Database()); $seedName = array_shift($params); if (empty($seedName)) { $seedName = CLI::prompt(lang('Migrations.migSeeder'), null, 'required'); // @codeCoverageIgnore } try { $seeder->call($seedName); } catch (Throwable $e) { $this->showError($e); } } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Database/MigrateRefresh.php
system/Commands/Database/MigrateRefresh.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Database; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; /** * Does a rollback followed by a latest to refresh the current state * of the database. */ class MigrateRefresh extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'Database'; /** * The Command's name * * @var string */ protected $name = 'migrate:refresh'; /** * the Command's short description * * @var string */ protected $description = 'Does a rollback followed by a latest to refresh the current state of the database.'; /** * the Command's usage * * @var string */ protected $usage = 'migrate:refresh [options]'; /** * the Command's Options * * @var array<string, string> */ protected $options = [ '-n' => 'Set migration namespace', '-g' => 'Set database group', '--all' => 'Set latest for all namespace, will ignore (-n) option', '-f' => 'Force command - this option allows you to bypass the confirmation question when running this command in a production environment', ]; /** * Does a rollback followed by a latest to refresh the current state * of the database. */ public function run(array $params) { $params['b'] = 0; if (ENVIRONMENT === 'production') { // @codeCoverageIgnoreStart $force = array_key_exists('f', $params) || CLI::getOption('f'); if (! $force && CLI::prompt(lang('Migrations.refreshConfirm'), ['y', 'n']) === 'n') { return; } $params['f'] = null; // @codeCoverageIgnoreEnd } $this->call('migrate:rollback', $params); $this->call('migrate', $params); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Database/MigrateStatus.php
system/Commands/Database/MigrateStatus.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Database; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; /** * Displays a list of all migrations and whether they've been run or not. * * @see \CodeIgniter\Commands\Database\MigrateStatusTest */ class MigrateStatus extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'Database'; /** * The Command's name * * @var string */ protected $name = 'migrate:status'; /** * the Command's short description * * @var string */ protected $description = 'Displays a list of all migrations and whether they\'ve been run or not.'; /** * the Command's usage * * @var string */ protected $usage = 'migrate:status [options]'; /** * the Command's Options * * @var array<string, string> */ protected $options = [ '-g' => 'Set database group', ]; /** * Namespaces to ignore when looking for migrations. * * @var list<string> */ protected $ignoredNamespaces = [ 'CodeIgniter', 'Config', 'Kint', 'Laminas\ZendFrameworkBridge', 'Laminas\Escaper', 'Psr\Log', ]; /** * Displays a list of all migrations and whether they've been run or not. * * @param array<string, mixed> $params */ public function run(array $params) { $runner = service('migrations'); $paramGroup = $params['g'] ?? CLI::getOption('g'); // Get all namespaces $namespaces = service('autoloader')->getNamespace(); // Collection of migration status $status = []; foreach (array_keys($namespaces) as $namespace) { if (ENVIRONMENT !== 'testing') { // Make Tests\\Support discoverable for testing $this->ignoredNamespaces[] = 'Tests\Support'; // @codeCoverageIgnore } if (in_array($namespace, $this->ignoredNamespaces, true)) { continue; } if (APP_NAMESPACE !== 'App' && $namespace === 'App') { continue; // @codeCoverageIgnore } $migrations = $runner->findNamespaceMigrations($namespace); if (empty($migrations)) { continue; } $runner->setNamespace($namespace); $history = $runner->getHistory((string) $paramGroup); ksort($migrations); foreach ($migrations as $uid => $migration) { $migrations[$uid]->name = mb_substr($migration->name, (int) mb_strpos($migration->name, $uid . '_')); $date = '---'; $group = '---'; $batch = '---'; foreach ($history as $row) { // @codeCoverageIgnoreStart if ($runner->getObjectUid($row) !== $migration->uid) { continue; } $date = date('Y-m-d H:i:s', (int) $row->time); $group = $row->group; $batch = $row->batch; // @codeCoverageIgnoreEnd } $status[] = [ $namespace, $migration->version, $migration->name, $group, $date, $batch, ]; } } if ($status === []) { // @codeCoverageIgnoreStart CLI::error(lang('Migrations.noneFound'), 'light_gray', 'red'); CLI::newLine(); return; // @codeCoverageIgnoreEnd } $headers = [ CLI::color(lang('Migrations.namespace'), 'yellow'), CLI::color(lang('Migrations.version'), 'yellow'), CLI::color(lang('Migrations.filename'), 'yellow'), CLI::color(lang('Migrations.group'), 'yellow'), CLI::color(str_replace(': ', '', lang('Migrations.on')), 'yellow'), CLI::color(lang('Migrations.batch'), 'yellow'), ]; CLI::table($status, $headers); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Database/ShowTableInfo.php
system/Commands/Database/ShowTableInfo.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Database; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Database\BaseConnection; use CodeIgniter\Database\TableName; use CodeIgniter\Exceptions\InvalidArgumentException; use Config\Database; /** * Get table data if it exists in the database. * * @see \CodeIgniter\Commands\Database\ShowTableInfoTest */ class ShowTableInfo extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'Database'; /** * The Command's name * * @var string */ protected $name = 'db:table'; /** * the Command's short description * * @var string */ protected $description = 'Retrieves information on the selected table.'; /** * the Command's usage * * @var string */ protected $usage = <<<'EOL' db:table [<table_name>] [options] Examples: db:table --show db:table --metadata db:table my_table --metadata db:table my_table db:table my_table --limit-rows 5 --limit-field-value 10 --desc EOL; /** * The Command's arguments * * @var array<string, string> */ protected $arguments = [ 'table_name' => 'The table name to show info', ]; /** * The Command's options * * @var array<string, string> */ protected $options = [ '--show' => 'Lists the names of all database tables.', '--metadata' => 'Retrieves list containing field information.', '--desc' => 'Sorts the table rows in DESC order.', '--limit-rows' => 'Limits the number of rows. Default: 10.', '--limit-field-value' => 'Limits the length of field values. Default: 15.', '--dbgroup' => 'Database group to show.', ]; /** * @var list<list<int|string>> Table Data. */ private array $tbody; private ?BaseConnection $db = null; /** * @var bool Sort the table rows in DESC order or not. */ private bool $sortDesc = false; private string $DBPrefix; public function run(array $params) { $dbGroup = $params['dbgroup'] ?? CLI::getOption('dbgroup'); try { $this->db = Database::connect($dbGroup); } catch (InvalidArgumentException $e) { CLI::error($e->getMessage()); return EXIT_ERROR; } $this->DBPrefix = $this->db->getPrefix(); $this->showDBConfig(); $tables = $this->db->listTables(); if (array_key_exists('desc', $params)) { $this->sortDesc = true; } if ($tables === []) { CLI::error('Database has no tables!', 'light_gray', 'red'); CLI::newLine(); return EXIT_ERROR; } if (array_key_exists('show', $params)) { $this->showAllTables($tables); return EXIT_ERROR; } $tableName = $params[0] ?? null; $limitRows = (int) ($params['limit-rows'] ?? 10); $limitFieldValue = (int) ($params['limit-field-value'] ?? 15); while (! in_array($tableName, $tables, true)) { $tableNameNo = CLI::promptByKey( ['Here is the list of your database tables:', 'Which table do you want to see?'], $tables, 'required', ); CLI::newLine(); $tableName = $tables[$tableNameNo] ?? null; } if (array_key_exists('metadata', $params)) { $this->showFieldMetaData($tableName); return EXIT_SUCCESS; } $this->showDataOfTable($tableName, $limitRows, $limitFieldValue); return EXIT_SUCCESS; } private function showDBConfig(): void { $data = [[ 'hostname' => $this->db->hostname, 'database' => $this->db->getDatabase(), 'username' => $this->db->username, 'DBDriver' => $this->db->getPlatform(), 'DBPrefix' => $this->DBPrefix, 'port' => $this->db->port, ]]; CLI::table( $data, ['hostname', 'database', 'username', 'DBDriver', 'DBPrefix', 'port'], ); } private function removeDBPrefix(): void { $this->db->setPrefix(''); } private function restoreDBPrefix(): void { $this->db->setPrefix($this->DBPrefix); } /** * Show Data of Table * * @return void */ private function showDataOfTable(string $tableName, int $limitRows, int $limitFieldValue) { CLI::write("Data of Table \"{$tableName}\":", 'black', 'yellow'); CLI::newLine(); $this->removeDBPrefix(); $thead = $this->db->getFieldNames(TableName::fromActualName($this->db->DBPrefix, $tableName)); $this->restoreDBPrefix(); // If there is a field named `id`, sort by it. $sortField = null; if (in_array('id', $thead, true)) { $sortField = 'id'; } $this->tbody = $this->makeTableRows($tableName, $limitRows, $limitFieldValue, $sortField); CLI::table($this->tbody, $thead); } /** * Show All Tables * * @param list<string> $tables * * @return void */ private function showAllTables(array $tables) { CLI::write('The following is a list of the names of all database tables:', 'black', 'yellow'); CLI::newLine(); $thead = ['ID', 'Table Name', 'Num of Rows', 'Num of Fields']; $this->tbody = $this->makeTbodyForShowAllTables($tables); CLI::table($this->tbody, $thead); CLI::newLine(); } /** * Make body for table * * @param list<string> $tables * * @return list<list<int|string>> */ private function makeTbodyForShowAllTables(array $tables): array { $this->removeDBPrefix(); foreach ($tables as $id => $tableName) { $table = $this->db->protectIdentifiers($tableName); $db = $this->db->query("SELECT * FROM {$table}"); $this->tbody[] = [ $id + 1, $tableName, $db->getNumRows(), $db->getFieldCount(), ]; } $this->restoreDBPrefix(); if ($this->sortDesc) { krsort($this->tbody); } return $this->tbody; } /** * Make table rows * * @return list<list<int|string>> */ private function makeTableRows( string $tableName, int $limitRows, int $limitFieldValue, ?string $sortField = null, ): array { $this->tbody = []; $this->removeDBPrefix(); $builder = $this->db->table(TableName::fromActualName($this->db->DBPrefix, $tableName)); $builder->limit($limitRows); if ($sortField !== null) { $builder->orderBy($sortField, $this->sortDesc ? 'DESC' : 'ASC'); } $rows = $builder->get()->getResultArray(); $this->restoreDBPrefix(); foreach ($rows as $row) { $row = array_map( static fn ($item): string => mb_strlen((string) $item) > $limitFieldValue ? mb_substr((string) $item, 0, $limitFieldValue) . '...' : (string) $item, $row, ); $this->tbody[] = $row; } if ($sortField === null && $this->sortDesc) { krsort($this->tbody); } return $this->tbody; } private function showFieldMetaData(string $tableName): void { CLI::write("List of Metadata Information in Table \"{$tableName}\":", 'black', 'yellow'); CLI::newLine(); $thead = ['Field Name', 'Type', 'Max Length', 'Nullable', 'Default', 'Primary Key']; $this->removeDBPrefix(); $fields = $this->db->getFieldData($tableName); $this->restoreDBPrefix(); foreach ($fields as $row) { $this->tbody[] = [ $row->name, $row->type, $row->max_length, isset($row->nullable) ? $this->setYesOrNo($row->nullable) : 'n/a', $row->default, isset($row->primary_key) ? $this->setYesOrNo($row->primary_key) : 'n/a', ]; } if ($this->sortDesc) { krsort($this->tbody); } CLI::table($this->tbody, $thead); } /** * @param bool|int|string|null $fieldValue */ private function setYesOrNo($fieldValue): string { if ((bool) $fieldValue) { return CLI::color('Yes', 'green'); } return CLI::color('No', 'red'); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Database/MigrateRollback.php
system/Commands/Database/MigrateRollback.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Database; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Database\MigrationRunner; use Throwable; /** * Runs all of the migrations in reverse order, until they have * all been unapplied. */ class MigrateRollback extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'Database'; /** * The Command's name * * @var string */ protected $name = 'migrate:rollback'; /** * the Command's short description * * @var string */ protected $description = 'Runs the "down" method for all migrations in the last batch.'; /** * the Command's usage * * @var string */ protected $usage = 'migrate:rollback [options]'; /** * the Command's Options * * @var array<string, string> */ protected $options = [ '-b' => 'Specify a batch to roll back to; e.g. "3" to return to batch #3', '-f' => 'Force command - this option allows you to bypass the confirmation question when running this command in a production environment', ]; /** * Runs all of the migrations in reverse order, until they have * all been unapplied. */ public function run(array $params) { if (ENVIRONMENT === 'production') { // @codeCoverageIgnoreStart $force = array_key_exists('f', $params) || CLI::getOption('f'); if (! $force && CLI::prompt(lang('Migrations.rollBackConfirm'), ['y', 'n']) === 'n') { return null; } // @codeCoverageIgnoreEnd } /** @var MigrationRunner $runner */ $runner = service('migrations'); try { $batch = $params['b'] ?? CLI::getOption('b') ?? $runner->getLastBatch() - 1; if (is_string($batch)) { if (! ctype_digit($batch)) { CLI::error('Invalid batch number: ' . $batch, 'light_gray', 'red'); CLI::newLine(); return EXIT_ERROR; } $batch = (int) $batch; } CLI::write(lang('Migrations.rollingBack') . ' ' . $batch, 'yellow'); if (! $runner->regress($batch)) { CLI::error(lang('Migrations.generalFault'), 'light_gray', 'red'); // @codeCoverageIgnore } $messages = $runner->getCliMessages(); foreach ($messages as $message) { CLI::write($message); } CLI::write('Done rolling back migrations.', 'green'); // @codeCoverageIgnoreStart } catch (Throwable $e) { $this->showError($e); // @codeCoverageIgnoreEnd } return null; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Database/CreateDatabase.php
system/Commands/Database/CreateDatabase.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Database; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Config\Factories; use CodeIgniter\Database\SQLite3\Connection; use Config\Database; use Throwable; /** * Creates a new database. */ class CreateDatabase extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'Database'; /** * The Command's name * * @var string */ protected $name = 'db:create'; /** * the Command's short description * * @var string */ protected $description = 'Create a new database schema.'; /** * the Command's usage * * @var string */ protected $usage = 'db:create <db_name> [options]'; /** * The Command's arguments * * @var array<string, string> */ protected $arguments = [ 'db_name' => 'The database name to use', ]; /** * The Command's options * * @var array<string, string> */ protected $options = [ '--ext' => 'File extension of the database file for SQLite3. Can be `db` or `sqlite`. Defaults to `db`.', ]; /** * Creates a new database. */ public function run(array $params) { $name = array_shift($params); if (empty($name)) { $name = CLI::prompt('Database name', null, 'required'); // @codeCoverageIgnore } try { $config = config(Database::class); // Set to an empty database to prevent connection errors. $group = ENVIRONMENT === 'testing' ? 'tests' : $config->defaultGroup; $config->{$group}['database'] = ''; $db = Database::connect(); // Special SQLite3 handling if ($db instanceof Connection) { $ext = $params['ext'] ?? CLI::getOption('ext') ?? 'db'; if (! in_array($ext, ['db', 'sqlite'], true)) { $ext = CLI::prompt('Please choose a valid file extension', ['db', 'sqlite']); // @codeCoverageIgnore } if ($name !== ':memory:') { $name = str_replace(['.db', '.sqlite'], '', $name) . ".{$ext}"; } $config->{$group}['DBDriver'] = 'SQLite3'; $config->{$group}['database'] = $name; if ($name !== ':memory:') { $dbName = ! str_contains($name, DIRECTORY_SEPARATOR) ? WRITEPATH . $name : $name; if (is_file($dbName)) { CLI::error("Database \"{$dbName}\" already exists.", 'light_gray', 'red'); CLI::newLine(); return; } unset($dbName); } // Connect to new SQLite3 to create new database $db = Database::connect(null, false); $db->connect(); if (! is_file($db->getDatabase()) && $name !== ':memory:') { // @codeCoverageIgnoreStart CLI::error('Database creation failed.', 'light_gray', 'red'); CLI::newLine(); return; // @codeCoverageIgnoreEnd } } elseif (! Database::forge()->createDatabase($name)) { // @codeCoverageIgnoreStart CLI::error('Database creation failed.', 'light_gray', 'red'); CLI::newLine(); return; // @codeCoverageIgnoreEnd } CLI::write("Database \"{$name}\" successfully created.", 'green'); CLI::newLine(); } catch (Throwable $e) { $this->showError($e); } finally { Factories::reset('config'); Database::connect(null, false); } } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Cache/ClearCache.php
system/Commands/Cache/ClearCache.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Cache; use CodeIgniter\Cache\CacheFactory; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use Config\Cache; /** * Clears current cache. */ class ClearCache extends BaseCommand { /** * Command grouping. * * @var string */ protected $group = 'Cache'; /** * The Command's name * * @var string */ protected $name = 'cache:clear'; /** * the Command's short description * * @var string */ protected $description = 'Clears the current system caches.'; /** * the Command's usage * * @var string */ protected $usage = 'cache:clear [<driver>]'; /** * the Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'driver' => 'The cache driver to use', ]; /** * Clears the cache */ public function run(array $params) { $config = config(Cache::class); $handler = $params[0] ?? $config->handler; if (! array_key_exists($handler, $config->validHandlers)) { CLI::error($handler . ' is not a valid cache handler.'); return; } $config->handler = $handler; $cache = CacheFactory::getHandler($config); if (! $cache->clean()) { // @codeCoverageIgnoreStart CLI::error('Error while clearing the cache.'); return; // @codeCoverageIgnoreEnd } CLI::write(CLI::color('Cache cleared.', 'green')); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Cache/InfoCache.php
system/Commands/Cache/InfoCache.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Cache; use CodeIgniter\Cache\CacheFactory; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\I18n\Time; use Config\Cache; /** * Shows information on the cache. */ class InfoCache extends BaseCommand { /** * Command grouping. * * @var string */ protected $group = 'Cache'; /** * The Command's name * * @var string */ protected $name = 'cache:info'; /** * the Command's short description * * @var string */ protected $description = 'Shows file cache information in the current system.'; /** * the Command's usage * * @var string */ protected $usage = 'cache:info'; /** * Clears the cache */ public function run(array $params) { $config = config(Cache::class); helper('number'); if ($config->handler !== 'file') { CLI::error('This command only supports the file cache handler.'); return; } $cache = CacheFactory::getHandler($config); $caches = $cache->getCacheInfo(); $tbody = []; foreach ($caches as $key => $field) { $tbody[] = [ $key, clean_path($field['server_path']), number_to_size($field['size']), Time::createFromTimestamp($field['date']), ]; } $thead = [ CLI::color('Name', 'green'), CLI::color('Server Path', 'green'), CLI::color('Size', 'green'), CLI::color('Date', 'green'), ]; CLI::table($tbody, $thead); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Server/Serve.php
system/Commands/Server/Serve.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Server; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; /** * Launch the PHP development server * * Not testable, as it throws phpunit for a loop :-/ * * @codeCoverageIgnore */ class Serve extends BaseCommand { /** * Group * * @var string */ protected $group = 'CodeIgniter'; /** * Name * * @var string */ protected $name = 'serve'; /** * Description * * @var string */ protected $description = 'Launches the CodeIgniter PHP-Development Server.'; /** * Usage * * @var string */ protected $usage = 'serve'; /** * Arguments * * @var array<string, string> */ protected $arguments = []; /** * The current port offset. * * @var int */ protected $portOffset = 0; /** * The max number of ports to attempt to serve from * * @var int */ protected $tries = 10; /** * Options * * @var array<string, string> */ protected $options = [ '--php' => 'The PHP Binary [default: "PHP_BINARY"]', '--host' => 'The HTTP Host [default: "localhost"]', '--port' => 'The HTTP Host Port [default: "8080"]', ]; /** * Run the server */ public function run(array $params) { // Collect any user-supplied options and apply them. $php = escapeshellarg(CLI::getOption('php') ?? PHP_BINARY); $host = CLI::getOption('host') ?? 'localhost'; $port = (int) (CLI::getOption('port') ?? 8080) + $this->portOffset; // Get the party started. CLI::write('CodeIgniter development server started on http://' . $host . ':' . $port, 'green'); CLI::write('Press Control-C to stop.'); // Set the Front Controller path as Document Root. $docroot = escapeshellarg(FCPATH); // Mimic Apache's mod_rewrite functionality with user settings. $rewrite = escapeshellarg(SYSTEMPATH . 'rewrite.php'); // Call PHP's built-in webserver, making sure to set our // base path to the public folder, and to use the rewrite file // to ensure our environment is set and it simulates basic mod_rewrite. passthru($php . ' -S ' . $host . ':' . $port . ' -t ' . $docroot . ' ' . $rewrite, $status); if ($status !== EXIT_SUCCESS && $this->portOffset < $this->tries) { $this->portOffset++; $this->run($params); } } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Housekeeping/ClearDebugbar.php
system/Commands/Housekeeping/ClearDebugbar.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Housekeeping; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; /** * ClearDebugbar Command */ class ClearDebugbar extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'Housekeeping'; /** * The Command's name * * @var string */ protected $name = 'debugbar:clear'; /** * The Command's usage * * @var string */ protected $usage = 'debugbar:clear'; /** * The Command's short description. * * @var string */ protected $description = 'Clears all debugbar JSON files.'; /** * Actually runs the command. */ public function run(array $params) { helper('filesystem'); if (! delete_files(WRITEPATH . 'debugbar', false, true)) { // @codeCoverageIgnoreStart CLI::error('Error deleting the debugbar JSON files.'); CLI::newLine(); return; // @codeCoverageIgnoreEnd } CLI::write('Debugbar cleared.', 'green'); CLI::newLine(); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Housekeeping/ClearLogs.php
system/Commands/Housekeeping/ClearLogs.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Housekeeping; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; /** * ClearLogs command. */ class ClearLogs extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'Housekeeping'; /** * The Command's name * * @var string */ protected $name = 'logs:clear'; /** * The Command's short description * * @var string */ protected $description = 'Clears all log files.'; /** * The Command's usage * * @var string */ protected $usage = 'logs:clear [option'; /** * The Command's options * * @var array<string, string> */ protected $options = [ '--force' => 'Force delete of all logs files without prompting.', ]; /** * Actually execute a command. */ public function run(array $params) { $force = array_key_exists('force', $params) || CLI::getOption('force'); if (! $force && CLI::prompt('Are you sure you want to delete the logs?', ['n', 'y']) === 'n') { // @codeCoverageIgnoreStart CLI::error('Deleting logs aborted.', 'light_gray', 'red'); CLI::error('If you want, use the "-force" option to force delete all log files.', 'light_gray', 'red'); CLI::newLine(); return; // @codeCoverageIgnoreEnd } helper('filesystem'); if (! delete_files(WRITEPATH . 'logs', false, true)) { // @codeCoverageIgnoreStart CLI::error('Error in deleting the logs files.', 'light_gray', 'red'); CLI::newLine(); return; // @codeCoverageIgnoreEnd } CLI::write('Logs cleared.', 'green'); CLI::newLine(); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/Publish.php
system/Commands/Utilities/Publish.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Publisher\Publisher; /** * Discovers all Publisher classes from the "Publishers/" directory * across namespaces. Executes `publish()` from each instance, parsing * each result. */ class Publish extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'CodeIgniter'; /** * The Command's name * * @var string */ protected $name = 'publish'; /** * The Command's short description * * @var string */ protected $description = 'Discovers and executes all predefined Publisher classes.'; /** * The Command's usage * * @var string */ protected $usage = 'publish [<directory>]'; /** * The Command's arguments * * @var array<string, string> */ protected $arguments = [ 'directory' => '[Optional] The directory to scan within each namespace. Default: "Publishers".', ]; /** * the Command's Options * * @var array<string, string> */ protected $options = [ '--namespace' => 'The namespace from which to search for files to publish. By default, all namespaces are analysed.', ]; /** * Displays the help for the spark cli script itself. */ public function run(array $params) { $directory = $params[0] ?? 'Publishers'; $namespace = $params['namespace'] ?? ''; if ([] === $publishers = Publisher::discover($directory, $namespace)) { if ($namespace === '') { CLI::write(lang('Publisher.publishMissing', [$directory])); } else { CLI::write(lang('Publisher.publishMissingNamespace', [$directory, $namespace])); } return; } foreach ($publishers as $publisher) { if ($publisher->publish()) { CLI::write(lang('Publisher.publishSuccess', [ $publisher::class, count($publisher->getPublished()), $publisher->getDestination(), ]), 'green'); } else { CLI::error(lang('Publisher.publishFailure', [ $publisher::class, $publisher->getDestination(), ]), 'light_gray', 'red'); foreach ($publisher->getErrors() as $file => $exception) { CLI::write($file); CLI::error($exception->getMessage()); CLI::newLine(); } } } } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/FilterCheck.php
system/Commands/Utilities/FilterCheck.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Commands\Utilities\Routes\FilterCollector; /** * Check filters for a route. */ class FilterCheck extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'CodeIgniter'; /** * The Command's name * * @var string */ protected $name = 'filter:check'; /** * the Command's short description * * @var string */ protected $description = 'Check filters for a route.'; /** * the Command's usage * * @var string */ protected $usage = 'filter:check <HTTP method> <route>'; /** * the Command's Arguments * * @var array<string, string> */ protected $arguments = [ 'method' => 'The HTTP method. GET, POST, PUT, etc.', 'route' => 'The route (URI path) to check filters.', ]; /** * the Command's Options * * @var array<string, string> */ protected $options = []; /** * @return int exit code */ public function run(array $params) { if (! $this->checkParams($params)) { return EXIT_ERROR; } $method = $params[0]; $route = $params[1]; // Load Routes service('routes')->loadRoutes(); $filterCollector = new FilterCollector(); $filters = $filterCollector->get($method, $route); // PageNotFoundException if ($filters['before'] === ['<unknown>']) { CLI::error( "Can't find a route: " . CLI::color( '"' . strtoupper($method) . ' ' . $route . '"', 'black', 'light_gray', ), ); return EXIT_ERROR; } $this->showTable($filterCollector, $filters, $method, $route); $this->showFilterClasses($filterCollector, $method, $route); return EXIT_SUCCESS; } /** * @param array<int|string, string|null> $params */ private function checkParams(array $params): bool { if (! isset($params[0], $params[1])) { CLI::error('You must specify a HTTP verb and a route.'); CLI::write(' Usage: ' . $this->usage); CLI::write('Example: filter:check GET /'); CLI::write(' filter:check PUT products/1'); return false; } return true; } /** * @param array{before: list<string>, after: list<string>} $filters */ private function showTable( FilterCollector $filterCollector, array $filters, string $method, string $route, ): void { $thead = [ 'Method', 'Route', 'Before Filters', 'After Filters', ]; $required = $filterCollector->getRequiredFilters(); $coloredRequired = $this->colorItems($required); $before = array_merge($coloredRequired['before'], $filters['before']); $after = array_merge($filters['after'], $coloredRequired['after']); $tbody = []; $tbody[] = [ strtoupper($method), $route, implode(' ', $before), implode(' ', $after), ]; CLI::table($tbody, $thead); } /** * Color all elements of the array. * * @param array<array-key, mixed> $array * * @return array<array-key, mixed> */ private function colorItems(array $array): array { return array_map(function ($item): array|string { if (is_array($item)) { return $this->colorItems($item); } return CLI::color($item, 'yellow'); }, $array); } private function showFilterClasses( FilterCollector $filterCollector, string $method, string $route, ): void { $requiredFilterClasses = $filterCollector->getRequiredFilterClasses(); $filterClasses = $filterCollector->getClasses($method, $route); $coloredRequiredFilterClasses = $this->colorItems($requiredFilterClasses); $classList = [ 'before' => array_merge($coloredRequiredFilterClasses['before'], $filterClasses['before']), 'after' => array_merge($filterClasses['after'], $coloredRequiredFilterClasses['after']), ]; foreach ($classList as $position => $classes) { CLI::write(ucfirst($position) . ' Filter Classes:', 'cyan'); CLI::write(implode(' → ', $classes)); } } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/Namespaces.php
system/Commands/Utilities/Namespaces.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use Config\Autoload; /** * Lists namespaces set in Config\Autoload with their * full server path. Helps you to verify that you have * the namespaces setup correctly. * * @see \CodeIgniter\Commands\Utilities\NamespacesTest */ class Namespaces extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'CodeIgniter'; /** * The Command's name * * @var string */ protected $name = 'namespaces'; /** * the Command's short description * * @var string */ protected $description = 'Verifies your namespaces are setup correctly.'; /** * the Command's usage * * @var string */ protected $usage = 'namespaces'; /** * the Command's Arguments * * @var array<string, string> */ protected $arguments = []; /** * the Command's Options * * @var array<string, string> */ protected $options = [ '-c' => 'Show only CodeIgniter config namespaces.', '-r' => 'Show raw path strings.', '-m' => 'Specify max length of the path strings to output. Default: 60.', ]; /** * Displays the help for the spark cli script itself. */ public function run(array $params) { $params['m'] = (int) ($params['m'] ?? 60); $tbody = array_key_exists('c', $params) ? $this->outputCINamespaces($params) : $this->outputAllNamespaces($params); $thead = [ 'Namespace', 'Path', 'Found?', ]; CLI::table($tbody, $thead); } private function outputAllNamespaces(array $params): array { $maxLength = $params['m']; $autoloader = service('autoloader'); $tbody = []; foreach ($autoloader->getNamespace() as $ns => $paths) { foreach ($paths as $path) { if (array_key_exists('r', $params)) { $pathOutput = $this->truncate($path, $maxLength); } else { $pathOutput = $this->truncate(clean_path($path), $maxLength); } $tbody[] = [ $ns, $pathOutput, is_dir($path) ? 'Yes' : 'MISSING', ]; } } return $tbody; } private function truncate(string $string, int $max): string { $length = mb_strlen($string); if ($length > $max) { return mb_substr($string, 0, $max - 3) . '...'; } return $string; } private function outputCINamespaces(array $params): array { $maxLength = $params['m']; $config = new Autoload(); $tbody = []; foreach ($config->psr4 as $ns => $paths) { foreach ((array) $paths as $path) { if (array_key_exists('r', $params)) { $pathOutput = $this->truncate($path, $maxLength); } else { $pathOutput = $this->truncate(clean_path($path), $maxLength); } $path = realpath($path) ?: $path; $tbody[] = [ $ns, $pathOutput, is_dir($path) ? 'Yes' : 'MISSING', ]; } } return $tbody; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/Optimize.php
system/Commands/Utilities/Optimize.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities; use CodeIgniter\Autoloader\FileLocator; use CodeIgniter\Autoloader\FileLocatorCached; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Exceptions\RuntimeException; use CodeIgniter\Publisher\Publisher; /** * Optimize for production. */ final class Optimize extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'CodeIgniter'; /** * The Command's name * * @var string */ protected $name = 'optimize'; /** * The Command's short description * * @var string */ protected $description = 'Optimize for production.'; /** * The Command's usage * * @var string */ protected $usage = 'optimize'; /** * @return int */ public function run(array $params) { try { $this->enableCaching(); $this->clearCache(); $this->removeDevPackages(); return EXIT_SUCCESS; } catch (RuntimeException) { CLI::error('The "spark optimize" failed.'); return EXIT_ERROR; } } private function clearCache(): void { $locator = new FileLocatorCached(new FileLocator(service('autoloader'))); $locator->deleteCache(); CLI::write('Removed FileLocatorCache.', 'green'); $cache = WRITEPATH . 'cache/FactoriesCache_config'; $this->removeFile($cache); } private function removeFile(string $cache): void { if (is_file($cache)) { $result = unlink($cache); if ($result) { CLI::write('Removed "' . clean_path($cache) . '".', 'green'); return; } CLI::error('Error in removing file: ' . clean_path($cache)); throw new RuntimeException(__METHOD__); } } private function enableCaching(): void { $publisher = new Publisher(APPPATH, APPPATH); $config = APPPATH . 'Config/Optimize.php'; $result = $publisher->replace( $config, [ 'public bool $configCacheEnabled = false;' => 'public bool $configCacheEnabled = true;', 'public bool $locatorCacheEnabled = false;' => 'public bool $locatorCacheEnabled = true;', ], ); if ($result) { CLI::write( 'Config Caching and FileLocator Caching are enabled in "app/Config/Optimize.php".', 'green', ); return; } CLI::error('Error in updating file: ' . clean_path($config)); throw new RuntimeException(__METHOD__); } private function removeDevPackages(): void { if (! defined('VENDORPATH')) { return; } chdir(ROOTPATH); passthru('composer install --no-dev', $status); if ($status === 0) { CLI::write('Removed Composer dev packages.', 'green'); return; } CLI::error('Error in removing Composer dev packages.'); throw new RuntimeException(__METHOD__); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/Environment.php
system/Commands/Utilities/Environment.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Config\DotEnv; /** * Command to display the current environment, * or set a new one in the `.env` file. */ final class Environment extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'CodeIgniter'; /** * The Command's name * * @var string */ protected $name = 'env'; /** * The Command's short description * * @var string */ protected $description = 'Retrieves the current environment, or set a new one.'; /** * The Command's usage * * @var string */ protected $usage = 'env [<environment>]'; /** * The Command's arguments * * @var array<string, string> */ protected $arguments = [ 'environment' => '[Optional] The new environment to set. If none is provided, this will print the current environment.', ]; /** * The Command's options * * @var array<string, string> */ protected $options = []; /** * Allowed values for environment. `testing` is excluded * since spark won't work on it. * * @var array<int, string> */ private static array $knownTypes = [ 'production', 'development', ]; /** * @return int */ public function run(array $params) { if ($params === []) { CLI::write(sprintf('Your environment is currently set as %s.', CLI::color($_SERVER['CI_ENVIRONMENT'] ?? ENVIRONMENT, 'green'))); CLI::newLine(); return EXIT_ERROR; } $env = strtolower(array_shift($params)); if ($env === 'testing') { CLI::error('The "testing" environment is reserved for PHPUnit testing.', 'light_gray', 'red'); CLI::error('You will not be able to run spark under a "testing" environment.', 'light_gray', 'red'); CLI::newLine(); return EXIT_ERROR; } if (! in_array($env, self::$knownTypes, true)) { CLI::error(sprintf('Invalid environment type "%s". Expected one of "%s".', $env, implode('" and "', self::$knownTypes)), 'light_gray', 'red'); CLI::newLine(); return EXIT_ERROR; } if (! $this->writeNewEnvironmentToEnvFile($env)) { CLI::error('Error in writing new environment to .env file.', 'light_gray', 'red'); CLI::newLine(); return EXIT_ERROR; } // force DotEnv to reload the new environment // however we cannot redefine the ENVIRONMENT constant putenv('CI_ENVIRONMENT'); unset($_ENV['CI_ENVIRONMENT'], $_SERVER['CI_ENVIRONMENT']); (new DotEnv(ROOTPATH))->load(); CLI::write(sprintf('Environment is successfully changed to "%s".', $env), 'green'); CLI::write('The ENVIRONMENT constant will be changed in the next script execution.'); CLI::newLine(); return EXIT_SUCCESS; } /** * @see https://regex101.com/r/4sSORp/1 for the regex in action */ private function writeNewEnvironmentToEnvFile(string $newEnv): bool { $baseEnv = ROOTPATH . 'env'; $envFile = ROOTPATH . '.env'; if (! is_file($envFile)) { if (! is_file($baseEnv)) { CLI::write('Both default shipped `env` file and custom `.env` are missing.', 'yellow'); CLI::write('It is impossible to write the new environment type.', 'yellow'); CLI::newLine(); return false; } copy($baseEnv, $envFile); } $pattern = preg_quote($_SERVER['CI_ENVIRONMENT'] ?? ENVIRONMENT, '/'); $pattern = sprintf('/^[#\s]*CI_ENVIRONMENT[=\s]+%s$/m', $pattern); return file_put_contents( $envFile, preg_replace($pattern, "\nCI_ENVIRONMENT = {$newEnv}", file_get_contents($envFile), -1, $count), ) !== false && $count > 0; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/PhpIniCheck.php
system/Commands/Utilities/PhpIniCheck.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Security\CheckPhpIni; /** * Check php.ini values. */ final class PhpIniCheck extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'CodeIgniter'; /** * The Command's name * * @var string */ protected $name = 'phpini:check'; /** * The Command's short description * * @var string */ protected $description = 'Check your php.ini values in production environment.'; /** * The Command's usage * * @var string */ protected $usage = 'phpini:check'; /** * The Command's arguments * * @var array<string, string> */ protected $arguments = [ 'opcache' => 'Check detail opcache values in production environment.', ]; /** * The Command's options * * @var array<string, string> */ protected $options = []; /** * @return int */ public function run(array $params) { if (isset($params[0]) && ! in_array($params[0], array_keys($this->arguments), true)) { CLI::error('You must specify a correct argument.'); CLI::write(' Usage: ' . $this->usage); CLI::write(' Example: phpini:check opcache'); CLI::write('Arguments:'); $length = max(array_map(strlen(...), array_keys($this->arguments))); foreach ($this->arguments as $argument => $description) { CLI::write(CLI::color($this->setPad($argument, $length, 2, 2), 'green') . $description); } return EXIT_ERROR; } $argument = $params[0] ?? null; CheckPhpIni::run(argument: $argument); return EXIT_SUCCESS; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/Routes.php
system/Commands/Utilities/Routes.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Commands\Utilities\Routes\AutoRouteCollector; use CodeIgniter\Commands\Utilities\Routes\AutoRouterImproved\AutoRouteCollector as AutoRouteCollectorImproved; use CodeIgniter\Commands\Utilities\Routes\FilterCollector; use CodeIgniter\Commands\Utilities\Routes\SampleURIGenerator; use CodeIgniter\Router\DefinedRouteCollector; use CodeIgniter\Router\Router; use Config\Feature; use Config\Routing; /** * Lists all the routes. This will include any Routes files * that can be discovered, and will include routes that are not defined * in routes files, but are instead discovered through auto-routing. */ class Routes extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'CodeIgniter'; /** * The Command's name * * @var string */ protected $name = 'routes'; /** * the Command's short description * * @var string */ protected $description = 'Displays all routes.'; /** * the Command's usage * * @var string */ protected $usage = 'routes'; /** * the Command's Arguments * * @var array<string, string> */ protected $arguments = []; /** * the Command's Options * * @var array<string, string> */ protected $options = [ '-h' => 'Sort by Handler.', '--host' => 'Specify hostname in request URI.', ]; /** * Displays the help for the spark cli script itself. */ public function run(array $params) { $sortByHandler = array_key_exists('h', $params); $host = $params['host'] ?? null; // Set HTTP_HOST if ($host !== null) { $request = service('request'); $_SERVER = $request->getServer(); $_SERVER['HTTP_HOST'] = $host; $request->setGlobal('server', $_SERVER); } $collection = service('routes')->loadRoutes(); // Reset HTTP_HOST if ($host !== null) { unset($_SERVER['HTTP_HOST']); } $methods = Router::HTTP_METHODS; $tbody = []; $uriGenerator = new SampleURIGenerator(); $filterCollector = new FilterCollector(); $definedRouteCollector = new DefinedRouteCollector($collection); foreach ($definedRouteCollector->collect() as $route) { $sampleUri = $uriGenerator->get($route['route']); $filters = $filterCollector->get($route['method'], $sampleUri); $routeName = ($route['route'] === $route['name']) ? '»' : $route['name']; $tbody[] = [ strtoupper($route['method']), $route['route'], $routeName, $route['handler'], implode(' ', array_map(class_basename(...), $filters['before'])), implode(' ', array_map(class_basename(...), $filters['after'])), ]; } if ($collection->shouldAutoRoute()) { $autoRoutesImproved = config(Feature::class)->autoRoutesImproved ?? false; if ($autoRoutesImproved) { $autoRouteCollector = new AutoRouteCollectorImproved( $collection->getDefaultNamespace(), $collection->getDefaultController(), $collection->getDefaultMethod(), $methods, $collection->getRegisteredControllers('*'), ); $autoRoutes = $autoRouteCollector->get(); // Check for Module Routes. $routingConfig = config(Routing::class); if ($routingConfig instanceof Routing) { foreach ($routingConfig->moduleRoutes as $uri => $namespace) { $autoRouteCollector = new AutoRouteCollectorImproved( $namespace, $collection->getDefaultController(), $collection->getDefaultMethod(), $methods, $collection->getRegisteredControllers('*'), $uri, ); $autoRoutes = [...$autoRoutes, ...$autoRouteCollector->get()]; } } } else { $autoRouteCollector = new AutoRouteCollector( $collection->getDefaultNamespace(), $collection->getDefaultController(), $collection->getDefaultMethod(), ); $autoRoutes = $autoRouteCollector->get(); foreach ($autoRoutes as &$routes) { // There is no `AUTO` method, but it is intentional not to get route filters. $filters = $filterCollector->get('AUTO', $uriGenerator->get($routes[1])); $routes[] = implode(' ', array_map(class_basename(...), $filters['before'])); $routes[] = implode(' ', array_map(class_basename(...), $filters['after'])); } } $tbody = [...$tbody, ...$autoRoutes]; } $thead = [ 'Method', 'Route', 'Name', $sortByHandler ? 'Handler ↓' : 'Handler', 'Before Filters', 'After Filters', ]; // Sort by Handler. if ($sortByHandler) { usort($tbody, static fn ($handler1, $handler2): int => strcmp($handler1[3], $handler2[3])); } if ($host !== null) { CLI::write('Host: ' . $host); } CLI::table($tbody, $thead); $this->showRequiredFilters(); } private function showRequiredFilters(): void { $filterCollector = new FilterCollector(); $required = $filterCollector->getRequiredFilters(); $filters = []; foreach ($required['before'] as $filter) { $filters[] = CLI::color($filter, 'yellow'); } CLI::write('Required Before Filters: ' . implode(', ', $filters)); $filters = []; foreach ($required['after'] as $filter) { $filters[] = CLI::color($filter, 'yellow'); } CLI::write(' Required After Filters: ' . implode(', ', $filters)); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/ConfigCheck.php
system/Commands/Utilities/ConfigCheck.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities; use CodeIgniter\Cache\FactoriesCache; use CodeIgniter\CLI\BaseCommand; use CodeIgniter\CLI\CLI; use CodeIgniter\Config\BaseConfig; use Config\Optimize; use Kint\Kint; /** * Check the Config values. * * @see \CodeIgniter\Commands\Utilities\ConfigCheckTest */ final class ConfigCheck extends BaseCommand { /** * The group the command is lumped under * when listing commands. * * @var string */ protected $group = 'CodeIgniter'; /** * The Command's name * * @var string */ protected $name = 'config:check'; /** * The Command's short description * * @var string */ protected $description = 'Check your Config values.'; /** * The Command's usage * * @var string */ protected $usage = 'config:check <classname>'; /** * The Command's arguments * * @var array<string, string> */ protected $arguments = [ 'classname' => 'The config classname to check. Short classname or FQCN.', ]; /** * The Command's options * * @var array<string, string> */ protected $options = []; /** * @return int */ public function run(array $params) { if (! isset($params[0])) { CLI::error('You must specify a Config classname.'); CLI::write(' Usage: ' . $this->usage); CLI::write('Example: config:check App'); CLI::write(' config:check \'CodeIgniter\Shield\Config\Auth\''); return EXIT_ERROR; } /** @var class-string<BaseConfig> $class */ $class = $params[0]; // Load Config cache if it is enabled. $configCacheEnabled = class_exists(Optimize::class) && (new Optimize())->configCacheEnabled; if ($configCacheEnabled) { $factoriesCache = new FactoriesCache(); $factoriesCache->load('config'); } $config = config($class); if ($config === null) { CLI::error('No such Config class: ' . $class); return EXIT_ERROR; } if (defined('KINT_DIR') && Kint::$enabled_mode !== false) { CLI::write($this->getKintD($config)); } else { CLI::write( CLI::color($this->getVarDump($config), 'cyan'), ); } CLI::newLine(); $state = CLI::color($configCacheEnabled ? 'Enabled' : 'Disabled', 'green'); CLI::write('Config Caching: ' . $state); return EXIT_SUCCESS; } /** * Gets object dump by Kint d() */ private function getKintD(object $config): string { ob_start(); d($config); $output = ob_get_clean(); $output = trim($output); $lines = explode("\n", $output); array_splice($lines, 0, 3); array_splice($lines, -3); return implode("\n", $lines); } /** * Gets object dump by var_dump() */ private function getVarDump(object $config): string { ob_start(); var_dump($config); $output = ob_get_clean(); return preg_replace( '!.*system/Commands/Utilities/ConfigCheck.php.*\n!u', '', $output, ); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/Routes/AutoRouteCollector.php
system/Commands/Utilities/Routes/AutoRouteCollector.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities\Routes; /** * Collects data for auto route listing. * * @see \CodeIgniter\Commands\Utilities\Routes\AutoRouteCollectorTest */ final class AutoRouteCollector { /** * @param string $namespace namespace to search */ public function __construct(private readonly string $namespace, private readonly string $defaultController, private readonly string $defaultMethod) { } /** * @return list<list<string>> */ public function get(): array { $finder = new ControllerFinder($this->namespace); $reader = new ControllerMethodReader($this->namespace); $tbody = []; foreach ($finder->find() as $class) { $output = $reader->read( $class, $this->defaultController, $this->defaultMethod, ); foreach ($output as $item) { $tbody[] = [ 'auto', $item['route'], '', $item['handler'], ]; } } return $tbody; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/Routes/SampleURIGenerator.php
system/Commands/Utilities/Routes/SampleURIGenerator.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities\Routes; use CodeIgniter\Router\RouteCollection; use Config\App; /** * Generate a sample URI path from route key regex. * * @see \CodeIgniter\Commands\Utilities\Routes\SampleURIGeneratorTest */ final class SampleURIGenerator { private readonly RouteCollection $routes; /** * Sample URI path for placeholder. * * @var array<string, string> */ private array $samples = [ 'any' => '123/abc', 'segment' => 'abc_123', 'alphanum' => 'abc123', 'num' => '123', 'alpha' => 'abc', 'hash' => 'abc_123', ]; public function __construct(?RouteCollection $routes = null) { $this->routes = $routes ?? service('routes'); } /** * @param string $routeKey route key regex * * @return string sample URI path */ public function get(string $routeKey): string { $sampleUri = $routeKey; if (str_contains($routeKey, '{locale}')) { $sampleUri = str_replace( '{locale}', config(App::class)->defaultLocale, $routeKey, ); } foreach ($this->routes->getPlaceholders() as $placeholder => $regex) { $sample = $this->samples[$placeholder] ?? '::unknown::'; $sampleUri = str_replace('(' . $regex . ')', $sample, $sampleUri); } // auto route return str_replace('[/...]', '/1/2/3/4/5', $sampleUri); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/Routes/FilterCollector.php
system/Commands/Utilities/Routes/FilterCollector.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities\Routes; use CodeIgniter\Filters\Filters; use CodeIgniter\HTTP\Method; use CodeIgniter\HTTP\Request; use CodeIgniter\Router\Router; use Config\Filters as FiltersConfig; /** * Collects filters for a route. * * @see \CodeIgniter\Commands\Utilities\Routes\FilterCollectorTest */ final class FilterCollector { public function __construct( /** * Whether to reset Defined Routes. * * If set to true, route filters are not found. */ private readonly bool $resetRoutes = false, ) { } /** * Returns filters for the URI * * @param string $method HTTP verb like `GET`,`POST` or `CLI`. * @param string $uri URI path to find filters for * * @return array{before: list<string>, after: list<string>} array of alias/classname:args */ public function get(string $method, string $uri): array { if ($method === strtolower($method)) { @trigger_error( 'Passing lowercase HTTP method "' . $method . '" is deprecated.' . ' Use uppercase HTTP method like "' . strtoupper($method) . '".', E_USER_DEPRECATED, ); } /** * @deprecated 4.5.0 * @TODO Remove this in the future. */ $method = strtoupper($method); if ($method === 'CLI') { return [ 'before' => [], 'after' => [], ]; } $request = service('incomingrequest', null, false); $request->setMethod($method); $router = $this->createRouter($request); $filters = $this->createFilters($request); $finder = new FilterFinder($router, $filters); return $finder->find($uri); } /** * Returns filter classes for the URI * * @param string $method HTTP verb like `GET`,`POST` or `CLI`. * @param string $uri URI path to find filters for * * @return array{before: list<string>, after: list<string>} array of classname:args */ public function getClasses(string $method, string $uri): array { if ($method === strtolower($method)) { @trigger_error( 'Passing lowercase HTTP method "' . $method . '" is deprecated.' . ' Use uppercase HTTP method like "' . strtoupper($method) . '".', E_USER_DEPRECATED, ); } /** * @deprecated 4.5.0 * @TODO Remove this in the future. */ $method = strtoupper($method); if ($method === 'CLI') { return [ 'before' => [], 'after' => [], ]; } $request = service('incomingrequest', null, false); $request->setMethod($method); $router = $this->createRouter($request); $filters = $this->createFilters($request); $finder = new FilterFinder($router, $filters); return $finder->findClasses($uri); } /** * Returns Required Filters * * @return array{before: list<string>, after: list<string>} array of aliases */ public function getRequiredFilters(): array { $request = service('incomingrequest', null, false); $request->setMethod(Method::GET); $router = $this->createRouter($request); $filters = $this->createFilters($request); $finder = new FilterFinder($router, $filters); return $finder->getRequiredFilters(); } /** * Returns Required Filter class list * * @return array{before: list<string>, after: list<string>} array of classnames */ public function getRequiredFilterClasses(): array { $request = service('incomingrequest', null, false); $request->setMethod(Method::GET); $router = $this->createRouter($request); $filters = $this->createFilters($request); $finder = new FilterFinder($router, $filters); return $finder->getRequiredFilterClasses(); } private function createRouter(Request $request): Router { $routes = service('routes'); if ($this->resetRoutes) { $routes->resetRoutes(); } return new Router($routes, $request); } private function createFilters(Request $request): Filters { $config = config(FiltersConfig::class); return new Filters($config, $request, service('response')); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/Routes/FilterFinder.php
system/Commands/Utilities/Routes/FilterFinder.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities\Routes; use CodeIgniter\Exceptions\PageNotFoundException; use CodeIgniter\Filters\Filters; use CodeIgniter\HTTP\Exceptions\BadRequestException; use CodeIgniter\HTTP\Exceptions\RedirectException; use CodeIgniter\Router\Router; use Config\Feature; /** * Finds filters. * * @see \CodeIgniter\Commands\Utilities\Routes\FilterFinderTest */ final class FilterFinder { private readonly Router $router; private readonly Filters $filters; public function __construct(?Router $router = null, ?Filters $filters = null) { $this->router = $router ?? service('router'); $this->filters = $filters ?? service('filters'); } private function getRouteFilters(string $uri): array { $this->router->handle($uri); return $this->router->getFilters(); } /** * @param string $uri URI path to find filters for * * @return array{before: list<string>, after: list<string>} array of alias/classname:args */ public function find(string $uri): array { $this->filters->reset(); try { // Add route filters $routeFilters = $this->getRouteFilters($uri); $this->filters->enableFilters($routeFilters, 'before'); $oldFilterOrder = config(Feature::class)->oldFilterOrder ?? false; if (! $oldFilterOrder) { $routeFilters = array_reverse($routeFilters); } $this->filters->enableFilters($routeFilters, 'after'); $this->filters->initialize($uri); return $this->filters->getFilters(); } catch (RedirectException) { return [ 'before' => [], 'after' => [], ]; } catch (BadRequestException|PageNotFoundException) { return [ 'before' => ['<unknown>'], 'after' => ['<unknown>'], ]; } } /** * @param string $uri URI path to find filters for * * @return array{before: list<string>, after: list<string>} array of classname:args */ public function findClasses(string $uri): array { $this->filters->reset(); try { // Add route filters $routeFilters = $this->getRouteFilters($uri); $this->filters->enableFilters($routeFilters, 'before'); $oldFilterOrder = config(Feature::class)->oldFilterOrder ?? false; if (! $oldFilterOrder) { $routeFilters = array_reverse($routeFilters); } $this->filters->enableFilters($routeFilters, 'after'); $this->filters->initialize($uri); $filterClassList = $this->filters->getFiltersClass(); $filterClasses = [ 'before' => [], 'after' => [], ]; foreach ($filterClassList['before'] as $classInfo) { $classWithArguments = ($classInfo[1] === []) ? $classInfo[0] : $classInfo[0] . ':' . implode(',', $classInfo[1]); $filterClasses['before'][] = $classWithArguments; } foreach ($filterClassList['after'] as $classInfo) { $classWithArguments = ($classInfo[1] === []) ? $classInfo[0] : $classInfo[0] . ':' . implode(',', $classInfo[1]); $filterClasses['after'][] = $classWithArguments; } return $filterClasses; } catch (RedirectException) { return [ 'before' => [], 'after' => [], ]; } catch (BadRequestException|PageNotFoundException) { return [ 'before' => ['<unknown>'], 'after' => ['<unknown>'], ]; } } /** * Returns Required Filters * * @return array{before: list<string>, after:list<string>} array of aliases */ public function getRequiredFilters(): array { [$requiredBefore] = $this->filters->getRequiredFilters('before'); [$requiredAfter] = $this->filters->getRequiredFilters('after'); return [ 'before' => $requiredBefore, 'after' => $requiredAfter, ]; } /** * Returns Required Filter classes * * @return array{before: list<string>, after:list<string>} */ public function getRequiredFilterClasses(): array { $before = $this->filters->getRequiredClasses('before'); $after = $this->filters->getRequiredClasses('after'); $requiredBefore = []; $requiredAfter = []; foreach ($before as $classInfo) { $requiredBefore[] = $classInfo[0]; } foreach ($after as $classInfo) { $requiredAfter[] = $classInfo[0]; } return [ 'before' => $requiredBefore, 'after' => $requiredAfter, ]; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/Routes/ControllerFinder.php
system/Commands/Utilities/Routes/ControllerFinder.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities\Routes; use CodeIgniter\Autoloader\FileLocatorInterface; /** * Finds all controllers in a namespace for auto route listing. * * @see \CodeIgniter\Commands\Utilities\Routes\ControllerFinderTest */ final class ControllerFinder { private readonly FileLocatorInterface $locator; /** * @param string $namespace namespace to search */ public function __construct( private readonly string $namespace, ) { $this->locator = service('locator'); } /** * @return list<class-string> */ public function find(): array { $nsArray = explode('\\', trim($this->namespace, '\\')); $count = count($nsArray); $ns = ''; $files = []; for ($i = 0; $i < $count; $i++) { $ns .= '\\' . array_shift($nsArray); $path = implode('\\', $nsArray); $files = $this->locator->listNamespaceFiles($ns, $path); if ($files !== []) { break; } } $classes = []; foreach ($files as $file) { if (\is_file($file)) { $classnameOrEmpty = $this->locator->getClassname($file); if ($classnameOrEmpty !== '') { /** @var class-string $classname */ $classname = $classnameOrEmpty; $classes[] = $classname; } } } return $classes; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/Routes/ControllerMethodReader.php
system/Commands/Utilities/Routes/ControllerMethodReader.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities\Routes; use ReflectionClass; use ReflectionMethod; /** * Reads a controller and returns a list of auto route listing. * * @see \CodeIgniter\Commands\Utilities\Routes\ControllerMethodReaderTest */ final class ControllerMethodReader { /** * @param string $namespace the default namespace */ public function __construct(private readonly string $namespace) { } /** * @param class-string $class * * @return list<array{route: string, handler: string}> */ public function read(string $class, string $defaultController = 'Home', string $defaultMethod = 'index'): array { $reflection = new ReflectionClass($class); if ($reflection->isAbstract()) { return []; } $classname = $reflection->getName(); $classShortname = $reflection->getShortName(); $output = []; $uriByClass = $this->getUriByClass($classname); if ($this->hasRemap($reflection)) { $methodName = '_remap'; $routeWithoutController = $this->getRouteWithoutController( $classShortname, $defaultController, $uriByClass, $classname, $methodName, ); $output = [...$output, ...$routeWithoutController]; $output[] = [ 'route' => $uriByClass . '[/...]', 'handler' => '\\' . $classname . '::' . $methodName, ]; return $output; } foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { $methodName = $method->getName(); $route = $uriByClass . '/' . $methodName; // Exclude BaseController and initController // See system/Config/Routes.php if (preg_match('#\AbaseController.*#', $route) === 1) { continue; } if (preg_match('#.*/initController\z#', $route) === 1) { continue; } if ($methodName === $defaultMethod) { $routeWithoutController = $this->getRouteWithoutController( $classShortname, $defaultController, $uriByClass, $classname, $methodName, ); $output = [...$output, ...$routeWithoutController]; $output[] = [ 'route' => $uriByClass, 'handler' => '\\' . $classname . '::' . $methodName, ]; } $output[] = [ 'route' => $route . '[/...]', 'handler' => '\\' . $classname . '::' . $methodName, ]; } return $output; } /** * Whether the class has a _remap() method. */ private function hasRemap(ReflectionClass $class): bool { if ($class->hasMethod('_remap')) { $remap = $class->getMethod('_remap'); return $remap->isPublic(); } return false; } /** * @param class-string $classname * * @return string URI path part from the folder(s) and controller */ private function getUriByClass(string $classname): string { // remove the namespace $pattern = '/' . preg_quote($this->namespace, '/') . '/'; $class = ltrim(preg_replace($pattern, '', $classname), '\\'); $classParts = explode('\\', $class); $classPath = ''; foreach ($classParts as $part) { // make the first letter lowercase, because auto routing makes // the URI path's first letter uppercase and search the controller $classPath .= lcfirst($part) . '/'; } return rtrim($classPath, '/'); } /** * Gets a route without default controller. */ private function getRouteWithoutController( string $classShortname, string $defaultController, string $uriByClass, string $classname, string $methodName, ): array { if ($classShortname !== $defaultController) { return []; } $pattern = '#' . preg_quote(lcfirst($defaultController), '#') . '\z#'; $routeWithoutController = rtrim(preg_replace($pattern, '', $uriByClass), '/'); $routeWithoutController = $routeWithoutController !== '' && $routeWithoutController !== '0' ? $routeWithoutController : '/'; return [[ 'route' => $routeWithoutController, 'handler' => '\\' . $classname . '::' . $methodName, ]]; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/Routes/AutoRouterImproved/AutoRouteCollector.php
system/Commands/Utilities/Routes/AutoRouterImproved/AutoRouteCollector.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities\Routes\AutoRouterImproved; use CodeIgniter\Commands\Utilities\Routes\ControllerFinder; use CodeIgniter\Commands\Utilities\Routes\FilterCollector; /** * Collects data for Auto Routing Improved. * * @see \CodeIgniter\Commands\Utilities\Routes\AutoRouterImproved\AutoRouteCollectorTest */ final class AutoRouteCollector { /** * @param string $namespace namespace to search * @param list<class-string> $protectedControllers List of controllers in Defined * Routes that should not be accessed via Auto-Routing. * @param list<string> $httpMethods * @param string $prefix URI prefix for Module Routing */ public function __construct( private readonly string $namespace, private readonly string $defaultController, private readonly string $defaultMethod, private readonly array $httpMethods, private readonly array $protectedControllers, private readonly string $prefix = '', ) { } /** * @return list<list<string>> */ public function get(): array { $finder = new ControllerFinder($this->namespace); $reader = new ControllerMethodReader($this->namespace, $this->httpMethods); $tbody = []; foreach ($finder->find() as $class) { // Exclude controllers in Defined Routes. if (in_array('\\' . $class, $this->protectedControllers, true)) { continue; } $routes = $reader->read( $class, $this->defaultController, $this->defaultMethod, ); if ($routes === []) { continue; } $routes = $this->addFilters($routes); foreach ($routes as $item) { $route = $item['route'] . $item['route_params']; // For module routing if ($this->prefix !== '' && $route === '/') { $route = $this->prefix; } elseif ($this->prefix !== '') { $route = $this->prefix . '/' . $route; } $tbody[] = [ strtoupper($item['method']) . '(auto)', $route, '', $item['handler'], $item['before'], $item['after'], ]; } } return $tbody; } /** * Adding Filters * * @param list<array<string, array|string>> $routes * * @return list<array<string, array|string>> */ private function addFilters($routes) { $filterCollector = new FilterCollector(true); foreach ($routes as &$route) { $routePath = $route['route']; // For module routing if ($this->prefix !== '' && $route === '/') { $routePath = $this->prefix; } elseif ($this->prefix !== '') { $routePath = $this->prefix . '/' . $routePath; } // Search filters for the URI with all params $sampleUri = $this->generateSampleUri($route); $filtersLongest = $filterCollector->get($route['method'], $routePath . $sampleUri); // Search filters for the URI without optional params $sampleUri = $this->generateSampleUri($route, false); $filtersShortest = $filterCollector->get($route['method'], $routePath . $sampleUri); // Get common array elements $filters = [ 'before' => array_intersect($filtersLongest['before'], $filtersShortest['before']), 'after' => array_intersect($filtersLongest['after'], $filtersShortest['after']), ]; $route['before'] = implode(' ', array_map(class_basename(...), $filters['before'])); $route['after'] = implode(' ', array_map(class_basename(...), $filters['after'])); } return $routes; } private function generateSampleUri(array $route, bool $longest = true): string { $sampleUri = ''; if (isset($route['params'])) { $i = 1; foreach ($route['params'] as $required) { if ($longest && ! $required) { $sampleUri .= '/' . $i++; } } } return $sampleUri; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Commands/Utilities/Routes/AutoRouterImproved/ControllerMethodReader.php
system/Commands/Utilities/Routes/AutoRouterImproved/ControllerMethodReader.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Commands\Utilities\Routes\AutoRouterImproved; use Config\Routing; use ReflectionClass; use ReflectionMethod; /** * Reads a controller and returns a list of auto route listing. * * @see \CodeIgniter\Commands\Utilities\Routes\AutoRouterImproved\ControllerMethodReaderTest */ final class ControllerMethodReader { private readonly bool $translateURIDashes; private readonly bool $translateUriToCamelCase; /** * @param string $namespace the default namespace * @param list<string> $httpMethods */ public function __construct( private readonly string $namespace, private readonly array $httpMethods, ) { $config = config(Routing::class); $this->translateURIDashes = $config->translateURIDashes; $this->translateUriToCamelCase = $config->translateUriToCamelCase; } /** * Returns found route info in the controller. * * @param class-string $class * * @return list<array<string, array|string>> */ public function read(string $class, string $defaultController = 'Home', string $defaultMethod = 'index'): array { $reflection = new ReflectionClass($class); if ($reflection->isAbstract()) { return []; } $classname = $reflection->getName(); $classShortname = $reflection->getShortName(); $output = []; $classInUri = $this->convertClassNameToUri($classname); foreach ($reflection->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { $methodName = $method->getName(); foreach ($this->httpMethods as $httpVerb) { if (str_starts_with($methodName, strtolower($httpVerb))) { // Remove HTTP verb prefix. $methodInUri = $this->convertMethodNameToUri($httpVerb, $methodName); // Check if it is the default method. if ($methodInUri === $defaultMethod) { $routeForDefaultController = $this->getRouteForDefaultController( $classShortname, $defaultController, $classInUri, $classname, $methodName, $httpVerb, $method, ); if ($routeForDefaultController !== []) { // The controller is the default controller. It only // has a route for the default method. Other methods // will not be routed even if they exist. $output = [...$output, ...$routeForDefaultController]; continue; } [$params, $routeParams] = $this->getParameters($method); // Route for the default method. $output[] = [ 'method' => $httpVerb, 'route' => $classInUri, 'route_params' => $routeParams, 'handler' => '\\' . $classname . '::' . $methodName, 'params' => $params, ]; continue; } $route = $classInUri . '/' . $methodInUri; [$params, $routeParams] = $this->getParameters($method); // If it is the default controller, the method will not be // routed. if ($classShortname === $defaultController) { $route = 'x ' . $route; } $output[] = [ 'method' => $httpVerb, 'route' => $route, 'route_params' => $routeParams, 'handler' => '\\' . $classname . '::' . $methodName, 'params' => $params, ]; } } } return $output; } private function getParameters(ReflectionMethod $method): array { $params = []; $routeParams = ''; $refParams = $method->getParameters(); foreach ($refParams as $param) { $required = true; if ($param->isOptional()) { $required = false; $routeParams .= '[/..]'; } else { $routeParams .= '/..'; } // [variable_name => required?] $params[$param->getName()] = $required; } return [$params, $routeParams]; } /** * @param class-string $classname * * @return string URI path part from the folder(s) and controller */ private function convertClassNameToUri(string $classname): string { // remove the namespace $pattern = '/' . preg_quote($this->namespace, '/') . '/'; $class = ltrim(preg_replace($pattern, '', $classname), '\\'); $classParts = explode('\\', $class); $classPath = ''; foreach ($classParts as $part) { // make the first letter lowercase, because auto routing makes // the URI path's first letter uppercase and search the controller $classPath .= lcfirst($part) . '/'; } $classUri = rtrim($classPath, '/'); return $this->translateToUri($classUri); } /** * @return string URI path part from the method */ private function convertMethodNameToUri(string $httpVerb, string $methodName): string { $methodUri = lcfirst(substr($methodName, strlen($httpVerb))); return $this->translateToUri($methodUri); } /** * @param string $string classname or method name */ private function translateToUri(string $string): string { if ($this->translateUriToCamelCase) { $string = strtolower( preg_replace('/([a-z\d])([A-Z])/', '$1-$2', $string), ); } elseif ($this->translateURIDashes) { $string = str_replace('_', '-', $string); } return $string; } /** * Gets a route for the default controller. * * @return list<array> */ private function getRouteForDefaultController( string $classShortname, string $defaultController, string $uriByClass, string $classname, string $methodName, string $httpVerb, ReflectionMethod $method, ): array { $output = []; if ($classShortname === $defaultController) { $pattern = '#' . preg_quote(lcfirst($defaultController), '#') . '\z#'; $routeWithoutController = rtrim(preg_replace($pattern, '', $uriByClass), '/'); $routeWithoutController = $routeWithoutController !== '' && $routeWithoutController !== '0' ? $routeWithoutController : '/'; [$params, $routeParams] = $this->getParameters($method); if ($routeWithoutController === '/' && $routeParams !== '') { $routeWithoutController = ''; } $output[] = [ 'method' => $httpVerb, 'route' => $routeWithoutController, 'route_params' => $routeParams, 'handler' => '\\' . $classname . '::' . $methodName, 'params' => $params, ]; } return $output; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Pager/PagerRenderer.php
system/Pager/PagerRenderer.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Pager; use CodeIgniter\HTTP\URI; /** * Class PagerRenderer * * This class is passed to the view that describes the pagination, * and is used to get the link information and provide utility * methods needed to work with pagination. * * @see \CodeIgniter\Pager\PagerRendererTest */ class PagerRenderer { /** * First page number in the set of links to be displayed. * * @var int */ protected $first; /** * Last page number in the set of links to be displayed. * * @var int */ protected $last; /** * Current page number. * * @var int */ protected $current; /** * Total number of items. * * @var int */ protected $total; /** * Total number of pages. * * @var int */ protected $pageCount; /** * URI base for pagination links * * @var URI */ protected $uri; /** * Segment number used for pagination. * * @var int */ protected $segment; /** * Name of $_GET parameter * * @var string */ protected $pageSelector; /** * Returns the number of results per page that should be shown. */ protected ?int $perPage; /** * The number of items the page starts with. */ protected ?int $perPageStart = null; /** * The number of items the page ends with. */ protected ?int $perPageEnd = null; /** * Constructor. */ public function __construct(array $details) { // `first` and `last` will be updated by `setSurroundCount()`. // You must call `setSurroundCount()` after instantiation. $this->first = 1; $this->last = $details['pageCount']; $this->current = $details['currentPage']; $this->total = $details['total']; $this->uri = $details['uri']; $this->pageCount = $details['pageCount']; $this->segment = $details['segment'] ?? 0; $this->pageSelector = $details['pageSelector'] ?? 'page'; $this->perPage = $details['perPage'] ?? null; $this->updatePerPages(); } /** * Sets the total number of links that should appear on either * side of the current page. Adjusts the first and last counts * to reflect it. * * @return PagerRenderer */ public function setSurroundCount(?int $count = null) { $this->updatePages($count); return $this; } /** * Checks to see if there is a "previous" page before our "first" page. */ public function hasPrevious(): bool { return $this->first > 1; } /** * Returns a URL to the "previous" page. The previous page is NOT the * page before the current page, but is the page just before the * "first" page. * * @return string|null */ public function getPrevious() { if (! $this->hasPrevious()) { return null; } $uri = clone $this->uri; if ($this->segment === 0) { $uri->addQuery($this->pageSelector, $this->first - 1); } else { $uri->setSegment($this->segment, $this->first - 1); } return URI::createURIString( $uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery(), $uri->getFragment(), ); } /** * Checks to see if there is a "next" page after our "last" page. */ public function hasNext(): bool { return $this->pageCount > $this->last; } /** * Returns a URL to the "next" page. The next page is NOT, the * page after the current page, but is the page that follows the * "last" page. * * @return string|null */ public function getNext() { if (! $this->hasNext()) { return null; } $uri = clone $this->uri; if ($this->segment === 0) { $uri->addQuery($this->pageSelector, $this->last + 1); } else { $uri->setSegment($this->segment, $this->last + 1); } return URI::createURIString( $uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery(), $uri->getFragment(), ); } /** * Returns the URI of the first page. */ public function getFirst(): string { $uri = clone $this->uri; if ($this->segment === 0) { $uri->addQuery($this->pageSelector, 1); } else { $uri->setSegment($this->segment, 1); } return URI::createURIString( $uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery(), $uri->getFragment(), ); } /** * Returns the URI of the last page. */ public function getLast(): string { $uri = clone $this->uri; if ($this->segment === 0) { $uri->addQuery($this->pageSelector, $this->pageCount); } else { $uri->setSegment($this->segment, $this->pageCount); } return URI::createURIString( $uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery(), $uri->getFragment(), ); } /** * Returns the URI of the current page. */ public function getCurrent(): string { $uri = clone $this->uri; if ($this->segment === 0) { $uri->addQuery($this->pageSelector, $this->current); } else { $uri->setSegment($this->segment, $this->current); } return URI::createURIString( $uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery(), $uri->getFragment(), ); } /** * Returns an array of links that should be displayed. Each link * is represented by another array containing of the URI the link * should go to, the title (number) of the link, and a boolean * value representing whether this link is active or not. * * @return list<array{uri:string, title:int, active:bool}> */ public function links(): array { $links = []; $uri = clone $this->uri; for ($i = $this->first; $i <= $this->last; $i++) { $uri = $this->segment === 0 ? $uri->addQuery($this->pageSelector, $i) : $uri->setSegment($this->segment, $i); $links[] = [ 'uri' => URI::createURIString( $uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery(), $uri->getFragment(), ), 'title' => $i, 'active' => ($i === $this->current), ]; } return $links; } /** * Updates the first and last pages based on $surroundCount, * which is the number of links surrounding the active page * to show. * * @param int|null $count The new "surroundCount" * * @return void */ protected function updatePages(?int $count = null) { if ($count === null) { return; } $this->first = $this->current - $count > 0 ? $this->current - $count : 1; $this->last = $this->current + $count <= $this->pageCount ? $this->current + $count : (int) $this->pageCount; } /** * Updates the start and end items per pages, which is * the number of items displayed on the active page. */ protected function updatePerPages(): void { if ($this->total === null || $this->perPage === null) { return; } // When the page is the last, perform a different calculation. if ($this->last === $this->current) { $this->perPageStart = $this->perPage * ($this->current - 1) + 1; $this->perPageEnd = $this->total; return; } $this->perPageStart = $this->current === 1 ? 1 : ($this->perPage * $this->current) - $this->perPage + 1; $this->perPageEnd = $this->perPage * $this->current; } /** * Checks to see if there is a "previous" page before our "first" page. */ public function hasPreviousPage(): bool { return $this->current > 1; } /** * Returns a URL to the "previous" page. * * You MUST call hasPreviousPage() first, or this value may be invalid. * * @return string|null */ public function getPreviousPage() { if (! $this->hasPreviousPage()) { return null; } $uri = clone $this->uri; if ($this->segment === 0) { $uri->addQuery($this->pageSelector, $this->current - 1); } else { $uri->setSegment($this->segment, $this->current - 1); } return URI::createURIString( $uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery(), $uri->getFragment(), ); } /** * Checks to see if there is a "next" page after our "last" page. */ public function hasNextPage(): bool { return $this->current < $this->last; } /** * Returns a URL to the "next" page. * * You MUST call hasNextPage() first, or this value may be invalid. * * @return string|null */ public function getNextPage() { if (! $this->hasNextPage()) { return null; } $uri = clone $this->uri; if ($this->segment === 0) { $uri->addQuery($this->pageSelector, $this->current + 1); } else { $uri->setSegment($this->segment, $this->current + 1); } return URI::createURIString( $uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery(), $uri->getFragment(), ); } /** * Returns the page number of the first page in the set of links to be displayed. */ public function getFirstPageNumber(): int { return $this->first; } /** * Returns the page number of the current page. */ public function getCurrentPageNumber(): int { return $this->current; } /** * Returns the page number of the last page in the set of links to be displayed. */ public function getLastPageNumber(): int { return $this->last; } /** * Returns total number of pages. */ public function getPageCount(): int { return $this->pageCount; } /** * Returns the previous page number. */ public function getPreviousPageNumber(): ?int { return ($this->current === 1) ? null : $this->current - 1; } /** * Returns the next page number. */ public function getNextPageNumber(): ?int { return ($this->current === $this->pageCount) ? null : $this->current + 1; } /** * Returns the total items of the page. */ public function getTotal(): ?int { return $this->total; } /** * Returns the number of items to be displayed on the page. */ public function getPerPage(): ?int { return $this->perPage; } /** * Returns the number of items the page starts with. */ public function getPerPageStart(): ?int { return $this->perPageStart; } /** * Returns the number of items the page ends with. */ public function getPerPageEnd(): ?int { return $this->perPageEnd; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Pager/PagerInterface.php
system/Pager/PagerInterface.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Pager; use CodeIgniter\HTTP\URI; /** * Expected behavior for a Pager */ interface PagerInterface { /** * Handles creating and displaying the * * @param string $template The output template alias to render. */ public function links(string $group = 'default', string $template = 'default'): string; /** * Creates simple Next/Previous links, instead of full pagination. */ public function simpleLinks(string $group = 'default', string $template = 'default'): string; /** * Allows for a simple, manual, form of pagination where all of the data * is provided by the user. The URL is the current URI. * * @param string $template The output template alias to render. */ public function makeLinks(int $page, int $perPage, int $total, string $template = 'default'): string; /** * Stores a set of pagination data for later display. Most commonly used * by the model to automate the process. * * @return $this */ public function store(string $group, int $page, int $perPage, int $total); /** * Sets the path that an aliased group of links will use. * * @return $this */ public function setPath(string $path, string $group = 'default'); /** * Returns the total number of pages. */ public function getPageCount(string $group = 'default'): int; /** * Returns the number of the current page of results. */ public function getCurrentPage(string $group = 'default'): int; /** * Returns the URI for a specific page for the specified group. * * @return string|URI */ public function getPageURI(?int $page = null, string $group = 'default', bool $returnObject = false); /** * Tells whether this group of results has any more pages of results. */ public function hasMore(string $group = 'default'): bool; /** * Returns the first page. * * @return int */ public function getFirstPage(string $group = 'default'); /** * Returns the last page, if we have a total that we can calculate with. * * @return int|null */ public function getLastPage(string $group = 'default'); /** * Returns the full URI to the next page of results, or null. * * @return string|null */ public function getNextPageURI(string $group = 'default'); /** * Returns the full URL to the previous page of results, or null. * * @return string|null */ public function getPreviousPageURI(string $group = 'default'); /** * Returns the number of results per page that should be shown. */ public function getPerPage(string $group = 'default'): int; /** * Returns an array with details about the results, including * total, per_page, current_page, last_page, next_url, prev_url, from, to. * Does not include the actual data. This data is suitable for adding * a 'data' object to with the result set and converting to JSON. */ public function getDetails(string $group = 'default'): array; }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Pager/Pager.php
system/Pager/Pager.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Pager; use CodeIgniter\HTTP\Exceptions\HTTPException; use CodeIgniter\HTTP\URI; use CodeIgniter\Pager\Exceptions\PagerException; use CodeIgniter\View\RendererInterface; use Config\Pager as PagerConfig; /** * Class Pager * * The Pager class provides semi-automatic and manual methods for creating * pagination links and reading the current url's query variable, "page" * to determine the current page. This class can support multiple * paginations on a single page. * * @see \CodeIgniter\Pager\PagerTest */ class Pager implements PagerInterface { /** * The group data. * * @var array */ protected $groups = []; /** * URI segment for groups if provided. * * @var array */ protected $segment = []; /** * Our configuration instance. * * @var PagerConfig */ protected $config; /** * The view engine to render the links with. * * @var RendererInterface */ protected $view; /** * List of only permitted queries * * @var list<string>|null */ protected $only; /** * Constructor. */ public function __construct(PagerConfig $config, RendererInterface $view) { $this->config = $config; $this->view = $view; } /** * Handles creating and displaying the * * @param string $template The output template alias to render. */ public function links(string $group = 'default', string $template = 'default_full'): string { $this->ensureGroup($group); return $this->displayLinks($group, $template); } /** * Creates simple Next/Previous links, instead of full pagination. */ public function simpleLinks(string $group = 'default', string $template = 'default_simple'): string { $this->ensureGroup($group); return $this->displayLinks($group, $template); } /** * Allows for a simple, manual, form of pagination where all of the data * is provided by the user. The URL is the current URI. * * @param string $template The output template alias to render. * @param int $segment (whether page number is provided by URI segment) * @param string|null $group optional group (i.e. if we'd like to define custom path) */ public function makeLinks(int $page, ?int $perPage, int $total, string $template = 'default_full', int $segment = 0, ?string $group = 'default'): string { $group = $group === '' ? 'default' : $group; $this->store($group, $page, $perPage ?? $this->config->perPage, $total, $segment); return $this->displayLinks($group, $template); } /** * Does the actual work of displaying the view file. Used internally * by links(), simpleLinks(), and makeLinks(). */ protected function displayLinks(string $group, string $template): string { if (! array_key_exists($template, $this->config->templates)) { throw PagerException::forInvalidTemplate($template); } $pager = new PagerRenderer($this->getDetails($group)); return $this->view->setVar('pager', $pager) ->render($this->config->templates[$template]); } /** * Stores a set of pagination data for later display. Most commonly used * by the model to automate the process. * * @return $this */ public function store(string $group, int $page, ?int $perPage, int $total, int $segment = 0) { if ($segment !== 0) { $this->setSegment($segment, $group); } $this->ensureGroup($group, $perPage); if ($segment > 0 && $this->groups[$group]['currentPage'] > 0) { $page = $this->groups[$group]['currentPage']; } $perPage ??= $this->config->perPage; $pageCount = (int) ceil($total / $perPage); $this->groups[$group]['currentPage'] = $page > $pageCount ? $pageCount : $page; $this->groups[$group]['perPage'] = $perPage; $this->groups[$group]['total'] = $total; $this->groups[$group]['pageCount'] = $pageCount; return $this; } /** * Sets segment for a group. * * @return $this */ public function setSegment(int $number, string $group = 'default') { $this->segment[$group] = $number; // Recalculate current page $this->ensureGroup($group); $this->calculateCurrentPage($group); return $this; } /** * Sets the path that an aliased group of links will use. * * @return $this */ public function setPath(string $path, string $group = 'default') { $this->ensureGroup($group); $this->groups[$group]['uri']->setPath($path); return $this; } /** * Returns the total number of items in data store. */ public function getTotal(string $group = 'default'): int { $this->ensureGroup($group); return $this->groups[$group]['total']; } /** * Returns the total number of pages. */ public function getPageCount(string $group = 'default'): int { $this->ensureGroup($group); return $this->groups[$group]['pageCount']; } /** * Returns the number of the current page of results. */ public function getCurrentPage(string $group = 'default'): int { $this->ensureGroup($group); return $this->groups[$group]['currentPage'] ?: 1; } /** * Tells whether this group of results has any more pages of results. */ public function hasMore(string $group = 'default'): bool { $this->ensureGroup($group); return ($this->groups[$group]['currentPage'] * $this->groups[$group]['perPage']) < $this->groups[$group]['total']; } /** * Returns the last page, if we have a total that we can calculate with. * * @return int|null */ public function getLastPage(string $group = 'default') { $this->ensureGroup($group); if (! is_numeric($this->groups[$group]['total']) || ! is_numeric($this->groups[$group]['perPage'])) { return null; } return (int) ceil($this->groups[$group]['total'] / $this->groups[$group]['perPage']); } /** * Determines the first page # that should be shown. */ public function getFirstPage(string $group = 'default'): int { $this->ensureGroup($group); // @todo determine based on a 'surroundCount' value return 1; } /** * Returns the URI for a specific page for the specified group. * * @return string|URI */ public function getPageURI(?int $page = null, string $group = 'default', bool $returnObject = false) { $this->ensureGroup($group); /** * @var URI $uri */ $uri = $this->groups[$group]['uri']; $segment = $this->segment[$group] ?? 0; if ($segment) { $uri->setSegment($segment, $page); } else { $uri->addQuery($this->groups[$group]['pageSelector'], $page); } if ($this->only !== null) { $query = array_intersect_key($_GET, array_flip($this->only)); if (! $segment) { $query[$this->groups[$group]['pageSelector']] = $page; } $uri->setQueryArray($query); } return $returnObject ? $uri : URI::createURIString( $uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery(), $uri->getFragment(), ); } /** * Returns the full URI to the next page of results, or null. * * @return string|null */ public function getNextPageURI(string $group = 'default', bool $returnObject = false) { $this->ensureGroup($group); $last = $this->getLastPage($group); $curr = $this->getCurrentPage($group); $page = null; if (! empty($last) && $curr !== 0 && $last === $curr) { return null; } if ($last > $curr) { $page = $curr + 1; } return $this->getPageURI($page, $group, $returnObject); } /** * Returns the full URL to the previous page of results, or null. * * @return string|null */ public function getPreviousPageURI(string $group = 'default', bool $returnObject = false) { $this->ensureGroup($group); $first = $this->getFirstPage($group); $curr = $this->getCurrentPage($group); $page = null; if ($first !== 0 && $curr !== 0 && $first === $curr) { return null; } if ($first < $curr) { $page = $curr - 1; } return $this->getPageURI($page, $group, $returnObject); } /** * Returns the number of results per page that should be shown. */ public function getPerPage(string $group = 'default'): int { $this->ensureGroup($group); return (int) $this->groups[$group]['perPage']; } /** * Returns an array with details about the results, including * total, per_page, current_page, last_page, next_url, prev_url, from, to. * Does not include the actual data. This data is suitable for adding * a 'data' object to with the result set and converting to JSON. */ public function getDetails(string $group = 'default'): array { if (! array_key_exists($group, $this->groups)) { throw PagerException::forInvalidPaginationGroup($group); } $newGroup = $this->groups[$group]; $newGroup['next'] = $this->getNextPageURI($group); $newGroup['previous'] = $this->getPreviousPageURI($group); $newGroup['segment'] = $this->segment[$group] ?? 0; return $newGroup; } /** * Sets only allowed queries on pagination links. */ public function only(array $queries): self { $this->only = $queries; return $this; } /** * Ensures that an array exists for the group specified. * * @return void */ protected function ensureGroup(string $group, ?int $perPage = null) { if (array_key_exists($group, $this->groups)) { return; } $this->groups[$group] = [ 'currentUri' => clone current_url(true), 'uri' => clone current_url(true), 'hasMore' => false, 'total' => null, 'perPage' => $perPage ?? $this->config->perPage, 'pageCount' => 1, 'pageSelector' => $group === 'default' ? 'page' : 'page_' . $group, ]; $this->calculateCurrentPage($group); if ($_GET !== []) { $this->groups[$group]['uri'] = $this->groups[$group]['uri']->setQueryArray($_GET); } } /** * Calculating the current page * * @return void */ protected function calculateCurrentPage(string $group) { if (array_key_exists($group, $this->segment)) { try { $this->groups[$group]['currentPage'] = (int) $this->groups[$group]['currentUri'] ->setSilent(false)->getSegment($this->segment[$group]); } catch (HTTPException) { $this->groups[$group]['currentPage'] = 1; } } else { $pageSelector = $this->groups[$group]['pageSelector']; $page = (int) ($_GET[$pageSelector] ?? 1); $this->groups[$group]['currentPage'] = $page < 1 ? 1 : $page; } } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Pager/Exceptions/PagerException.php
system/Pager/Exceptions/PagerException.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Pager\Exceptions; use CodeIgniter\Exceptions\FrameworkException; class PagerException extends FrameworkException { /** * Throws when the template is invalid. * * @return static */ public static function forInvalidTemplate(?string $template = null) { return new static(lang('Pager.invalidTemplate', [$template])); } /** * Throws when the group is invalid. * * @return static */ public static function forInvalidPaginationGroup(?string $group = null) { return new static(lang('Pager.invalidPaginationGroup', [$group])); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Pager/Views/default_full.php
system/Pager/Views/default_full.php
<?php use CodeIgniter\Pager\PagerRenderer; /** * @var PagerRenderer $pager */ $pager->setSurroundCount(2); ?> <nav aria-label="<?= lang('Pager.pageNavigation') ?>"> <ul class="pagination"> <?php if ($pager->hasPrevious()) : ?> <li> <a href="<?= $pager->getFirst() ?>" aria-label="<?= lang('Pager.first') ?>"> <span aria-hidden="true"><?= lang('Pager.first') ?></span> </a> </li> <li> <a href="<?= $pager->getPrevious() ?>" aria-label="<?= lang('Pager.previous') ?>"> <span aria-hidden="true"><?= lang('Pager.previous') ?></span> </a> </li> <?php endif ?> <?php foreach ($pager->links() as $link) : ?> <li <?= $link['active'] ? 'class="active"' : '' ?>> <a href="<?= $link['uri'] ?>"> <?= $link['title'] ?> </a> </li> <?php endforeach ?> <?php if ($pager->hasNext()) : ?> <li> <a href="<?= $pager->getNext() ?>" aria-label="<?= lang('Pager.next') ?>"> <span aria-hidden="true"><?= lang('Pager.next') ?></span> </a> </li> <li> <a href="<?= $pager->getLast() ?>" aria-label="<?= lang('Pager.last') ?>"> <span aria-hidden="true"><?= lang('Pager.last') ?></span> </a> </li> <?php endif ?> </ul> </nav>
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Pager/Views/default_simple.php
system/Pager/Views/default_simple.php
<?php use CodeIgniter\Pager\PagerRenderer; /** * @var PagerRenderer $pager */ $pager->setSurroundCount(0); ?> <nav> <ul class="pager"> <li <?= $pager->hasPrevious() ? '' : 'class="disabled"' ?>> <a href="<?= $pager->getPrevious() ?? '#' ?>" aria-label="<?= lang('Pager.previous') ?>"> <span aria-hidden="true"><?= lang('Pager.newer') ?></span> </a> </li> <li <?= $pager->hasNext() ? '' : 'class="disabled"' ?>> <a href="<?= $pager->getNext() ?? '#' ?>" aria-label="<?= lang('Pager.next') ?>"> <span aria-hidden="true"><?= lang('Pager.older') ?></span> </a> </li> </ul> </nav>
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Pager/Views/default_head.php
system/Pager/Views/default_head.php
<?php /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ use CodeIgniter\Pager\PagerRenderer; /** * @var PagerRenderer $pager */ $pager->setSurroundCount(0); if ($pager->hasPrevious()) { echo '<link rel="prev" href="' . $pager->getPrevious() . '">' . PHP_EOL; } echo '<link rel="canonical" href="' . $pager->getCurrent() . '">' . PHP_EOL; if ($pager->hasNext()) { echo '<link rel="next" href="' . $pager->getNext() . '">' . PHP_EOL; }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Filters/Cors.php
system/Filters/Cors.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Filters; use CodeIgniter\HTTP\Cors as CorsService; use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; /** * @see \CodeIgniter\Filters\CorsTest */ class Cors implements FilterInterface { private ?CorsService $cors = null; /** * @testTag $config is used for testing purposes only. * * @param array{ * allowedOrigins?: list<string>, * allowedOriginsPatterns?: list<string>, * supportsCredentials?: bool, * allowedHeaders?: list<string>, * exposedHeaders?: list<string>, * allowedMethods?: list<string>, * maxAge?: int, * } $config */ public function __construct(array $config = []) { if ($config !== []) { $this->cors = new CorsService($config); } } /** * @param list<string>|null $arguments * * @return ResponseInterface|null */ public function before(RequestInterface $request, $arguments = null) { if (! $request instanceof IncomingRequest) { return null; } $this->createCorsService($arguments); /** @var ResponseInterface $response */ $response = service('response'); if ($this->cors->isPreflightRequest($request)) { $response = $this->cors->handlePreflightRequest($request, $response); // Always adds `Vary: Access-Control-Request-Method` header for cacheability. // If there is an intermediate cache server such as a CDN, if a plain // OPTIONS request is sent, it may be cached. But valid preflight requests // have this header, so it will be cached separately. $response->appendHeader('Vary', 'Access-Control-Request-Method'); return $response; } if ($request->is('OPTIONS')) { // Always adds `Vary: Access-Control-Request-Method` header for cacheability. // If there is an intermediate cache server such as a CDN, if a plain // OPTIONS request is sent, it may be cached. But valid preflight requests // have this header, so it will be cached separately. $response->appendHeader('Vary', 'Access-Control-Request-Method'); } $this->cors->addResponseHeaders($request, $response); return null; } /** * @param list<string>|null $arguments */ private function createCorsService(?array $arguments): void { $this->cors ??= ($arguments === null) ? CorsService::factory() : CorsService::factory($arguments[0]); } /** * @param list<string>|null $arguments */ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { if (! $request instanceof IncomingRequest) { return null; } $this->createCorsService($arguments); if ($this->cors->hasResponseHeaders($request, $response)) { return null; } // Always adds `Vary: Access-Control-Request-Method` header for cacheability. // If there is an intermediate cache server such as a CDN, if a plain // OPTIONS request is sent, it may be cached. But valid preflight requests // have this header, so it will be cached separately. if ($request->is('OPTIONS')) { $response->appendHeader('Vary', 'Access-Control-Request-Method'); } return $this->cors->addResponseHeaders($request, $response); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Filters/FilterInterface.php
system/Filters/FilterInterface.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Filters; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; /** * Filter interface */ interface FilterInterface { /** * Do whatever processing this filter needs to do. * By default it should not return anything during * normal execution. However, when an abnormal state * is found, it should return an instance of * CodeIgniter\HTTP\Response. If it does, script * execution will end and that Response will be * sent back to the client, allowing for error pages, * redirects, etc. * * @param list<string>|null $arguments * * @return RequestInterface|ResponseInterface|string|null */ public function before(RequestInterface $request, $arguments = null); /** * Allows After filters to inspect and modify the response * object as needed. This method does not allow any way * to stop execution of other after filters, short of * throwing an Exception or Error. * * @param list<string>|null $arguments * * @return ResponseInterface|null */ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null); }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Filters/CSRF.php
system/Filters/CSRF.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Filters; use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\RedirectResponse; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\Security\Exceptions\SecurityException; use CodeIgniter\Security\Security; /** * CSRF filter. * * This filter is not intended to be used from the command line. * * @codeCoverageIgnore * @see \CodeIgniter\Filters\CSRFTest */ class CSRF implements FilterInterface { /** * CSRF verification. * * @param list<string>|null $arguments * * @return RedirectResponse|null * * @throws SecurityException */ public function before(RequestInterface $request, $arguments = null) { if (! $request instanceof IncomingRequest) { return null; } /** @var Security $security */ $security = service('security'); try { $security->verify($request); } catch (SecurityException $e) { if ($security->shouldRedirect() && ! $request->isAJAX()) { return redirect()->back()->with('error', $e->getMessage()); } throw $e; } return null; } /** * We don't have anything to do here. * * @param list<string>|null $arguments */ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { return null; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Filters/PageCache.php
system/Filters/PageCache.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Filters; use CodeIgniter\Cache\ResponseCache; use CodeIgniter\HTTP\CLIRequest; use CodeIgniter\HTTP\DownloadResponse; use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\RedirectResponse; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; /** * Page Cache filter */ class PageCache implements FilterInterface { private readonly ResponseCache $pageCache; public function __construct() { $this->pageCache = service('responsecache'); } /** * Checks page cache and return if found. * * @param array|null $arguments * * @return ResponseInterface|null */ public function before(RequestInterface $request, $arguments = null) { assert($request instanceof CLIRequest || $request instanceof IncomingRequest); $response = service('response'); $cachedResponse = $this->pageCache->get($request, $response); if ($cachedResponse instanceof ResponseInterface) { return $cachedResponse; } return null; } /** * Cache the page. * * @param array|null $arguments */ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { assert($request instanceof CLIRequest || $request instanceof IncomingRequest); if ( ! $response instanceof DownloadResponse && ! $response instanceof RedirectResponse ) { // Cache it without the performance metrics replaced // so that we can have live speed updates along the way. // Must be run after filters to preserve the Response headers. $this->pageCache->make($request, $response); return $response; } return null; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Filters/ForceHTTPS.php
system/Filters/ForceHTTPS.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Filters; use CodeIgniter\HTTP\Exceptions\RedirectException; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Config\App; /** * Force HTTPS filter */ class ForceHTTPS implements FilterInterface { /** * Force Secure Site Access? If the config value 'forceGlobalSecureRequests' * is true, will enforce that all requests to this site are made through * HTTPS. Will redirect the user to the current page with HTTPS, as well * as set the HTTP Strict Transport Security (HSTS) header for those browsers * that support it. * * @param array|null $arguments * * @return ResponseInterface|null */ public function before(RequestInterface $request, $arguments = null) { $config = config(App::class); if ($config->forceGlobalSecureRequests !== true) { return null; } $response = service('response'); try { force_https(YEAR, $request, $response); } catch (RedirectException $e) { return $e->getResponse(); } return null; } /** * We don't have anything to do here. * * @param array|null $arguments */ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { return null; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Filters/InvalidChars.php
system/Filters/InvalidChars.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Filters; use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\Security\Exceptions\SecurityException; /** * InvalidChars filter. * * Check if user input data ($_GET, $_POST, $_COOKIE, php://input) do not contain * invalid characters: * - invalid UTF-8 characters * - control characters except line break and tab code * * @see \CodeIgniter\Filters\InvalidCharsTest */ class InvalidChars implements FilterInterface { /** * Data source * * @var string */ protected $source; /** * Regular expressions for valid control codes * * @var string */ protected $controlCodeRegex = '/\A[\r\n\t[:^cntrl:]]*\z/u'; /** * Check invalid characters. * * @param list<string>|null $arguments */ public function before(RequestInterface $request, $arguments = null) { if (! $request instanceof IncomingRequest) { return null; } $data = [ 'get' => $request->getGet(), 'post' => $request->getPost(), 'cookie' => $request->getCookie(), 'rawInput' => $request->getRawInput(), ]; foreach ($data as $source => $values) { $this->source = $source; $this->checkEncoding($values); $this->checkControl($values); } return null; } /** * We don't have anything to do here. * * @param list<string>|null $arguments */ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { return null; } /** * Check the character encoding is valid UTF-8. * * @param array|string $value * * @return array|string */ protected function checkEncoding($value) { if (is_array($value)) { array_map($this->checkEncoding(...), $value); return $value; } if (mb_check_encoding($value, 'UTF-8')) { return $value; } throw SecurityException::forInvalidUTF8Chars($this->source, $value); } /** * Check for the presence of control characters except line breaks and tabs. * * @param array|string $value * * @return array|string */ protected function checkControl($value) { if (is_array($value)) { array_map($this->checkControl(...), $value); return $value; } if (preg_match($this->controlCodeRegex, $value) === 1) { return $value; } throw SecurityException::forInvalidControlChars($this->source, $value); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Filters/Filters.php
system/Filters/Filters.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Filters; use CodeIgniter\Config\Filters as BaseFiltersConfig; use CodeIgniter\Filters\Exceptions\FilterException; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Config\Feature; use Config\Filters as FiltersConfig; use Config\Modules; /** * Filters * * @see \CodeIgniter\Filters\FiltersTest */ class Filters { /** * The Config\Filters instance * * @var FiltersConfig */ protected $config; /** * The active IncomingRequest or CLIRequest * * @var RequestInterface */ protected $request; /** * The active Response instance * * @var ResponseInterface */ protected $response; /** * The Config\Modules instance * * @var Modules */ protected $modules; /** * Whether we've done initial processing on the filter lists. * * @var bool */ protected $initialized = false; /** * The filter list to execute for the current request (URI path). * * This property is for display. Use $filtersClass to execute filters. * This does not include "Required Filters". * * [ * 'before' => [ * 'alias', * 'alias:arg1', * 'alias:arg1,arg2', * ], * 'after' => [ * 'alias', * 'alias:arg1', * 'alias:arg1,arg2', * ], * ] * * @var array{ * before: list<string>, * after: list<string> * } */ protected $filters = [ 'before' => [], 'after' => [], ]; /** * The collection of filter classnames and their arguments to execute for * the current request (URI path). * * This does not include "Required Filters". * * [ * 'before' => [ * [classname, arguments], * ], * 'after' => [ * [classname, arguments], * ], * ] * * @var array{ * before: list<array{0: class-string, 1: list<string>}>, * after: list<array{0: class-string, 1: list<string>}> * } */ protected $filtersClass = [ 'before' => [], 'after' => [], ]; /** * List of filter class instances. * * @var array<class-string, FilterInterface> [classname => instance] */ protected array $filterClassInstances = []; /** * Any arguments to be passed to filters. * * @var array<string, list<string>|null> [name => params] * * @deprecated 4.6.0 No longer used. */ protected $arguments = []; /** * Any arguments to be passed to filtersClass. * * @var array<class-string, list<string>|null> [classname => arguments] * * @deprecated 4.6.0 No longer used. */ protected $argumentsClass = []; /** * Constructor. * * @param FiltersConfig $config */ public function __construct($config, RequestInterface $request, ResponseInterface $response, ?Modules $modules = null) { $this->config = $config; $this->request = &$request; $this->setResponse($response); $this->modules = $modules instanceof Modules ? $modules : new Modules(); if ($this->modules->shouldDiscover('filters')) { $this->discoverFilters(); } } /** * If discoverFilters is enabled in Config then system will try to * auto-discover custom filters files in namespaces and allow access to * the config object via the variable $filters as with the routes file. * * Sample: * $filters->aliases['custom-auth'] = \Acme\Blob\Filters\BlobAuth::class; * * @deprecated 4.4.2 Use Registrar instead. */ private function discoverFilters(): void { $locator = service('locator'); // for access by custom filters $filters = $this->config; $files = $locator->search('Config/Filters.php'); foreach ($files as $file) { // The $file may not be a class file. $className = $locator->getClassname($file); // Don't include our main Filter config again... if ($className === FiltersConfig::class || $className === BaseFiltersConfig::class) { continue; } include $file; } } /** * Set the response explicitly. * * @return void */ public function setResponse(ResponseInterface $response) { $this->response = $response; } /** * Runs through all the filters (except "Required Filters") for the specified * URI and position. * * @param string $uri URI path relative to baseURL * @param 'after'|'before' $position * * @return RequestInterface|ResponseInterface|string|null * * @throws FilterException */ public function run(string $uri, string $position = 'before') { $this->initialize(strtolower($uri)); if ($position === 'before') { return $this->runBefore($this->filtersClass[$position]); } // After return $this->runAfter($this->filtersClass[$position]); } /** * @param list<array{0: class-string, 1: list<string>}> $filterClassList [[classname, arguments], ...] * * @return RequestInterface|ResponseInterface|string */ private function runBefore(array $filterClassList) { foreach ($filterClassList as $filterClassInfo) { $className = $filterClassInfo[0]; $arguments = ($filterClassInfo[1] === []) ? null : $filterClassInfo[1]; $instance = $this->createFilter($className); $result = $instance->before($this->request, $arguments); if ($result instanceof RequestInterface) { $this->request = $result; continue; } // If the response object was sent back, // then send it and quit. if ($result instanceof ResponseInterface) { // short circuit - bypass any other filters return $result; } // Ignore an empty result if (empty($result)) { continue; } return $result; } return $this->request; } /** * @param list<array{0: class-string, 1: list<string>}> $filterClassList [[classname, arguments], ...] */ private function runAfter(array $filterClassList): ResponseInterface { foreach ($filterClassList as $filterClassInfo) { $className = $filterClassInfo[0]; $arguments = ($filterClassInfo[1] === []) ? null : $filterClassInfo[1]; $instance = $this->createFilter($className); $result = $instance->after($this->request, $this->response, $arguments); if ($result instanceof ResponseInterface) { $this->response = $result; continue; } } return $this->response; } /** * @param class-string $className */ private function createFilter(string $className): FilterInterface { if (isset($this->filterClassInstances[$className])) { return $this->filterClassInstances[$className]; } $instance = new $className(); if (! $instance instanceof FilterInterface) { throw FilterException::forIncorrectInterface($instance::class); } $this->filterClassInstances[$className] = $instance; return $instance; } /** * Returns the "Required Filters" class list. * * @param 'after'|'before' $position * * @return list<array{0: class-string, 1: list<string>}> [[classname, arguments], ...] */ public function getRequiredClasses(string $position): array { [$filters, $aliases] = $this->getRequiredFilters($position); if ($filters === []) { return []; } $filterClassList = []; foreach ($filters as $alias) { if (is_array($aliases[$alias])) { foreach ($this->config->aliases[$alias] as $class) { $filterClassList[] = [$class, []]; } } else { $filterClassList[] = [$aliases[$alias], []]; } } return $filterClassList; } /** * Runs "Required Filters" for the specified position. * * @param 'after'|'before' $position * * @return RequestInterface|ResponseInterface|string|null * * @throws FilterException * * @internal */ public function runRequired(string $position = 'before') { $filterClassList = $this->getRequiredClasses($position); if ($filterClassList === []) { return $position === 'before' ? $this->request : $this->response; } if ($position === 'before') { return $this->runBefore($filterClassList); } // After return $this->runAfter($filterClassList); } /** * Returns "Required Filters" for the specified position. * * @param 'after'|'before' $position * * @internal */ public function getRequiredFilters(string $position = 'before'): array { // For backward compatibility. For users who do not update Config\Filters. if (! isset($this->config->required[$position])) { $baseConfig = config(BaseFiltersConfig::class); // @phpstan-ignore-line $filters = $baseConfig->required[$position]; $aliases = $baseConfig->aliases; } else { $filters = $this->config->required[$position]; $aliases = $this->config->aliases; } if ($filters === []) { return [[], $aliases]; } if ($position === 'after') { if (in_array('toolbar', $this->filters['after'], true)) { // It was already run in globals filters. So remove it. $filters = $this->setToolbarToLast($filters, true); } else { // Set the toolbar filter to the last position to be executed $filters = $this->setToolbarToLast($filters); } } foreach ($filters as $alias) { if (! array_key_exists($alias, $aliases)) { throw FilterException::forNoAlias($alias); } } return [$filters, $aliases]; } /** * Set the toolbar filter to the last position to be executed. * * @param list<string> $filters `after` filter array * @param bool $remove if true, remove `toolbar` filter */ private function setToolbarToLast(array $filters, bool $remove = false): array { $afters = []; $found = false; foreach ($filters as $alias) { if ($alias === 'toolbar') { $found = true; continue; } $afters[] = $alias; } if ($found && ! $remove) { $afters[] = 'toolbar'; } return $afters; } /** * Runs through our list of filters provided by the configuration * object to get them ready for use, including getting uri masks * to proper regex, removing those we can from the possibilities * based on HTTP method, etc. * * The resulting $this->filters is an array of only filters * that should be applied to this request. * * We go ahead and process the entire tree because we'll need to * run through both a before and after and don't want to double * process the rows. * * @param string|null $uri URI path relative to baseURL (all lowercase) * * @TODO We don't need to accept null as $uri. * * @return Filters * * @testTag Only for test code. The run() calls this, so you don't need to * call this in your app. */ public function initialize(?string $uri = null) { if ($this->initialized === true) { return $this; } // Decode URL-encoded string $uri = urldecode($uri ?? ''); $oldFilterOrder = config(Feature::class)->oldFilterOrder ?? false; if ($oldFilterOrder) { $this->processGlobals($uri); $this->processMethods(); $this->processFilters($uri); } else { $this->processFilters($uri); $this->processMethods(); $this->processGlobals($uri); } // Set the toolbar filter to the last position to be executed $this->filters['after'] = $this->setToolbarToLast($this->filters['after']); // Since some filters like rate limiters rely on being executed once a request, // we filter em here. $this->filters['before'] = array_unique($this->filters['before']); $this->filters['after'] = array_unique($this->filters['after']); $this->processAliasesToClass('before'); $this->processAliasesToClass('after'); $this->initialized = true; return $this; } /** * Restores instance to its pre-initialized state. * Most useful for testing so the service can be * re-initialized to a different path. */ public function reset(): self { $this->initialized = false; $this->arguments = $this->argumentsClass = []; $this->filters = $this->filtersClass = [ 'before' => [], 'after' => [], ]; return $this; } /** * Returns the processed filters array. * This does not include "Required Filters". * * @return array{ * before: list<string>, * after: list<string> * } */ public function getFilters(): array { return $this->filters; } /** * Returns the filtersClass array. * This does not include "Required Filters". * * @return array{ * before: list<array{0: class-string, 1: list<string>}>, * after: list<array{0: class-string, 1: list<string>}> * } */ public function getFiltersClass(): array { return $this->filtersClass; } /** * Adds a new alias to the config file. * MUST be called prior to initialize(); * Intended for use within routes files. * * @param 'after'|'before' $position * * @return $this */ public function addFilter(string $class, ?string $alias = null, string $position = 'before', string $section = 'globals') { $alias ??= md5($class); if (! isset($this->config->{$section})) { $this->config->{$section} = []; } if (! isset($this->config->{$section}[$position])) { $this->config->{$section}[$position] = []; } $this->config->aliases[$alias] = $class; $this->config->{$section}[$position][] = $alias; return $this; } /** * Ensures that a specific filter is on and enabled for the current request. * * Filters can have "arguments". This is done by placing a colon immediately * after the filter name, followed by a comma-separated list of arguments that * are passed to the filter when executed. * * @param string $filter filter_name or filter_name:arguments like 'role:admin,manager' * or filter classname. * @param 'after'|'before' $position */ private function enableFilter(string $filter, string $position = 'before'): void { // Normalize the arguments. [$alias, $arguments] = $this->getCleanName($filter); $filter = ($arguments === []) ? $alias : $alias . ':' . implode(',', $arguments); if (class_exists($alias)) { $this->config->aliases[$alias] = $alias; } elseif (! array_key_exists($alias, $this->config->aliases)) { throw FilterException::forNoAlias($alias); } if (! isset($this->filters[$position][$filter])) { $this->filters[$position][] = $filter; } // Since some filters like rate limiters rely on being executed once a request, // we filter em here. $this->filters[$position] = array_unique($this->filters[$position]); } /** * Get clean name and arguments * * @param string $filter filter_name or filter_name:arguments like 'role:admin,manager' * * @return array{0: string, 1: list<string>} [name, arguments] */ private function getCleanName(string $filter): array { $arguments = []; if (! str_contains($filter, ':')) { return [$filter, $arguments]; } [$alias, $arguments] = explode(':', $filter); $arguments = explode(',', $arguments); array_walk($arguments, static function (&$item): void { $item = trim($item); }); return [$alias, $arguments]; } /** * Ensures that specific filters are on and enabled for the current request. * * Filters can have "arguments". This is done by placing a colon immediately * after the filter name, followed by a comma-separated list of arguments that * are passed to the filter when executed. * * @param list<string> $filters filter_name or filter_name:arguments like 'role:admin,manager' * * @return Filters */ public function enableFilters(array $filters, string $when = 'before') { foreach ($filters as $filter) { $this->enableFilter($filter, $when); } return $this; } /** * Returns the arguments for a specified key, or all. * * @return array<string, string>|string * * @deprecated 4.6.0 Already does not work. */ public function getArguments(?string $key = null) { return ((string) $key === '') ? $this->arguments : $this->arguments[$key]; } // -------------------------------------------------------------------- // Processors // -------------------------------------------------------------------- /** * Add any applicable (not excluded) global filter settings to the mix. * * @param string|null $uri URI path relative to baseURL (all lowercase) * * @return void */ protected function processGlobals(?string $uri = null) { if (! isset($this->config->globals) || ! is_array($this->config->globals)) { return; } $uri = strtolower(trim($uri ?? '', '/ ')); // Add any global filters, unless they are excluded for this URI $sets = ['before', 'after']; $filters = []; foreach ($sets as $set) { if (isset($this->config->globals[$set])) { // look at each alias in the group foreach ($this->config->globals[$set] as $alias => $rules) { $keep = true; if (is_array($rules)) { // see if it should be excluded if (isset($rules['except'])) { // grab the exclusion rules $check = $rules['except']; if ($this->checkExcept($uri, $check)) { $keep = false; } } } else { $alias = $rules; // simple name of filter to apply } if ($keep) { $filters[$set][] = $alias; } } } } if (isset($filters['before'])) { $oldFilterOrder = config(Feature::class)->oldFilterOrder ?? false; if ($oldFilterOrder) { $this->filters['before'] = array_merge($this->filters['before'], $filters['before']); } else { $this->filters['before'] = array_merge($filters['before'], $this->filters['before']); } } if (isset($filters['after'])) { $this->filters['after'] = array_merge($this->filters['after'], $filters['after']); } } /** * Add any method-specific filters to the mix. * * @return void */ protected function processMethods() { if (! isset($this->config->methods) || ! is_array($this->config->methods)) { return; } $method = $this->request->getMethod(); $found = false; if (array_key_exists($method, $this->config->methods)) { $found = true; } // Checks lowercase HTTP method for backward compatibility. // @deprecated 4.5.0 // @TODO remove this in the future. elseif (array_key_exists(strtolower($method), $this->config->methods)) { @trigger_error( 'Setting lowercase HTTP method key "' . strtolower($method) . '" is deprecated.' . ' Use uppercase HTTP method like "' . strtoupper($method) . '".', E_USER_DEPRECATED, ); $found = true; $method = strtolower($method); } if ($found) { $oldFilterOrder = config(Feature::class)->oldFilterOrder ?? false; if ($oldFilterOrder) { $this->filters['before'] = array_merge($this->filters['before'], $this->config->methods[$method]); } else { $this->filters['before'] = array_merge($this->config->methods[$method], $this->filters['before']); } } } /** * Add any applicable configured filters to the mix. * * @param string|null $uri URI path relative to baseURL (all lowercase) * * @return void */ protected function processFilters(?string $uri = null) { if (! isset($this->config->filters) || $this->config->filters === []) { return; } $uri = strtolower(trim($uri, '/ ')); // Add any filters that apply to this URI $filters = []; foreach ($this->config->filters as $filter => $settings) { // Normalize the arguments. [$alias, $arguments] = $this->getCleanName($filter); $filter = ($arguments === []) ? $alias : $alias . ':' . implode(',', $arguments); // Look for inclusion rules if (isset($settings['before'])) { $path = $settings['before']; if ($this->pathApplies($uri, $path)) { $filters['before'][] = $filter; } } if (isset($settings['after'])) { $path = $settings['after']; if ($this->pathApplies($uri, $path)) { $filters['after'][] = $filter; } } } $oldFilterOrder = config(Feature::class)->oldFilterOrder ?? false; if (isset($filters['before'])) { if ($oldFilterOrder) { $this->filters['before'] = array_merge($this->filters['before'], $filters['before']); } else { $this->filters['before'] = array_merge($filters['before'], $this->filters['before']); } } if (isset($filters['after'])) { if (! $oldFilterOrder) { $filters['after'] = array_reverse($filters['after']); } $this->filters['after'] = array_merge($this->filters['after'], $filters['after']); } } /** * Maps filter aliases to the equivalent filter classes * * @param 'after'|'before' $position * * @return void * * @throws FilterException */ protected function processAliasesToClass(string $position) { $filterClassList = []; foreach ($this->filters[$position] as $filter) { // Get arguments and clean alias [$alias, $arguments] = $this->getCleanName($filter); if (! array_key_exists($alias, $this->config->aliases)) { throw FilterException::forNoAlias($alias); } if (is_array($this->config->aliases[$alias])) { foreach ($this->config->aliases[$alias] as $class) { $filterClassList[] = [$class, $arguments]; } } else { $filterClassList[] = [$this->config->aliases[$alias], $arguments]; } } if ($position === 'before') { $this->filtersClass[$position] = array_merge($filterClassList, $this->filtersClass[$position]); } else { $this->filtersClass[$position] = array_merge($this->filtersClass[$position], $filterClassList); } } /** * Check paths for match for URI * * @param string $uri URI to test against * @param array|string $paths The path patterns to test * * @return bool True if any of the paths apply to the URI */ private function pathApplies(string $uri, $paths) { // empty path matches all if ($paths === '' || $paths === []) { return true; } // make sure the paths are iterable if (is_string($paths)) { $paths = [$paths]; } return $this->checkPseudoRegex($uri, $paths); } /** * Check except paths * * @param string $uri URI path relative to baseURL (all lowercase) * @param array|string $paths The except path patterns * * @return bool True if the URI matches except paths. */ private function checkExcept(string $uri, $paths): bool { // empty array does not match anything if ($paths === []) { return false; } // make sure the paths are iterable if (is_string($paths)) { $paths = [$paths]; } return $this->checkPseudoRegex($uri, $paths); } /** * Check the URI path as pseudo-regex * * @param string $uri URI path relative to baseURL (all lowercase, URL-decoded) * @param array $paths The except path patterns */ private function checkPseudoRegex(string $uri, array $paths): bool { // treat each path as pseudo-regex foreach ($paths as $path) { // need to escape path separators $path = str_replace('/', '\/', trim($path, '/ ')); // need to make pseudo wildcard real $path = strtolower(str_replace('*', '.*', $path)); // Does this rule apply here? if (preg_match('#\A' . $path . '\z#u', $uri, $match) === 1) { return true; } } return false; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Filters/Honeypot.php
system/Filters/Honeypot.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Filters; use CodeIgniter\Honeypot\Exceptions\HoneypotException; use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; /** * Honeypot filter * * @see \CodeIgniter\Filters\HoneypotTest */ class Honeypot implements FilterInterface { /** * Checks if Honeypot field is empty, if not then the * requester is a bot * * @param list<string>|null $arguments * * @throws HoneypotException */ public function before(RequestInterface $request, $arguments = null) { if (! $request instanceof IncomingRequest) { return null; } if (service('honeypot')->hasContent($request)) { throw HoneypotException::isBot(); } return null; } /** * Attach a honeypot to the current response. * * @param list<string>|null $arguments */ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { service('honeypot')->attachHoneypot($response); return null; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Filters/SecureHeaders.php
system/Filters/SecureHeaders.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Filters; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; /** * Add Common Security Headers * * @see \CodeIgniter\Filters\SecureHeadersTest */ class SecureHeaders implements FilterInterface { /** * @var array<string, string> */ protected $headers = [ // https://owasp.org/www-project-secure-headers/#x-frame-options 'X-Frame-Options' => 'SAMEORIGIN', // https://owasp.org/www-project-secure-headers/#x-content-type-options 'X-Content-Type-Options' => 'nosniff', // https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/jj542450(v=vs.85)#the-noopen-directive 'X-Download-Options' => 'noopen', // https://owasp.org/www-project-secure-headers/#x-permitted-cross-domain-policies 'X-Permitted-Cross-Domain-Policies' => 'none', // https://owasp.org/www-project-secure-headers/#referrer-policy 'Referrer-Policy' => 'same-origin', // https://owasp.org/www-project-secure-headers/#x-xss-protection // If you do not need to support legacy browsers, it is recommended that you use // Content-Security-Policy without allowing unsafe-inline scripts instead. // 'X-XSS-Protection' => '1; mode=block', ]; /** * We don't have anything to do here. * * @param list<string>|null $arguments */ public function before(RequestInterface $request, $arguments = null) { return null; } /** * Add security headers. * * @param list<string>|null $arguments */ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { foreach ($this->headers as $header => $value) { $response->setHeader($header, $value); } return $response; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Filters/PerformanceMetrics.php
system/Filters/PerformanceMetrics.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Filters; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; /** * Performance Metrics filter */ class PerformanceMetrics implements FilterInterface { /** * We don't need to do anything here. * * @param array|null $arguments */ public function before(RequestInterface $request, $arguments = null) { return null; } /** * Replaces the performance metrics. * * @param array|null $arguments */ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { $body = $response->getBody(); if ($body !== null) { $benchmark = service('timer'); $output = str_replace( [ '{elapsed_time}', '{memory_usage}', ], [ (string) $benchmark->getElapsedTime('total_execution'), number_format(memory_get_peak_usage() / 1024 / 1024, 3), ], $body, ); $response->setBody($output); return $response; } return null; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Filters/DebugToolbar.php
system/Filters/DebugToolbar.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Filters; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; /** * Debug toolbar filter * * @see \CodeIgniter\Filters\DebugToolbarTest */ class DebugToolbar implements FilterInterface { /** * We don't need to do anything here. * * @param list<string>|null $arguments */ public function before(RequestInterface $request, $arguments = null) { return null; } /** * If the debug flag is set (CI_DEBUG) then collect performance * and debug information and display it in a toolbar. * * @param list<string>|null $arguments */ public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { service('toolbar')->prepare($request, $response); return null; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Filters/Exceptions/FilterException.php
system/Filters/Exceptions/FilterException.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Filters\Exceptions; use CodeIgniter\Exceptions\ConfigException; /** * FilterException */ class FilterException extends ConfigException { /** * Thrown when the provided alias is not within * the list of configured filter aliases. * * @return static */ public static function forNoAlias(string $alias) { return new static(lang('Filters.noFilter', [$alias])); } /** * Thrown when the filter class does not implement FilterInterface. * * @return static */ public static function forIncorrectInterface(string $class) { return new static(lang('Filters.incorrectInterface', [$class])); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Typography/Typography.php
system/Typography/Typography.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Typography; use Config\DocTypes; /** * Typography Class * * @see \CodeIgniter\Typography\TypographyTest */ class Typography { /** * Block level elements that should not be wrapped inside <p> tags * * @var string */ public $blockElements = 'address|blockquote|div|dl|fieldset|form|h\d|hr|noscript|object|ol|p|pre|script|table|ul'; /** * Elements that should not have <p> and <br> tags within them. * * @var string */ public $skipElements = 'p|pre|ol|ul|dl|object|table|h\d'; /** * Tags we want the parser to completely ignore when splitting the string. * * @var string */ public $inlineElements = 'a|abbr|acronym|b|bdo|big|br|button|cite|code|del|dfn|em|i|img|ins|input|label|map|kbd|q|samp|select|small|span|strong|sub|sup|textarea|tt|var'; /** * array of block level elements that require inner content to be within another block level element * * @var array */ public $innerBlockRequired = ['blockquote']; /** * the last block element parsed * * @var string */ public $lastBlockElement = ''; /** * whether or not to protect quotes within { curly braces } * * @var bool */ public $protectBracedQuotes = false; /** * Auto Typography * * This function converts text, making it typographically correct: * - Converts double spaces into paragraphs. * - Converts single line breaks into <br> tags * - Converts single and double quotes into correctly facing curly quote entities. * - Converts three dots into ellipsis. * - Converts double dashes into em-dashes. * - Converts two spaces into entities * * @param bool $reduceLinebreaks whether to reduce more then two consecutive newlines to two */ public function autoTypography(string $str, bool $reduceLinebreaks = false): string { if ($str === '') { return ''; } // Standardize Newlines to make matching easier if (str_contains($str, "\r")) { $str = str_replace(["\r\n", "\r"], "\n", $str); } // Reduce line breaks. If there are more than two consecutive linebreaks // we'll compress them down to a maximum of two since there's no benefit to more. if ($reduceLinebreaks === false) { $str = preg_replace("/\n\n+/", "\n\n", $str); } // HTML comment tags don't conform to patterns of normal tags, so pull them out separately, only if needed $htmlComments = []; if (str_contains($str, '<!--') && preg_match_all('#(<!\-\-.*?\-\->)#s', $str, $matches) >= 1) { for ($i = 0, $total = count($matches[0]); $i < $total; $i++) { $htmlComments[] = $matches[0][$i]; $str = str_replace($matches[0][$i], '{@HC' . $i . '}', $str); } } // match and yank <pre> tags if they exist. It's cheaper to do this separately since most content will // not contain <pre> tags, and it keeps the PCRE patterns below simpler and faster if (str_contains($str, '<pre')) { $str = preg_replace_callback('#<pre.*?>.*?</pre>#si', $this->protectCharacters(...), $str); } // Convert quotes within tags to temporary markers. $str = preg_replace_callback('#<.+?>#si', $this->protectCharacters(...), $str); // Do the same with braces if necessary if ($this->protectBracedQuotes === false) { $str = preg_replace_callback('#\{.+?\}#si', $this->protectCharacters(...), $str); } // Convert "ignore" tags to temporary marker. The parser splits out the string at every tag // it encounters. Certain inline tags, like image tags, links, span tags, etc. will be // adversely affected if they are split out so we'll convert the opening bracket < temporarily to: {@TAG} $str = preg_replace('#<(/*)(' . $this->inlineElements . ')([ >])#i', '{@TAG}\\1\\2\\3', $str); /* Split the string at every tag. This expression creates an array with this prototype: * * [array] * { * [0] = <opening tag> * [1] = Content... * [2] = <closing tag> * Etc... * } */ $chunks = preg_split('/(<(?:[^<>]+(?:"[^"]*"|\'[^\']*\')?)+>)/', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); // Build our finalized string. We cycle through the array, skipping tags, and processing the contained text $str = ''; $process = true; for ($i = 0, $c = count($chunks) - 1; $i <= $c; $i++) { // Are we dealing with a tag? If so, we'll skip the processing for this cycle. // Well also set the "process" flag which allows us to skip <pre> tags and a few other things. if (preg_match('#<(/*)(' . $this->blockElements . ').*?>#', $chunks[$i], $match)) { if (preg_match('#' . $this->skipElements . '#', $match[2])) { $process = ($match[1] === '/'); } if ($match[1] === '') { $this->lastBlockElement = $match[2]; } $str .= $chunks[$i]; continue; } if ($process === false) { $str .= $chunks[$i]; continue; } // Force a newline to make sure end tags get processed by _format_newlines() if ($i === $c) { $chunks[$i] .= "\n"; } // Convert Newlines into <p> and <br> tags $str .= $this->formatNewLines($chunks[$i]); } // No opening block level tag? Add it if needed. if (preg_match('/^\s*<(?:' . $this->blockElements . ')/i', $str) !== 1) { $str = preg_replace('/^(.*?)<(' . $this->blockElements . ')/i', '<p>$1</p><$2', $str); } // Convert quotes, elipsis, em-dashes, non-breaking spaces, and ampersands $str = $this->formatCharacters($str); foreach ($htmlComments as $i => $htmlComment) { // remove surrounding paragraph tags, but only if there's an opening paragraph tag // otherwise HTML comments at the ends of paragraphs will have the closing tag removed // if '<p>{@HC1}' then replace <p>{@HC1}</p> with the comment, else replace only {@HC1} with the comment $str = preg_replace('#(?(?=<p>\{@HC' . $i . '\})<p>\{@HC' . $i . '\}(\s*</p>)|\{@HC' . $i . '\})#s', $htmlComment, $str); } // Final clean up $table = [ // If the user submitted their own paragraph tags within the text // we will retain them instead of using our tags. '/(<p[^>*?]>)<p>/' => '$1', // <?php BBEdit syntax coloring bug fix // Reduce multiple instances of opening/closing paragraph tags to a single one '#(</p>)+#' => '</p>', '/(<p>\W*<p>)+/' => '<p>', // Clean up stray paragraph tags that appear before block level elements '#<p></p><(' . $this->blockElements . ')#' => '<$1', // Clean up stray non-breaking spaces preceeding block elements '#(&nbsp;\s*)+<(' . $this->blockElements . ')#' => ' <$2', // Replace the temporary markers we added earlier '/\{@TAG\}/' => '<', '/\{@DQ\}/' => '"', '/\{@SQ\}/' => "'", '/\{@DD\}/' => '--', '/\{@NBS\}/' => ' ', // An unintended consequence of the _format_newlines function is that // some of the newlines get truncated, resulting in <p> tags // starting immediately after <block> tags on the same line. // This forces a newline after such occurrences, which looks much nicer. "/><p>\n/" => ">\n<p>", // Similarly, there might be cases where a closing </block> will follow // a closing </p> tag, so we'll correct it by adding a newline in between '#</p></#' => "</p>\n</", ]; // Do we need to reduce empty lines? if ($reduceLinebreaks) { $table['#<p>\n*</p>#'] = ''; } else { // If we have empty paragraph tags we add a non-breaking space // otherwise most browsers won't treat them as true paragraphs $table['#<p></p>#'] = '<p>&nbsp;</p>'; } return preg_replace(array_keys($table), $table, $str); } /** * Format Characters * * This function mainly converts double and single quotes * to curly entities, but it also converts em-dashes, * double spaces, and ampersands */ public function formatCharacters(string $str): string { static $table; if (! isset($table)) { $table = [ // nested smart quotes, opening and closing // note that rules for grammar (English) allow only for two levels deep // and that single quotes are _supposed_ to always be on the outside // but we'll accommodate both // Note that in all cases, whitespace is the primary determining factor // on which direction to curl, with non-word characters like punctuation // being a secondary factor only after whitespace is addressed. '/\'"(\s|$)/' => '&#8217;&#8221;$1', '/(^|\s|<p>)\'"/' => '$1&#8216;&#8220;', '/\'"(\W)/' => '&#8217;&#8221;$1', '/(\W)\'"/' => '$1&#8216;&#8220;', '/"\'(\s|$)/' => '&#8221;&#8217;$1', '/(^|\s|<p>)"\'/' => '$1&#8220;&#8216;', '/"\'(\W)/' => '&#8221;&#8217;$1', '/(\W)"\'/' => '$1&#8220;&#8216;', // single quote smart quotes '/\'(\s|$)/' => '&#8217;$1', '/(^|\s|<p>)\'/' => '$1&#8216;', '/\'(\W)/' => '&#8217;$1', '/(\W)\'/' => '$1&#8216;', // double quote smart quotes '/"(\s|$)/' => '&#8221;$1', '/(^|\s|<p>)"/' => '$1&#8220;', '/"(\W)/' => '&#8221;$1', '/(\W)"/' => '$1&#8220;', // apostrophes '/(\w)\'(\w)/' => '$1&#8217;$2', // Em dash and ellipses dots '/\s?\-\-\s?/' => '&#8212;', '/(\w)\.{3}/' => '$1&#8230;', // double space after sentences '/(\W) /' => '$1&nbsp; ', // ampersands, if not a character entity '/&(?!#?[a-zA-Z0-9]{2,};)/' => '&amp;', ]; } return preg_replace(array_keys($table), $table, $str); } /** * Format Newlines * * Converts newline characters into either <p> tags or <br> */ protected function formatNewLines(string $str): string { if ($str === '' || (! str_contains($str, "\n") && ! in_array($this->lastBlockElement, $this->innerBlockRequired, true))) { return $str; } // Convert two consecutive newlines to paragraphs $str = str_replace("\n\n", "</p>\n\n<p>", $str); // Convert single spaces to <br> tags $br = '<br' . _solidus() . '>'; $str = preg_replace("/([^\n])(\n)([^\n])/", '\\1' . $br . '\\2\\3', $str); // Wrap the whole enchilada in enclosing paragraphs if ($str !== "\n") { // We trim off the right-side new line so that the closing </p> tag // will be positioned immediately following the string, matching // the behavior of the opening <p> tag $str = '<p>' . rtrim($str) . '</p>'; } // Remove empty paragraphs if they are on the first line, as this // is a potential unintended consequence of the previous code return preg_replace('/<p><\/p>(.*)/', '\\1', $str, 1); } /** * Protect Characters * * Protects special characters from being formatted later * We don't want quotes converted within tags so we'll temporarily convert them to {@DQ} and {@SQ} * and we don't want double dashes converted to emdash entities, so they are marked with {@DD} * likewise double spaces are converted to {@NBS} to prevent entity conversion */ protected function protectCharacters(array $match): string { return str_replace(["'", '"', '--', ' '], ['{@SQ}', '{@DQ}', '{@DD}', '{@NBS}'], $match[0]); } /** * Convert newlines to HTML line breaks except within PRE tags */ public function nl2brExceptPre(string $str): string { $newstr = ''; $docTypes = new DocTypes(); for ($ex = explode('pre>', $str), $ct = count($ex), $i = 0; $i < $ct; $i++) { $xhtml = ! ($docTypes->html5 ?? false); $newstr .= (($i % 2) === 0) ? nl2br($ex[$i], $xhtml) : $ex[$i]; if ($ct - 1 !== $i) { $newstr .= 'pre>'; } } return $newstr; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/DataCaster/DataCaster.php
system/DataCaster/DataCaster.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\DataCaster; use CodeIgniter\DataCaster\Cast\ArrayCast; use CodeIgniter\DataCaster\Cast\BooleanCast; use CodeIgniter\DataCaster\Cast\CastInterface; use CodeIgniter\DataCaster\Cast\CSVCast; use CodeIgniter\DataCaster\Cast\DatetimeCast; use CodeIgniter\DataCaster\Cast\FloatCast; use CodeIgniter\DataCaster\Cast\IntBoolCast; use CodeIgniter\DataCaster\Cast\IntegerCast; use CodeIgniter\DataCaster\Cast\JsonCast; use CodeIgniter\DataCaster\Cast\TimestampCast; use CodeIgniter\DataCaster\Cast\URICast; use CodeIgniter\Entity\Cast\CastInterface as EntityCastInterface; use CodeIgniter\Entity\Exceptions\CastException; use CodeIgniter\Exceptions\InvalidArgumentException; final class DataCaster { /** * Array of field names and the type of value to cast. * * @var array<string, string> [field => type] */ private array $types = []; /** * Convert handlers * * @var array<string, class-string> [type => classname] */ private array $castHandlers = [ 'array' => ArrayCast::class, 'bool' => BooleanCast::class, 'boolean' => BooleanCast::class, 'csv' => CSVCast::class, 'datetime' => DatetimeCast::class, 'double' => FloatCast::class, 'float' => FloatCast::class, 'int' => IntegerCast::class, 'integer' => IntegerCast::class, 'int-bool' => IntBoolCast::class, 'json' => JsonCast::class, 'timestamp' => TimestampCast::class, 'uri' => URICast::class, ]; /** * @param array<string, class-string>|null $castHandlers Custom convert handlers * @param array<string, string>|null $types [field => type] * @param object|null $helper Helper object. * @param bool $strict Strict mode? Set to false for casts for Entity. */ public function __construct( ?array $castHandlers = null, ?array $types = null, private readonly ?object $helper = null, private readonly bool $strict = true, ) { $this->castHandlers = array_merge($this->castHandlers, $castHandlers); if ($types !== null) { $this->setTypes($types); } if ($this->strict) { foreach ($this->castHandlers as $handler) { if ( ! is_subclass_of($handler, CastInterface::class) && ! is_subclass_of($handler, EntityCastInterface::class) ) { throw new InvalidArgumentException( 'Invalid class type. It must implement CastInterface. class: ' . $handler, ); } } } } /** * This method is only for Entity. * * @TODO if Entity::$casts is readonly, we don't need this method. * * @param array<string, string> $types [field => type] * * @return $this * * @internal */ public function setTypes(array $types): static { $this->types = $types; return $this; } /** * Provides the ability to cast an item as a specific data type. * Add ? at the beginning of the type (i.e. ?string) to get `null` * instead of casting $value when $value is null. * * @param mixed $value The value to convert * @param string $field The field name * @param 'get'|'set' $method Allowed to "get" and "set" */ public function castAs(mixed $value, string $field, string $method = 'get'): mixed { // If the type is not defined, return as it is. if (! isset($this->types[$field])) { return $value; } $type = $this->types[$field]; $isNullable = false; // Is nullable? if (str_starts_with($type, '?')) { $isNullable = true; if ($value === null) { return null; } $type = substr($type, 1); } elseif ($value === null) { if ($this->strict) { $message = 'Field "' . $field . '" is not nullable, but null was passed.'; throw new InvalidArgumentException($message); } } // In order not to create a separate handler for the // json-array type, we transform the required one. $type = ($type === 'json-array') ? 'json[array]' : $type; $params = []; // Attempt to retrieve additional parameters if specified // type[param, param2,param3] if (preg_match('/\A(.+)\[(.+)\]\z/', $type, $matches)) { $type = $matches[1]; $params = array_map(trim(...), explode(',', $matches[2])); } if ($isNullable && ! $this->strict) { $params[] = 'nullable'; } $type = trim($type, '[]'); $handlers = $this->castHandlers; if (! isset($handlers[$type])) { throw new InvalidArgumentException( 'No such handler for "' . $field . '". Invalid type: ' . $type, ); } $handler = $handlers[$type]; if ( ! $this->strict && ! is_subclass_of($handler, CastInterface::class) && ! is_subclass_of($handler, EntityCastInterface::class) ) { throw CastException::forInvalidInterface($handler); } return $handler::$method($value, $params, $this->helper); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/DataCaster/Cast/JsonCast.php
system/DataCaster/Cast/JsonCast.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\DataCaster\Cast; use CodeIgniter\DataCaster\Exceptions\CastException; use JsonException; use stdClass; /** * Class JsonCast * * (PHP) [array|stdClass --> string] --> (DB driver) --> (DB column) string * [ <-- string] <-- (DB driver) <-- (DB column) string */ class JsonCast extends BaseCast { public static function get( mixed $value, array $params = [], ?object $helper = null, ): array|stdClass { if (! is_string($value)) { self::invalidTypeValueError($value); } $associative = in_array('array', $params, true); $output = ($associative ? [] : new stdClass()); try { $output = json_decode($value, $associative, 512, JSON_THROW_ON_ERROR); } catch (JsonException $e) { throw CastException::forInvalidJsonFormat($e->getCode()); } return $output; } public static function set( mixed $value, array $params = [], ?object $helper = null, ): string { try { $output = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR); } catch (JsonException $e) { throw CastException::forInvalidJsonFormat($e->getCode()); } return $output; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/DataCaster/Cast/TimestampCast.php
system/DataCaster/Cast/TimestampCast.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\DataCaster\Cast; use CodeIgniter\I18n\Time; /** * Class TimestampCast * * (PHP) [Time --> int ] --> (DB driver) --> (DB column) int * [ <-- int|string] <-- (DB driver) <-- (DB column) int */ class TimestampCast extends BaseCast { public static function get( mixed $value, array $params = [], ?object $helper = null, ): Time { if (! is_int($value) && ! is_string($value)) { self::invalidTypeValueError($value); } return Time::createFromTimestamp((int) $value, date_default_timezone_get()); } public static function set( mixed $value, array $params = [], ?object $helper = null, ): int { if (! $value instanceof Time) { self::invalidTypeValueError($value); } return $value->getTimestamp(); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/DataCaster/Cast/BaseCast.php
system/DataCaster/Cast/BaseCast.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\DataCaster\Cast; use CodeIgniter\Exceptions\InvalidArgumentException; abstract class BaseCast implements CastInterface { public static function get( mixed $value, array $params = [], ?object $helper = null, ): mixed { return $value; } public static function set( mixed $value, array $params = [], ?object $helper = null, ): mixed { return $value; } protected static function invalidTypeValueError(mixed $value): never { $message = '[' . static::class . '] Invalid value type: ' . get_debug_type($value); if (is_scalar($value)) { $message .= ', and its value: ' . var_export($value, true); } throw new InvalidArgumentException($message); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/DataCaster/Cast/ArrayCast.php
system/DataCaster/Cast/ArrayCast.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\DataCaster\Cast; /** * Class ArrayCast * * (PHP) [array --> string] --> (DB driver) --> (DB column) string * [ <-- string] <-- (DB driver) <-- (DB column) string */ class ArrayCast extends BaseCast implements CastInterface { public static function get( mixed $value, array $params = [], ?object $helper = null, ): array { if (! is_string($value)) { self::invalidTypeValueError($value); } if ((str_starts_with($value, 'a:') || str_starts_with($value, 's:'))) { $value = unserialize($value, ['allowed_classes' => false]); } return (array) $value; } public static function set( mixed $value, array $params = [], ?object $helper = null, ): string { return serialize($value); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/DataCaster/Cast/FloatCast.php
system/DataCaster/Cast/FloatCast.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\DataCaster\Cast; /** * Class FloatCast * * (PHP) [float --> float ] --> (DB driver) --> (DB column) float * [ <-- float|string] <-- (DB driver) <-- (DB column) float */ class FloatCast extends BaseCast { public static function get( mixed $value, array $params = [], ?object $helper = null, ): float { if (! is_float($value) && ! is_string($value)) { self::invalidTypeValueError($value); } return (float) $value; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/DataCaster/Cast/DatetimeCast.php
system/DataCaster/Cast/DatetimeCast.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\DataCaster\Cast; use CodeIgniter\Database\BaseConnection; use CodeIgniter\Exceptions\InvalidArgumentException; use CodeIgniter\I18n\Time; /** * Class DatetimeCast * * (PHP) [Time --> string] --> (DB driver) --> (DB column) datetime * [ <-- string] <-- (DB driver) <-- (DB column) datetime */ class DatetimeCast extends BaseCast { public static function get( mixed $value, array $params = [], ?object $helper = null, ): Time { if (! is_string($value)) { self::invalidTypeValueError($value); } if (! $helper instanceof BaseConnection) { $message = 'The parameter $helper must be BaseConnection.'; throw new InvalidArgumentException($message); } /** * @see https://www.php.net/manual/en/datetimeimmutable.createfromformat.php#datetimeimmutable.createfromformat.parameters */ $format = self::getDateTimeFormat($params, $helper); return Time::createFromFormat($format, $value); } public static function set( mixed $value, array $params = [], ?object $helper = null, ): string { if (! $value instanceof Time) { self::invalidTypeValueError($value); } if (! $helper instanceof BaseConnection) { $message = 'The parameter $helper must be BaseConnection.'; throw new InvalidArgumentException($message); } $format = self::getDateTimeFormat($params, $helper); return $value->format($format); } /** * Gets DateTime format from the DB connection. * * @param list<string> $params Additional param */ protected static function getDateTimeFormat(array $params, BaseConnection $db): string { return match ($params[0] ?? '') { '' => $db->dateFormat['datetime'], 'ms' => $db->dateFormat['datetime-ms'], 'us' => $db->dateFormat['datetime-us'], default => throw new InvalidArgumentException('Invalid parameter: ' . $params[0]), }; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/DataCaster/Cast/IntegerCast.php
system/DataCaster/Cast/IntegerCast.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\DataCaster\Cast; /** * Class IntegerCast * * (PHP) [int --> int ] --> (DB driver) --> (DB column) int * [ <-- int|string] <-- (DB driver) <-- (DB column) int */ class IntegerCast extends BaseCast { public static function get( mixed $value, array $params = [], ?object $helper = null, ): int { if (! is_string($value) && ! is_int($value)) { self::invalidTypeValueError($value); } return (int) $value; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/DataCaster/Cast/IntBoolCast.php
system/DataCaster/Cast/IntBoolCast.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\DataCaster\Cast; /** * Int Bool Cast * * (PHP) [bool --> int ] --> (DB driver) --> (DB column) int(0/1) * [ <-- int|string] <-- (DB driver) <-- (DB column) int(0/1) */ final class IntBoolCast extends BaseCast { public static function get( mixed $value, array $params = [], ?object $helper = null, ): bool { if (! is_int($value) && ! is_string($value)) { self::invalidTypeValueError($value); } return (bool) $value; } public static function set( mixed $value, array $params = [], ?object $helper = null, ): int { if (! is_bool($value)) { self::invalidTypeValueError($value); } return (int) $value; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/DataCaster/Cast/URICast.php
system/DataCaster/Cast/URICast.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\DataCaster\Cast; use CodeIgniter\HTTP\URI; /** * Class URICast * * (PHP) [URI --> string] --> (DB driver) --> (DB column) string * [ <-- string] <-- (DB driver) <-- (DB column) string */ class URICast extends BaseCast { public static function get( mixed $value, array $params = [], ?object $helper = null, ): URI { if (! is_string($value)) { self::invalidTypeValueError($value); } return new URI($value); } public static function set( mixed $value, array $params = [], ?object $helper = null, ): string { if (! $value instanceof URI) { self::invalidTypeValueError($value); } return (string) $value; } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/DataCaster/Cast/CastInterface.php
system/DataCaster/Cast/CastInterface.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\DataCaster\Cast; interface CastInterface { /** * Takes a value from DataSource, returns its value for PHP. * * @param mixed $value Data from database driver * @param list<string> $params Additional param * @param object|null $helper Helper object. E.g., database connection * * @return mixed PHP native value */ public static function get( mixed $value, array $params = [], ?object $helper = null, ): mixed; /** * Takes a PHP value, returns its value for DataSource. * * @param mixed $value PHP native value * @param list<string> $params Additional param * @param object|null $helper Helper object. E.g., database connection * * @return mixed Data to pass to database driver */ public static function set( mixed $value, array $params = [], ?object $helper = null, ): mixed; }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/DataCaster/Cast/BooleanCast.php
system/DataCaster/Cast/BooleanCast.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\DataCaster\Cast; /** * Class BooleanCast * * (PHP) [bool --> bool ] --> (DB driver) --> (DB column) bool|int(0/1) * [ <-- string|int] <-- (DB driver) <-- (DB column) bool|int(0/1) */ class BooleanCast extends BaseCast { public static function get( mixed $value, array $params = [], ?object $helper = null, ): bool { // For PostgreSQL if ($value === 't') { return true; } if ($value === 'f') { return false; } return filter_var($value, FILTER_VALIDATE_BOOLEAN); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/DataCaster/Cast/CSVCast.php
system/DataCaster/Cast/CSVCast.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\DataCaster\Cast; /** * Class CSVCast * * (PHP) [array --> string] --> (DB driver) --> (DB column) string * [ <-- string] <-- (DB driver) <-- (DB column) string */ class CSVCast extends BaseCast { public static function get( mixed $value, array $params = [], ?object $helper = null, ): array { if (! is_string($value)) { self::invalidTypeValueError($value); } return explode(',', $value); } public static function set( mixed $value, array $params = [], ?object $helper = null, ): string { if (! is_array($value)) { self::invalidTypeValueError($value); } return implode(',', $value); } }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/DataCaster/Exceptions/CastException.php
system/DataCaster/Exceptions/CastException.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\DataCaster\Exceptions; use CodeIgniter\Entity\Exceptions\CastException as EntityCastException; /** * CastException is thrown for invalid cast initialization and management. */ class CastException extends EntityCastException { }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false
trampgeek/jobe
https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cookie/CloneableCookieInterface.php
system/Cookie/CloneableCookieInterface.php
<?php declare(strict_types=1); /** * This file is part of CodeIgniter 4 framework. * * (c) CodeIgniter Foundation <admin@codeigniter.com> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace CodeIgniter\Cookie; use DateTimeInterface; /** * Interface for a fresh Cookie instance with selected attribute(s) * only changed from the original instance. */ interface CloneableCookieInterface extends CookieInterface { /** * Creates a new Cookie with a new cookie prefix. * * @return static */ public function withPrefix(string $prefix = ''); /** * Creates a new Cookie with a new name. * * @return static */ public function withName(string $name); /** * Creates a new Cookie with new value. * * @return static */ public function withValue(string $value); /** * Creates a new Cookie with a new cookie expires time. * * @param DateTimeInterface|int|string $expires * * @return static */ public function withExpires($expires); /** * Creates a new Cookie that will expire the cookie from the browser. * * @return static */ public function withExpired(); /** * Creates a new Cookie with a new path on the server the cookie is available. * * @return static */ public function withPath(?string $path); /** * Creates a new Cookie with a new domain the cookie is available. * * @return static */ public function withDomain(?string $domain); /** * Creates a new Cookie with a new "Secure" attribute. * * @return static */ public function withSecure(bool $secure = true); /** * Creates a new Cookie with a new "HttpOnly" attribute * * @return static */ public function withHTTPOnly(bool $httponly = true); /** * Creates a new Cookie with a new "SameSite" attribute. * * @return static */ public function withSameSite(string $samesite); /** * Creates a new Cookie with URL encoding option updated. * * @return static */ public function withRaw(bool $raw = true); }
php
MIT
cffff99685a78a2e13b47a5288e6fa87a1abe40a
2026-01-05T05:19:26.518100Z
false