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/Database/Seeder.php | system/Database/Seeder.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\Database;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Exceptions\InvalidArgumentException;
use Config\Database;
use Faker\Factory;
use Faker\Generator;
/**
* Class Seeder
*/
class Seeder
{
/**
* The name of the database group to use.
*
* @var non-empty-string
*/
protected $DBGroup;
/**
* Where we can find the Seed files.
*
* @var string
*/
protected $seedPath;
/**
* An instance of the main Database configuration
*
* @var Database
*/
protected $config;
/**
* Database Connection instance
*
* @var BaseConnection
*/
protected $db;
/**
* Database Forge instance.
*
* @var Forge
*/
protected $forge;
/**
* If true, will not display CLI messages.
*
* @var bool
*/
protected $silent = false;
/**
* Faker Generator instance.
*
* @deprecated
*/
private static ?Generator $faker = null;
/**
* Seeder constructor.
*/
public function __construct(Database $config, ?BaseConnection $db = null)
{
$this->seedPath = $config->filesPath ?? APPPATH . 'Database/';
if ($this->seedPath === '') {
throw new InvalidArgumentException('Invalid filesPath set in the Config\Database.');
}
$this->seedPath = rtrim($this->seedPath, '\\/') . '/Seeds/';
if (! is_dir($this->seedPath)) {
throw new InvalidArgumentException('Unable to locate the seeds directory. Please check Config\Database::filesPath');
}
$this->config = &$config;
$db ??= Database::connect($this->DBGroup);
$this->db = $db;
$this->forge = Database::forge($this->DBGroup);
}
/**
* Gets the Faker Generator instance.
*
* @deprecated
*/
public static function faker(): ?Generator
{
if (! self::$faker instanceof Generator && class_exists(Factory::class)) {
self::$faker = Factory::create();
}
return self::$faker;
}
/**
* Loads the specified seeder and runs it.
*
* @return void
*
* @throws InvalidArgumentException
*/
public function call(string $class)
{
$class = trim($class);
if ($class === '') {
throw new InvalidArgumentException('No seeder was specified.');
}
if (! str_contains($class, '\\')) {
$path = $this->seedPath . str_replace('.php', '', $class) . '.php';
if (! is_file($path)) {
throw new InvalidArgumentException('The specified seeder is not a valid file: ' . $path);
}
// Assume the class has the correct namespace
// @codeCoverageIgnoreStart
$class = APP_NAMESPACE . '\Database\Seeds\\' . $class;
if (! class_exists($class, false)) {
require_once $path;
}
// @codeCoverageIgnoreEnd
}
/** @var Seeder $seeder */
$seeder = new $class($this->config);
$seeder->setSilent($this->silent)->run();
unset($seeder);
if (is_cli() && ! $this->silent) {
CLI::write("Seeded: {$class}", 'green');
}
}
/**
* Sets the location of the directory that seed files can be located in.
*
* @return $this
*/
public function setPath(string $path)
{
$this->seedPath = rtrim($path, '\\/') . '/';
return $this;
}
/**
* Sets the silent treatment.
*
* @return $this
*/
public function setSilent(bool $silent)
{
$this->silent = $silent;
return $this;
}
/**
* Run the database seeds. This is where the magic happens.
*
* Child classes must implement this method and take care
* of inserting their data here.
*
* @return void
*
* @codeCoverageIgnore
*/
public function run()
{
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/BaseResult.php | system/Database/BaseResult.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\Database;
use CodeIgniter\Entity\Entity;
use stdClass;
/**
* @template TConnection
* @template TResult
*
* @implements ResultInterface<TConnection, TResult>
*/
abstract class BaseResult implements ResultInterface
{
/**
* Connection ID
*
* @var TConnection
*/
public $connID;
/**
* Result ID
*
* @var false|TResult
*/
public $resultID;
/**
* Result Array
*
* @var list<array>
*/
public $resultArray = [];
/**
* Result Object
*
* @var list<object>
*/
public $resultObject = [];
/**
* Custom Result Object
*
* @var array
*/
public $customResultObject = [];
/**
* Current Row index
*
* @var int
*/
public $currentRow = 0;
/**
* The number of records in the query result
*
* @var int|null
*/
protected $numRows;
/**
* Row data
*
* @var array|null
*/
public $rowData;
/**
* Constructor
*
* @param TConnection $connID
* @param TResult $resultID
*/
public function __construct(&$connID, &$resultID)
{
$this->connID = $connID;
$this->resultID = $resultID;
}
/**
* Retrieve the results of the query. Typically an array of
* individual data rows, which can be either an 'array', an
* 'object', or a custom class name.
*
* @param string $type The row type. Either 'array', 'object', or a class name to use
*/
public function getResult(string $type = 'object'): array
{
if ($type === 'array') {
return $this->getResultArray();
}
if ($type === 'object') {
return $this->getResultObject();
}
return $this->getCustomResultObject($type);
}
/**
* Returns the results as an array of custom objects.
*
* @param class-string $className
*
* @return array
*/
public function getCustomResultObject(string $className)
{
if (isset($this->customResultObject[$className])) {
return $this->customResultObject[$className];
}
if (! $this->isValidResultId()) {
return [];
}
// Don't fetch the result set again if we already have it
$_data = null;
if (($c = count($this->resultArray)) > 0) {
$_data = 'resultArray';
} elseif (($c = count($this->resultObject)) > 0) {
$_data = 'resultObject';
}
if ($_data !== null) {
for ($i = 0; $i < $c; $i++) {
$this->customResultObject[$className][$i] = new $className();
foreach ($this->{$_data}[$i] as $key => $value) {
$this->customResultObject[$className][$i]->{$key} = $value;
}
}
return $this->customResultObject[$className];
}
if ($this->rowData !== null) {
$this->dataSeek();
}
$this->customResultObject[$className] = [];
while ($row = $this->fetchObject($className)) {
if (! is_subclass_of($row, Entity::class) && method_exists($row, 'syncOriginal')) {
$row->syncOriginal();
}
$this->customResultObject[$className][] = $row;
}
return $this->customResultObject[$className];
}
/**
* Returns the results as an array of arrays.
*
* If no results, an empty array is returned.
*/
public function getResultArray(): array
{
if ($this->resultArray !== []) {
return $this->resultArray;
}
// In the event that query caching is on, the result_id variable
// will not be a valid resource so we'll simply return an empty
// array.
if (! $this->isValidResultId()) {
return [];
}
if ($this->resultObject !== []) {
foreach ($this->resultObject as $row) {
$this->resultArray[] = (array) $row;
}
return $this->resultArray;
}
if ($this->rowData !== null) {
$this->dataSeek();
}
while ($row = $this->fetchAssoc()) {
$this->resultArray[] = $row;
}
return $this->resultArray;
}
/**
* Returns the results as an array of objects.
*
* If no results, an empty array is returned.
*
* @return list<stdClass>
*/
public function getResultObject(): array
{
if ($this->resultObject !== []) {
return $this->resultObject;
}
// In the event that query caching is on, the result_id variable
// will not be a valid resource so we'll simply return an empty
// array.
if (! $this->isValidResultId()) {
return [];
}
if ($this->resultArray !== []) {
foreach ($this->resultArray as $row) {
$this->resultObject[] = (object) $row;
}
return $this->resultObject;
}
if ($this->rowData !== null) {
$this->dataSeek();
}
while ($row = $this->fetchObject()) {
if (! is_subclass_of($row, Entity::class) && method_exists($row, 'syncOriginal')) {
$row->syncOriginal();
}
$this->resultObject[] = $row;
}
return $this->resultObject;
}
/**
* Wrapper object to return a row as either an array, an object, or
* a custom class.
*
* If the row doesn't exist, returns null.
*
* @template T of object
*
* @param int|string $n The index of the results to return, or column name.
* @param 'array'|'object'|class-string<T> $type The type of result object. 'array', 'object' or class name.
*
* @return ($n is string ? float|int|string|null : ($type is 'object' ? stdClass|null : ($type is 'array' ? array|null : T|null)))
*/
public function getRow($n = 0, string $type = 'object')
{
// $n is a column name.
if (! is_numeric($n)) {
// We cache the row data for subsequent uses
if (! is_array($this->rowData)) {
$this->rowData = $this->getRowArray();
}
// array_key_exists() instead of isset() to allow for NULL values
if (empty($this->rowData) || ! array_key_exists($n, $this->rowData)) {
return null;
}
return $this->rowData[$n];
}
if ($type === 'object') {
return $this->getRowObject($n);
}
if ($type === 'array') {
return $this->getRowArray($n);
}
return $this->getCustomRowObject($n, $type);
}
/**
* Returns a row as a custom class instance.
*
* If the row doesn't exist, returns null.
*
* @template T of object
*
* @param int $n The index of the results to return.
* @param class-string<T> $className
*
* @return T|null
*/
public function getCustomRowObject(int $n, string $className)
{
if (! isset($this->customResultObject[$className])) {
$this->getCustomResultObject($className);
}
if (empty($this->customResultObject[$className])) {
return null;
}
if ($n !== $this->currentRow && isset($this->customResultObject[$className][$n])) {
$this->currentRow = $n;
}
return $this->customResultObject[$className][$this->currentRow];
}
/**
* Returns a single row from the results as an array.
*
* If row doesn't exist, returns null.
*
* @return array|null
*/
public function getRowArray(int $n = 0)
{
$result = $this->getResultArray();
if ($result === []) {
return null;
}
if ($n !== $this->currentRow && isset($result[$n])) {
$this->currentRow = $n;
}
return $result[$this->currentRow];
}
/**
* Returns a single row from the results as an object.
*
* If row doesn't exist, returns null.
*
* @return object|stdClass|null
*/
public function getRowObject(int $n = 0)
{
$result = $this->getResultObject();
if ($result === []) {
return null;
}
if ($n !== $this->customResultObject && isset($result[$n])) {
$this->currentRow = $n;
}
return $result[$this->currentRow];
}
/**
* Assigns an item into a particular column slot.
*
* @param array|string $key
* @param array|object|stdClass|null $value
*
* @return void
*/
public function setRow($key, $value = null)
{
// We cache the row data for subsequent uses
if (! is_array($this->rowData)) {
$this->rowData = $this->getRowArray();
}
if (is_array($key)) {
foreach ($key as $k => $v) {
$this->rowData[$k] = $v;
}
return;
}
if ($key !== '' && $value !== null) {
$this->rowData[$key] = $value;
}
}
/**
* Returns the "first" row of the current results.
*
* @return array|object|null
*/
public function getFirstRow(string $type = 'object')
{
$result = $this->getResult($type);
return ($result === []) ? null : $result[0];
}
/**
* Returns the "last" row of the current results.
*
* @return array|object|null
*/
public function getLastRow(string $type = 'object')
{
$result = $this->getResult($type);
return ($result === []) ? null : $result[count($result) - 1];
}
/**
* Returns the "next" row of the current results.
*
* @return array|object|null
*/
public function getNextRow(string $type = 'object')
{
$result = $this->getResult($type);
if ($result === []) {
return null;
}
return isset($result[$this->currentRow + 1]) ? $result[++$this->currentRow] : null;
}
/**
* Returns the "previous" row of the current results.
*
* @return array|object|null
*/
public function getPreviousRow(string $type = 'object')
{
$result = $this->getResult($type);
if ($result === []) {
return null;
}
if (isset($result[$this->currentRow - 1])) {
$this->currentRow--;
}
return $result[$this->currentRow];
}
/**
* Returns an unbuffered row and move the pointer to the next row.
*
* @return array|object|null
*/
public function getUnbufferedRow(string $type = 'object')
{
if ($type === 'array') {
return $this->fetchAssoc();
}
if ($type === 'object') {
return $this->fetchObject();
}
return $this->fetchObject($type);
}
/**
* Number of rows in the result set; checks for previous count, falls
* back on counting resultArray or resultObject, finally fetching resultArray
* if nothing was previously fetched
*/
public function getNumRows(): int
{
if (is_int($this->numRows)) {
return $this->numRows;
}
if ($this->resultArray !== []) {
return $this->numRows = count($this->resultArray);
}
if ($this->resultObject !== []) {
return $this->numRows = count($this->resultObject);
}
return $this->numRows = count($this->getResultArray());
}
private function isValidResultId(): bool
{
return is_resource($this->resultID) || is_object($this->resultID);
}
/**
* Gets the number of fields in the result set.
*/
abstract public function getFieldCount(): int;
/**
* Generates an array of column names in the result set.
*/
abstract public function getFieldNames(): array;
/**
* Generates an array of objects representing field meta-data.
*/
abstract public function getFieldData(): array;
/**
* Frees the current result.
*
* @return void
*/
abstract public function freeResult();
/**
* Moves the internal pointer to the desired offset. This is called
* internally before fetching results to make sure the result set
* starts at zero.
*
* @return bool
*/
abstract public function dataSeek(int $n = 0);
/**
* Returns the result set as an array.
*
* Overridden by driver classes.
*
* @return array|false|null
*/
abstract protected function fetchAssoc();
/**
* Returns the result set as an object.
*
* @param class-string $className
*
* @return false|object
*/
abstract protected function fetchObject(string $className = stdClass::class);
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/TableName.php | system/Database/TableName.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\Database;
/**
* Represents a table name in SQL.
*
* @interal
*
* @see \CodeIgniter\Database\TableNameTest
*/
class TableName
{
/**
* @param string $actualTable Actual table name
* @param string $logicalTable Logical table name (w/o DB prefix)
* @param string $schema Schema name
* @param string $database Database name
* @param string $alias Alias name
*/
protected function __construct(
private readonly string $actualTable,
private readonly string $logicalTable = '',
private readonly string $schema = '',
private readonly string $database = '',
private readonly string $alias = '',
) {
}
/**
* Creates a new instance.
*
* @param string $table Table name (w/o DB prefix)
* @param string $alias Alias name
*/
public static function create(string $dbPrefix, string $table, string $alias = ''): self
{
return new self(
$dbPrefix . $table,
$table,
'',
'',
$alias,
);
}
/**
* Creates a new instance from an actual table name.
*
* @param string $actualTable Actual table name with DB prefix
* @param string $alias Alias name
*/
public static function fromActualName(string $dbPrefix, string $actualTable, string $alias = ''): self
{
$prefix = $dbPrefix;
$logicalTable = '';
if (str_starts_with($actualTable, $prefix)) {
$logicalTable = substr($actualTable, strlen($prefix));
}
return new self(
$actualTable,
$logicalTable,
'',
$alias,
);
}
/**
* Creates a new instance from full name.
*
* @param string $table Table name (w/o DB prefix)
* @param string $schema Schema name
* @param string $database Database name
* @param string $alias Alias name
*/
public static function fromFullName(
string $dbPrefix,
string $table,
string $schema = '',
string $database = '',
string $alias = '',
): self {
return new self(
$dbPrefix . $table,
$table,
$schema,
$database,
$alias,
);
}
/**
* Returns the single segment table name w/o DB prefix.
*/
public function getTableName(): string
{
return $this->logicalTable;
}
/**
* Returns the actual single segment table name w/z DB prefix.
*/
public function getActualTableName(): string
{
return $this->actualTable;
}
public function getAlias(): string
{
return $this->alias;
}
public function getSchema(): string
{
return $this->schema;
}
public function getDatabase(): string
{
return $this->database;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/Config.php | system/Database/Config.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\Database;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Exceptions\InvalidArgumentException;
use Config\Database as DbConfig;
/**
* @see \CodeIgniter\Database\ConfigTest
*/
class Config extends BaseConfig
{
/**
* Cache for instance of any connections that
* have been requested as a "shared" instance.
*
* @var array
*/
protected static $instances = [];
/**
* The main instance used to manage all of
* our open database connections.
*
* @var Database|null
*/
protected static $factory;
/**
* Returns the database connection
*
* @param array|BaseConnection|non-empty-string|null $group The name of the connection group to use,
* or an array of configuration settings.
* @param bool $getShared Whether to return a shared instance of the connection.
*
* @return BaseConnection
*/
public static function connect($group = null, bool $getShared = true)
{
// If a DB connection is passed in, just pass it back
if ($group instanceof BaseConnection) {
return $group;
}
if (is_array($group)) {
$config = $group;
$group = 'custom-' . md5(json_encode($config));
} else {
$dbConfig = config(DbConfig::class);
if ($group === null) {
$group = (ENVIRONMENT === 'testing') ? 'tests' : $dbConfig->defaultGroup;
}
assert(is_string($group));
if (! isset($dbConfig->{$group})) {
throw new InvalidArgumentException('"' . $group . '" is not a valid database connection group.');
}
$config = $dbConfig->{$group};
}
if ($getShared && isset(static::$instances[$group])) {
return static::$instances[$group];
}
static::ensureFactory();
$connection = static::$factory->load($config, $group);
static::$instances[$group] = $connection;
return $connection;
}
/**
* Returns an array of all db connections currently made.
*/
public static function getConnections(): array
{
return static::$instances;
}
/**
* Loads and returns an instance of the Forge for the specified
* database group, and loads the group if it hasn't been loaded yet.
*
* @param array|ConnectionInterface|string|null $group
*
* @return Forge
*/
public static function forge($group = null)
{
$db = static::connect($group);
return static::$factory->loadForge($db);
}
/**
* Returns a new instance of the Database Utilities class.
*
* @param array|string|null $group
*
* @return BaseUtils
*/
public static function utils($group = null)
{
$db = static::connect($group);
return static::$factory->loadUtils($db);
}
/**
* Returns a new instance of the Database Seeder.
*
* @param non-empty-string|null $group
*
* @return Seeder
*/
public static function seeder(?string $group = null)
{
$config = config(DbConfig::class);
return new Seeder($config, static::connect($group));
}
/**
* Ensures the database Connection Manager/Factory is loaded and ready to use.
*
* @return void
*/
protected static function ensureFactory()
{
if (static::$factory instanceof Database) {
return;
}
static::$factory = new Database();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/PreparedQueryInterface.php | system/Database/PreparedQueryInterface.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\Database;
use CodeIgniter\Exceptions\BadMethodCallException;
/**
* @template TConnection
* @template TStatement
* @template TResult
*/
interface PreparedQueryInterface
{
/**
* Takes a new set of data and runs it against the currently
* prepared query. Upon success, will return a Results object.
*
* @return bool|ResultInterface<TConnection, TResult>
*/
public function execute(...$data);
/**
* Prepares the query against the database, and saves the connection
* info necessary to execute the query later.
*
* @return $this
*/
public function prepare(string $sql, array $options = []);
/**
* Explicity closes the statement.
*
* @throws BadMethodCallException
*/
public function close(): bool;
/**
* Returns the SQL that has been prepared.
*/
public function getQueryString(): string;
/**
* Returns the error code created while executing this statement.
*/
public function getErrorCode(): int;
/**
* Returns the error message created while executing this statement.
*/
public function getErrorMessage(): string;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/BaseConnection.php | system/Database/BaseConnection.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\Database;
use Closure;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Events\Events;
use stdClass;
use Stringable;
use Throwable;
/**
* @property-read array $aliasedTables
* @property-read string $charset
* @property-read bool $compress
* @property-read float $connectDuration
* @property-read float $connectTime
* @property-read string $database
* @property-read array $dateFormat
* @property-read string $DBCollat
* @property-read bool $DBDebug
* @property-read string $DBDriver
* @property-read string $DBPrefix
* @property-read string $DSN
* @property-read array|bool $encrypt
* @property-read array $failover
* @property-read string $hostname
* @property-read Query $lastQuery
* @property-read string $password
* @property-read bool $pConnect
* @property-read int|string $port
* @property-read bool $pretend
* @property-read string $queryClass
* @property-read array $reservedIdentifiers
* @property-read bool $strictOn
* @property-read string $subdriver
* @property-read string $swapPre
* @property-read int $transDepth
* @property-read bool $transFailure
* @property-read bool $transStatus
* @property-read string $username
*
* @template TConnection
* @template TResult
*
* @implements ConnectionInterface<TConnection, TResult>
* @see \CodeIgniter\Database\BaseConnectionTest
*/
abstract class BaseConnection implements ConnectionInterface
{
/**
* Data Source Name / Connect string
*
* @var string
*/
protected $DSN;
/**
* Database port
*
* @var int|string
*/
protected $port = '';
/**
* Hostname
*
* @var string
*/
protected $hostname;
/**
* Username
*
* @var string
*/
protected $username;
/**
* Password
*
* @var string
*/
protected $password;
/**
* Database name
*
* @var string
*/
protected $database;
/**
* Database driver
*
* @var string
*/
protected $DBDriver = 'MySQLi';
/**
* Sub-driver
*
* @used-by CI_DB_pdo_driver
*
* @var string
*/
protected $subdriver;
/**
* Table prefix
*
* @var string
*/
protected $DBPrefix = '';
/**
* Persistent connection flag
*
* @var bool
*/
protected $pConnect = false;
/**
* Whether to throw Exception or not when an error occurs.
*
* @var bool
*/
protected $DBDebug = true;
/**
* Character set
*
* This value must be updated by Config\Database if the driver use it.
*
* @var string
*/
protected $charset = '';
/**
* Collation
*
* This value must be updated by Config\Database if the driver use it.
*
* @var string
*/
protected $DBCollat = '';
/**
* Swap Prefix
*
* @var string
*/
protected $swapPre = '';
/**
* Encryption flag/data
*
* @var array|bool
*/
protected $encrypt = false;
/**
* Compression flag
*
* @var bool
*/
protected $compress = false;
/**
* Strict ON flag
*
* Whether we're running in strict SQL mode.
*
* @var bool|null
*
* @deprecated 4.5.0 Will move to MySQLi\Connection.
*/
protected $strictOn;
/**
* Settings for a failover connection.
*
* @var array
*/
protected $failover = [];
/**
* The last query object that was executed
* on this connection.
*
* @var Query
*/
protected $lastQuery;
/**
* Connection ID
*
* @var false|TConnection
*/
public $connID = false;
/**
* Result ID
*
* @var false|TResult
*/
public $resultID = false;
/**
* Protect identifiers flag
*
* @var bool
*/
public $protectIdentifiers = true;
/**
* List of reserved identifiers
*
* Identifiers that must NOT be escaped.
*
* @var array
*/
protected $reservedIdentifiers = ['*'];
/**
* Identifier escape character
*
* @var array|string
*/
public $escapeChar = '"';
/**
* ESCAPE statement string
*
* @var string
*/
public $likeEscapeStr = " ESCAPE '%s' ";
/**
* ESCAPE character
*
* @var string
*/
public $likeEscapeChar = '!';
/**
* RegExp used to escape identifiers
*
* @var array
*/
protected $pregEscapeChar = [];
/**
* Holds previously looked up data
* for performance reasons.
*
* @var array
*/
public $dataCache = [];
/**
* Microtime when connection was made
*
* @var float
*/
protected $connectTime = 0.0;
/**
* How long it took to establish connection.
*
* @var float
*/
protected $connectDuration = 0.0;
/**
* If true, no queries will actually be
* run against the database.
*
* @var bool
*/
protected $pretend = false;
/**
* Transaction enabled flag
*
* @var bool
*/
public $transEnabled = true;
/**
* Strict transaction mode flag
*
* @var bool
*/
public $transStrict = true;
/**
* Transaction depth level
*
* @var int
*/
protected $transDepth = 0;
/**
* Transaction status flag
*
* Used with transactions to determine if a rollback should occur.
*
* @var bool
*/
protected $transStatus = true;
/**
* Transaction failure flag
*
* Used with transactions to determine if a transaction has failed.
*
* @var bool
*/
protected $transFailure = false;
/**
* Whether to throw exceptions during transaction
*/
protected bool $transException = false;
/**
* Array of table aliases.
*
* @var list<string>
*/
protected $aliasedTables = [];
/**
* Query Class
*
* @var string
*/
protected $queryClass = Query::class;
/**
* Default Date/Time formats
*
* @var array<string, string>
*/
protected array $dateFormat = [
'date' => 'Y-m-d',
'datetime' => 'Y-m-d H:i:s',
'datetime-ms' => 'Y-m-d H:i:s.v',
'datetime-us' => 'Y-m-d H:i:s.u',
'time' => 'H:i:s',
];
/**
* Saves our connection settings.
*/
public function __construct(array $params)
{
if (isset($params['dateFormat'])) {
$this->dateFormat = array_merge($this->dateFormat, $params['dateFormat']);
unset($params['dateFormat']);
}
foreach ($params as $key => $value) {
if (property_exists($this, $key)) {
$this->{$key} = $value;
}
}
$queryClass = str_replace('Connection', 'Query', static::class);
if (class_exists($queryClass)) {
$this->queryClass = $queryClass;
}
if ($this->failover !== []) {
// If there is a failover database, connect now to do failover.
// Otherwise, Query Builder creates SQL statement with the main database config
// (DBPrefix) even when the main database is down.
$this->initialize();
}
}
/**
* Initializes the database connection/settings.
*
* @return void
*
* @throws DatabaseException
*/
public function initialize()
{
/* If an established connection is available, then there's
* no need to connect and select the database.
*
* Depending on the database driver, connID can be either
* boolean TRUE, a resource or an object.
*/
if ($this->connID) {
return;
}
$this->connectTime = microtime(true);
$connectionErrors = [];
try {
// Connect to the database and set the connection ID
$this->connID = $this->connect($this->pConnect);
} catch (Throwable $e) {
$this->connID = false;
$connectionErrors[] = sprintf(
'Main connection [%s]: %s',
$this->DBDriver,
$e->getMessage(),
);
log_message('error', 'Error connecting to the database: ' . $e);
}
// No connection resource? Check if there is a failover else throw an error
if (! $this->connID) {
// Check if there is a failover set
if (! empty($this->failover) && is_array($this->failover)) {
// Go over all the failovers
foreach ($this->failover as $index => $failover) {
// Replace the current settings with those of the failover
foreach ($failover as $key => $val) {
if (property_exists($this, $key)) {
$this->{$key} = $val;
}
}
try {
// Try to connect
$this->connID = $this->connect($this->pConnect);
} catch (Throwable $e) {
$connectionErrors[] = sprintf(
'Failover #%d [%s]: %s',
++$index,
$this->DBDriver,
$e->getMessage(),
);
log_message('error', 'Error connecting to the database: ' . $e);
}
// If a connection is made break the foreach loop
if ($this->connID) {
break;
}
}
}
// We still don't have a connection?
if (! $this->connID) {
throw new DatabaseException(sprintf(
'Unable to connect to the database.%s%s',
PHP_EOL,
implode(PHP_EOL, $connectionErrors),
));
}
}
$this->connectDuration = microtime(true) - $this->connectTime;
}
/**
* Close the database connection.
*
* @return void
*/
public function close()
{
if ($this->connID) {
$this->_close();
$this->connID = false;
}
}
/**
* Platform dependent way method for closing the connection.
*
* @return void
*/
abstract protected function _close();
/**
* Create a persistent database connection.
*
* @return false|TConnection
*/
public function persistentConnect()
{
return $this->connect(true);
}
/**
* Returns the actual connection object. If both a 'read' and 'write'
* connection has been specified, you can pass either term in to
* get that connection. If you pass either alias in and only a single
* connection is present, it must return the sole connection.
*
* @return false|TConnection
*/
public function getConnection(?string $alias = null)
{
// @todo work with read/write connections
return $this->connID;
}
/**
* Returns the name of the current database being used.
*/
public function getDatabase(): string
{
return empty($this->database) ? '' : $this->database;
}
/**
* Set DB Prefix
*
* Set's the DB Prefix to something new without needing to reconnect
*
* @param string $prefix The prefix
*/
public function setPrefix(string $prefix = ''): string
{
return $this->DBPrefix = $prefix;
}
/**
* Returns the database prefix.
*/
public function getPrefix(): string
{
return $this->DBPrefix;
}
/**
* The name of the platform in use (MySQLi, Postgre, SQLite3, OCI8, etc)
*/
public function getPlatform(): string
{
return $this->DBDriver;
}
/**
* Sets the Table Aliases to use. These are typically
* collected during use of the Builder, and set here
* so queries are built correctly.
*
* @return $this
*/
public function setAliasedTables(array $aliases)
{
$this->aliasedTables = $aliases;
return $this;
}
/**
* Add a table alias to our list.
*
* @return $this
*/
public function addTableAlias(string $alias)
{
if ($alias === '') {
return $this;
}
if (! in_array($alias, $this->aliasedTables, true)) {
$this->aliasedTables[] = $alias;
}
return $this;
}
/**
* Executes the query against the database.
*
* @return false|TResult
*/
abstract protected function execute(string $sql);
/**
* Orchestrates a query against the database. Queries must use
* Database\Statement objects to store the query and build it.
* This method works with the cache.
*
* Should automatically handle different connections for read/write
* queries if needed.
*
* @param array|string|null $binds
*
* @return BaseResult<TConnection, TResult>|bool|Query
*
* @todo BC set $queryClass default as null in 4.1
*/
public function query(string $sql, $binds = null, bool $setEscapeFlags = true, string $queryClass = '')
{
$queryClass = $queryClass !== '' && $queryClass !== '0' ? $queryClass : $this->queryClass;
if (empty($this->connID)) {
$this->initialize();
}
/**
* @var Query $query
*/
$query = new $queryClass($this);
$query->setQuery($sql, $binds, $setEscapeFlags);
if (! empty($this->swapPre) && ! empty($this->DBPrefix)) {
$query->swapPrefix($this->DBPrefix, $this->swapPre);
}
$startTime = microtime(true);
// Always save the last query so we can use
// the getLastQuery() method.
$this->lastQuery = $query;
// If $pretend is true, then we just want to return
// the actual query object here. There won't be
// any results to return.
if ($this->pretend) {
$query->setDuration($startTime);
return $query;
}
// Run the query for real
try {
$exception = null;
$this->resultID = $this->simpleQuery($query->getQuery());
} catch (DatabaseException $exception) {
$this->resultID = false;
}
if ($this->resultID === false) {
$query->setDuration($startTime, $startTime);
// This will trigger a rollback if transactions are being used
$this->handleTransStatus();
if (
$this->DBDebug
&& (
// Not in transactions
$this->transDepth === 0
// In transactions, do not throw exception by default.
|| $this->transException
)
) {
// We call this function in order to roll-back queries
// if transactions are enabled. If we don't call this here
// the error message will trigger an exit, causing the
// transactions to remain in limbo.
while ($this->transDepth !== 0) {
$transDepth = $this->transDepth;
$this->transComplete();
if ($transDepth === $this->transDepth) {
log_message('error', 'Database: Failure during an automated transaction commit/rollback!');
break;
}
}
// Let others do something with this query.
Events::trigger('DBQuery', $query);
if ($exception instanceof DatabaseException) {
throw new DatabaseException(
$exception->getMessage(),
$exception->getCode(),
$exception,
);
}
return false;
}
// Let others do something with this query.
Events::trigger('DBQuery', $query);
return false;
}
$query->setDuration($startTime);
// Let others do something with this query
Events::trigger('DBQuery', $query);
// resultID is not false, so it must be successful
if ($this->isWriteType($sql)) {
return true;
}
// query is not write-type, so it must be read-type query; return QueryResult
$resultClass = str_replace('Connection', 'Result', static::class);
return new $resultClass($this->connID, $this->resultID);
}
/**
* Performs a basic query against the database. No binding or caching
* is performed, nor are transactions handled. Simply takes a raw
* query string and returns the database-specific result id.
*
* @return false|TResult
*/
public function simpleQuery(string $sql)
{
if (empty($this->connID)) {
$this->initialize();
}
return $this->execute($sql);
}
/**
* Disable Transactions
*
* This permits transactions to be disabled at run-time.
*
* @return void
*/
public function transOff()
{
$this->transEnabled = false;
}
/**
* Enable/disable Transaction Strict Mode
*
* When strict mode is enabled, if you are running multiple groups of
* transactions, if one group fails all subsequent groups will be
* rolled back.
*
* If strict mode is disabled, each group is treated autonomously,
* meaning a failure of one group will not affect any others
*
* @param bool $mode = true
*
* @return $this
*/
public function transStrict(bool $mode = true)
{
$this->transStrict = $mode;
return $this;
}
/**
* Start Transaction
*/
public function transStart(bool $testMode = false): bool
{
if (! $this->transEnabled) {
return false;
}
return $this->transBegin($testMode);
}
/**
* If set to true, exceptions are thrown during transactions.
*
* @return $this
*/
public function transException(bool $transException)
{
$this->transException = $transException;
return $this;
}
/**
* Complete Transaction
*/
public function transComplete(): bool
{
if (! $this->transEnabled) {
return false;
}
// The query() function will set this flag to FALSE in the event that a query failed
if ($this->transStatus === false || $this->transFailure === true) {
$this->transRollback();
// If we are NOT running in strict mode, we will reset
// the _trans_status flag so that subsequent groups of
// transactions will be permitted.
if ($this->transStrict === false) {
$this->transStatus = true;
}
return false;
}
return $this->transCommit();
}
/**
* Lets you retrieve the transaction flag to determine if it has failed
*/
public function transStatus(): bool
{
return $this->transStatus;
}
/**
* Begin Transaction
*/
public function transBegin(bool $testMode = false): bool
{
if (! $this->transEnabled) {
return false;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
if ($this->transDepth > 0) {
$this->transDepth++;
return true;
}
if (empty($this->connID)) {
$this->initialize();
}
// Reset the transaction failure flag.
// If the $testMode flag is set to TRUE transactions will be rolled back
// even if the queries produce a successful result.
$this->transFailure = $testMode;
if ($this->_transBegin()) {
$this->transDepth++;
return true;
}
return false;
}
/**
* Commit Transaction
*/
public function transCommit(): bool
{
if (! $this->transEnabled || $this->transDepth === 0) {
return false;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
if ($this->transDepth > 1 || $this->_transCommit()) {
$this->transDepth--;
return true;
}
return false;
}
/**
* Rollback Transaction
*/
public function transRollback(): bool
{
if (! $this->transEnabled || $this->transDepth === 0) {
return false;
}
// When transactions are nested we only begin/commit/rollback the outermost ones
if ($this->transDepth > 1 || $this->_transRollback()) {
$this->transDepth--;
return true;
}
return false;
}
/**
* Reset transaction status - to restart transactions after strict mode failure
*/
public function resetTransStatus(): static
{
$this->transStatus = true;
return $this;
}
/**
* Handle transaction status when a query fails
*
* @internal This method is for internal database component use only
*/
public function handleTransStatus(): void
{
if ($this->transDepth !== 0) {
$this->transStatus = false;
}
}
/**
* Begin Transaction
*/
abstract protected function _transBegin(): bool;
/**
* Commit Transaction
*/
abstract protected function _transCommit(): bool;
/**
* Rollback Transaction
*/
abstract protected function _transRollback(): bool;
/**
* Returns a non-shared new instance of the query builder for this connection.
*
* @param array|string|TableName $tableName
*
* @return BaseBuilder
*
* @throws DatabaseException
*/
public function table($tableName)
{
if (empty($tableName)) {
throw new DatabaseException('You must set the database table to be used with your query.');
}
$className = str_replace('Connection', 'Builder', static::class);
return new $className($tableName, $this);
}
/**
* Returns a new instance of the BaseBuilder class with a cleared FROM clause.
*/
public function newQuery(): BaseBuilder
{
// save table aliases
$tempAliases = $this->aliasedTables;
$builder = $this->table(',')->from([], true);
$this->aliasedTables = $tempAliases;
return $builder;
}
/**
* Creates a prepared statement with the database that can then
* be used to execute multiple statements against. Within the
* closure, you would build the query in any normal way, though
* the Query Builder is the expected manner.
*
* Example:
* $stmt = $db->prepare(function($db)
* {
* return $db->table('users')
* ->where('id', 1)
* ->get();
* })
*
* @param Closure(BaseConnection): mixed $func
*
* @return BasePreparedQuery|null
*/
public function prepare(Closure $func, array $options = [])
{
if (empty($this->connID)) {
$this->initialize();
}
$this->pretend();
$sql = $func($this);
$this->pretend(false);
if ($sql instanceof QueryInterface) {
$sql = $sql->getOriginalQuery();
}
$class = str_ireplace('Connection', 'PreparedQuery', static::class);
/** @var BasePreparedQuery $class */
$class = new $class($this);
return $class->prepare($sql, $options);
}
/**
* Returns the last query's statement object.
*
* @return Query
*/
public function getLastQuery()
{
return $this->lastQuery;
}
/**
* Returns a string representation of the last query's statement object.
*/
public function showLastQuery(): string
{
return (string) $this->lastQuery;
}
/**
* Returns the time we started to connect to this database in
* seconds with microseconds.
*
* Used by the Debug Toolbar's timeline.
*/
public function getConnectStart(): ?float
{
return $this->connectTime;
}
/**
* Returns the number of seconds with microseconds that it took
* to connect to the database.
*
* Used by the Debug Toolbar's timeline.
*/
public function getConnectDuration(int $decimals = 6): string
{
return number_format($this->connectDuration, $decimals);
}
/**
* Protect Identifiers
*
* This function is used extensively by the Query Builder class, and by
* a couple functions in this class.
* It takes a column or table name (optionally with an alias) and inserts
* the table prefix onto it. Some logic is necessary in order to deal with
* column names that include the path. Consider a query like this:
*
* SELECT hostname.database.table.column AS c FROM hostname.database.table
*
* Or a query with aliasing:
*
* SELECT m.member_id, m.member_name FROM members AS m
*
* Since the column name can include up to four segments (host, DB, table, column)
* or also have an alias prefix, we need to do a bit of work to figure this out and
* insert the table prefix (if it exists) in the proper position, and escape only
* the correct identifiers.
*
* @param array|int|string|TableName $item
* @param bool $prefixSingle Prefix a table name with no segments?
* @param bool $protectIdentifiers Protect table or column names?
* @param bool $fieldExists Supplied $item contains a column name?
*
* @return ($item is array ? array : string)
*/
public function protectIdentifiers($item, bool $prefixSingle = false, ?bool $protectIdentifiers = null, bool $fieldExists = true)
{
if (! is_bool($protectIdentifiers)) {
$protectIdentifiers = $this->protectIdentifiers;
}
if (is_array($item)) {
$escapedArray = [];
foreach ($item as $k => $v) {
$escapedArray[$this->protectIdentifiers($k)] = $this->protectIdentifiers($v, $prefixSingle, $protectIdentifiers, $fieldExists);
}
return $escapedArray;
}
if ($item instanceof TableName) {
/** @psalm-suppress NoValue I don't know why ERROR. */
return $this->escapeTableName($item);
}
// If you pass `['column1', 'column2']`, `$item` will be int because the array keys are int.
$item = (string) $item;
// This is basically a bug fix for queries that use MAX, MIN, etc.
// If a parenthesis is found we know that we do not need to
// escape the data or add a prefix. There's probably a more graceful
// way to deal with this, but I'm not thinking of it
//
// Added exception for single quotes as well, we don't want to alter
// literal strings.
if (strcspn($item, "()'") !== strlen($item)) {
/** @psalm-suppress NoValue I don't know why ERROR. */
return $item;
}
// Do not protect identifiers and do not prefix, no swap prefix, there is nothing to do
if ($protectIdentifiers === false && $prefixSingle === false && $this->swapPre === '') {
/** @psalm-suppress NoValue I don't know why ERROR. */
return $item;
}
// Convert tabs or multiple spaces into single spaces
/** @psalm-suppress NoValue I don't know why ERROR. */
$item = preg_replace('/\s+/', ' ', trim($item));
// If the item has an alias declaration we remove it and set it aside.
// Note: strripos() is used in order to support spaces in table names
if ($offset = strripos($item, ' AS ')) {
$alias = ($protectIdentifiers) ? substr($item, $offset, 4) . $this->escapeIdentifiers(substr($item, $offset + 4)) : substr($item, $offset);
$item = substr($item, 0, $offset);
} elseif ($offset = strrpos($item, ' ')) {
$alias = ($protectIdentifiers) ? ' ' . $this->escapeIdentifiers(substr($item, $offset + 1)) : substr($item, $offset);
$item = substr($item, 0, $offset);
} else {
$alias = '';
}
// Break the string apart if it contains periods, then insert the table prefix
// in the correct location, assuming the period doesn't indicate that we're dealing
// with an alias. While we're at it, we will escape the components
if (str_contains($item, '.')) {
return $this->protectDotItem($item, $alias, $protectIdentifiers, $fieldExists);
}
// In some cases, especially 'from', we end up running through
// protect_identifiers twice. This algorithm won't work when
// it contains the escapeChar so strip it out.
$item = trim($item, $this->escapeChar);
// Is there a table prefix? If not, no need to insert it
if ($this->DBPrefix !== '') {
// Verify table prefix and replace if necessary
if ($this->swapPre !== '' && str_starts_with($item, $this->swapPre)) {
$item = preg_replace('/^' . $this->swapPre . '(\S+?)/', $this->DBPrefix . '\\1', $item);
}
// Do we prefix an item with no segments?
elseif ($prefixSingle && ! str_starts_with($item, $this->DBPrefix)) {
$item = $this->DBPrefix . $item;
}
}
if ($protectIdentifiers === true && ! in_array($item, $this->reservedIdentifiers, true)) {
$item = $this->escapeIdentifiers($item);
}
return $item . $alias;
}
private function protectDotItem(string $item, string $alias, bool $protectIdentifiers, bool $fieldExists): string
{
$parts = explode('.', $item);
// Does the first segment of the exploded item match
// one of the aliases previously identified? If so,
// we have nothing more to do other than escape the item
//
// NOTE: The ! empty() condition prevents this method
// from breaking when QB isn't enabled.
if (! empty($this->aliasedTables) && in_array($parts[0], $this->aliasedTables, true)) {
if ($protectIdentifiers) {
foreach ($parts as $key => $val) {
if (! in_array($val, $this->reservedIdentifiers, true)) {
$parts[$key] = $this->escapeIdentifiers($val);
}
}
$item = implode('.', $parts);
}
return $item . $alias;
}
// Is there a table prefix defined in the config file? If not, no need to do anything
if ($this->DBPrefix !== '') {
// We now add the table prefix based on some logic.
// Do we have 4 segments (hostname.database.table.column)?
// If so, we add the table prefix to the column name in the 3rd segment.
if (isset($parts[3])) {
$i = 2;
}
// Do we have 3 segments (database.table.column)?
// If so, we add the table prefix to the column name in 2nd position
elseif (isset($parts[2])) {
$i = 1;
}
// Do we have 2 segments (table.column)?
// If so, we add the table prefix to the column name in 1st segment
else {
$i = 0;
}
// This flag is set when the supplied $item does not contain a field name.
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | true |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/Query.php | system/Database/Query.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\Database;
use Stringable;
/**
* Query builder
*/
class Query implements QueryInterface, Stringable
{
/**
* The query string, as provided by the user.
*
* @var string
*/
protected $originalQueryString;
/**
* The query string if table prefix has been swapped.
*
* @var string|null
*/
protected $swappedQueryString;
/**
* The final query string after binding, etc.
*
* @var string|null
*/
protected $finalQueryString;
/**
* The binds and their values used for binding.
*
* @var array
*/
protected $binds = [];
/**
* Bind marker
*
* Character used to identify values in a prepared statement.
*
* @var string
*/
protected $bindMarker = '?';
/**
* The start time in seconds with microseconds
* for when this query was executed.
*
* @var float|string
*/
protected $startTime;
/**
* The end time in seconds with microseconds
* for when this query was executed.
*
* @var float
*/
protected $endTime;
/**
* The error code, if any.
*
* @var int
*/
protected $errorCode;
/**
* The error message, if any.
*
* @var string
*/
protected $errorString;
/**
* Pointer to database connection.
* Mainly for escaping features.
*
* @var ConnectionInterface
*/
public $db;
public function __construct(ConnectionInterface $db)
{
$this->db = $db;
}
/**
* Sets the raw query string to use for this statement.
*
* @param mixed $binds
*
* @return $this
*/
public function setQuery(string $sql, $binds = null, bool $setEscape = true)
{
$this->originalQueryString = $sql;
unset($this->swappedQueryString);
if ($binds !== null) {
if (! is_array($binds)) {
$binds = [$binds];
}
if ($setEscape) {
array_walk($binds, static function (&$item): void {
$item = [
$item,
true,
];
});
}
$this->binds = $binds;
}
unset($this->finalQueryString);
return $this;
}
/**
* Will store the variables to bind into the query later.
*
* @return $this
*/
public function setBinds(array $binds, bool $setEscape = true)
{
if ($setEscape) {
array_walk($binds, static function (&$item): void {
$item = [$item, true];
});
}
$this->binds = $binds;
unset($this->finalQueryString);
return $this;
}
/**
* Returns the final, processed query string after binding, etal
* has been performed.
*/
public function getQuery(): string
{
if (empty($this->finalQueryString)) {
$this->compileBinds();
}
return $this->finalQueryString;
}
/**
* Records the execution time of the statement using microtime(true)
* for it's start and end values. If no end value is present, will
* use the current time to determine total duration.
*
* @return $this
*/
public function setDuration(float $start, ?float $end = null)
{
$this->startTime = $start;
if ($end === null) {
$end = microtime(true);
}
$this->endTime = $end;
return $this;
}
/**
* Returns the start time in seconds with microseconds.
*
* @return float|string
*/
public function getStartTime(bool $returnRaw = false, int $decimals = 6)
{
if ($returnRaw) {
return $this->startTime;
}
return number_format($this->startTime, $decimals);
}
/**
* Returns the duration of this query during execution, or null if
* the query has not been executed yet.
*
* @param int $decimals The accuracy of the returned time.
*/
public function getDuration(int $decimals = 6): string
{
return number_format(($this->endTime - $this->startTime), $decimals);
}
/**
* Stores the error description that happened for this query.
*
* @return $this
*/
public function setError(int $code, string $error)
{
$this->errorCode = $code;
$this->errorString = $error;
return $this;
}
/**
* Reports whether this statement created an error not.
*/
public function hasError(): bool
{
return ! empty($this->errorString);
}
/**
* Returns the error code created while executing this statement.
*/
public function getErrorCode(): int
{
return $this->errorCode;
}
/**
* Returns the error message created while executing this statement.
*/
public function getErrorMessage(): string
{
return $this->errorString;
}
/**
* Determines if the statement is a write-type query or not.
*/
public function isWriteType(): bool
{
return $this->db->isWriteType($this->originalQueryString);
}
/**
* Swaps out one table prefix for a new one.
*
* @return $this
*/
public function swapPrefix(string $orig, string $swap)
{
$sql = $this->swappedQueryString ?? $this->originalQueryString;
$from = '/(\W)' . $orig . '(\S)/';
$to = '\\1' . $swap . '\\2';
$this->swappedQueryString = preg_replace($from, $to, $sql);
unset($this->finalQueryString);
return $this;
}
/**
* Returns the original SQL that was passed into the system.
*/
public function getOriginalQuery(): string
{
return $this->originalQueryString;
}
/**
* Escapes and inserts any binds into the finalQueryString property.
*
* @see https://regex101.com/r/EUEhay/5
*
* @return void
*/
protected function compileBinds()
{
$sql = $this->swappedQueryString ?? $this->originalQueryString;
$binds = $this->binds;
if (empty($binds)) {
$this->finalQueryString = $sql;
return;
}
if (is_int(array_key_first($binds))) {
$bindCount = count($binds);
$ml = strlen($this->bindMarker);
$this->finalQueryString = $this->matchSimpleBinds($sql, $binds, $bindCount, $ml);
} else {
// Reverse the binds so that duplicate named binds
// will be processed prior to the original binds.
$binds = array_reverse($binds);
$this->finalQueryString = $this->matchNamedBinds($sql, $binds);
}
}
/**
* Match bindings
*/
protected function matchNamedBinds(string $sql, array $binds): string
{
$replacers = [];
foreach ($binds as $placeholder => $value) {
// $value[1] contains the boolean whether should be escaped or not
$escapedValue = $value[1] ? $this->db->escape($value[0]) : $value[0];
// In order to correctly handle backlashes in saved strings
// we will need to preg_quote, so remove the wrapping escape characters
// otherwise it will get escaped.
if (is_array($value[0])) {
$escapedValue = '(' . implode(',', $escapedValue) . ')';
}
$replacers[":{$placeholder}:"] = $escapedValue;
}
return strtr($sql, $replacers);
}
/**
* Match bindings
*/
protected function matchSimpleBinds(string $sql, array $binds, int $bindCount, int $ml): string
{
if ($c = preg_match_all("/'[^']*'/", $sql, $matches) >= 1) {
$c = preg_match_all('/' . preg_quote($this->bindMarker, '/') . '/i', str_replace($matches[0], str_replace($this->bindMarker, str_repeat(' ', $ml), $matches[0]), $sql, $c), $matches, PREG_OFFSET_CAPTURE);
// Bind values' count must match the count of markers in the query
if ($bindCount !== $c) {
return $sql;
}
} elseif (($c = preg_match_all('/' . preg_quote($this->bindMarker, '/') . '/i', $sql, $matches, PREG_OFFSET_CAPTURE)) !== $bindCount) {
return $sql;
}
do {
$c--;
$escapedValue = $binds[$c][1] ? $this->db->escape($binds[$c][0]) : $binds[$c][0];
if (is_array($escapedValue)) {
$escapedValue = '(' . implode(',', $escapedValue) . ')';
}
$sql = substr_replace($sql, (string) $escapedValue, $matches[0][$c][1], $ml);
} while ($c !== 0);
return $sql;
}
/**
* Returns string to display in debug toolbar
*/
public function debugToolbarDisplay(): string
{
// Key words we want bolded
static $highlight = [
'AND',
'AS',
'ASC',
'AVG',
'BY',
'COUNT',
'DESC',
'DISTINCT',
'FROM',
'GROUP',
'HAVING',
'IN',
'INNER',
'INSERT',
'INTO',
'IS',
'JOIN',
'LEFT',
'LIKE',
'LIMIT',
'MAX',
'MIN',
'NOT',
'NULL',
'OFFSET',
'ON',
'OR',
'ORDER',
'RIGHT',
'SELECT',
'SUM',
'UPDATE',
'VALUES',
'WHERE',
];
$sql = esc($this->getQuery());
/**
* @see https://stackoverflow.com/a/20767160
* @see https://regex101.com/r/hUlrGN/4
*/
$search = '/\b(?:' . implode('|', $highlight) . ')\b(?![^(')]*'(?:(?:[^(')]*'){2})*[^(')]*$)/';
return preg_replace_callback($search, static fn ($matches): string => '<strong>' . str_replace(' ', ' ', $matches[0]) . '</strong>', $sql);
}
/**
* Return text representation of the query
*/
public function __toString(): string
{
return $this->getQuery();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/BaseBuilder.php | system/Database/BaseBuilder.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\Database;
use Closure;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\Exceptions\DataException;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Traits\ConditionalTrait;
use Config\Feature;
/**
* Class BaseBuilder
*
* Provides the core Query Builder methods.
* Database-specific Builders might need to override
* certain methods to make them work.
*/
class BaseBuilder
{
use ConditionalTrait;
/**
* Reset DELETE data flag
*
* @var bool
*/
protected $resetDeleteData = false;
/**
* QB SELECT data
*
* @var array
*/
protected $QBSelect = [];
/**
* QB DISTINCT flag
*
* @var bool
*/
protected $QBDistinct = false;
/**
* QB FROM data
*
* @var array
*/
protected $QBFrom = [];
/**
* QB JOIN data
*
* @var array
*/
protected $QBJoin = [];
/**
* QB WHERE data
*
* @var array
*/
protected $QBWhere = [];
/**
* QB GROUP BY data
*
* @var array
*/
public $QBGroupBy = [];
/**
* QB HAVING data
*
* @var array
*/
protected $QBHaving = [];
/**
* QB keys
* list of column names.
*
* @var list<string>
*/
protected $QBKeys = [];
/**
* QB LIMIT data
*
* @var bool|int
*/
protected $QBLimit = false;
/**
* QB OFFSET data
*
* @var bool|int
*/
protected $QBOffset = false;
/**
* QB ORDER BY data
*
* @var array|string|null
*/
public $QBOrderBy = [];
/**
* QB UNION data
*
* @var list<string>
*/
protected array $QBUnion = [];
/**
* Whether to protect identifiers in SELECT
*
* @var list<bool|null> true=protect, false=not protect
*/
public $QBNoEscape = [];
/**
* QB data sets
*
* @var array<string, string>|list<list<int|string>>
*/
protected $QBSet = [];
/**
* QB WHERE group started flag
*
* @var bool
*/
protected $QBWhereGroupStarted = false;
/**
* QB WHERE group count
*
* @var int
*/
protected $QBWhereGroupCount = 0;
/**
* Ignore data that cause certain
* exceptions, for example in case of
* duplicate keys.
*
* @var bool
*/
protected $QBIgnore = false;
/**
* QB Options data
* Holds additional options and data used to render SQL
* and is reset by resetWrite()
*
* @var array{
* updateFieldsAdditional?: array,
* tableIdentity?: string,
* updateFields?: array,
* constraints?: array,
* setQueryAsData?: string,
* sql?: string,
* alias?: string,
* fieldTypes?: array<string, array<string, string>>
* }
*
* fieldTypes: [ProtectedTableName => [FieldName => Type]]
*/
protected $QBOptions;
/**
* A reference to the database connection.
*
* @var BaseConnection
*/
protected $db;
/**
* Name of the primary table for this instance.
* Tracked separately because $QBFrom gets escaped
* and prefixed.
*
* When $tableName to the constructor has multiple tables,
* the value is empty string.
*
* @var string
*/
protected $tableName;
/**
* ORDER BY random keyword
*
* @var array
*/
protected $randomKeyword = [
'RAND()',
'RAND(%d)',
];
/**
* COUNT string
*
* @used-by CI_DB_driver::count_all()
* @used-by BaseBuilder::count_all_results()
*
* @var string
*/
protected $countString = 'SELECT COUNT(*) AS ';
/**
* Collects the named parameters and
* their values for later binding
* in the Query object.
*
* @var array
*/
protected $binds = [];
/**
* Collects the key count for named parameters
* in the Query object.
*
* @var array
*/
protected $bindsKeyCount = [];
/**
* Some databases, like SQLite, do not by default
* allow limiting of delete clauses.
*
* @var bool
*/
protected $canLimitDeletes = true;
/**
* Some databases do not by default
* allow limit update queries with WHERE.
*
* @var bool
*/
protected $canLimitWhereUpdates = true;
/**
* Specifies which sql statements
* support the ignore option.
*
* @var array<string, string>
*/
protected $supportedIgnoreStatements = [];
/**
* Builder testing mode status.
*
* @var bool
*/
protected $testMode = false;
/**
* Tables relation types
*
* @var array
*/
protected $joinTypes = [
'LEFT',
'RIGHT',
'OUTER',
'INNER',
'LEFT OUTER',
'RIGHT OUTER',
];
/**
* Strings that determine if a string represents a literal value or a field name
*
* @var list<string>
*/
protected $isLiteralStr = [];
/**
* RegExp used to get operators
*
* @var list<string>
*/
protected $pregOperators = [];
/**
* Constructor
*
* @param array|string|TableName $tableName tablename or tablenames with or without aliases
*
* Examples of $tableName: `mytable`, `jobs j`, `jobs j, users u`, `['jobs j','users u']`
*
* @throws DatabaseException
*/
public function __construct($tableName, ConnectionInterface $db, ?array $options = null)
{
if (empty($tableName)) {
throw new DatabaseException('A table must be specified when creating a new Query Builder.');
}
/**
* @var BaseConnection $db
*/
$this->db = $db;
if ($tableName instanceof TableName) {
$this->tableName = $tableName->getTableName();
$this->QBFrom[] = $this->db->escapeIdentifier($tableName);
$this->db->addTableAlias($tableName->getAlias());
}
// If it contains `,`, it has multiple tables
elseif (is_string($tableName) && ! str_contains($tableName, ',')) {
$this->tableName = $tableName; // @TODO remove alias if exists
$this->from($tableName);
} else {
$this->tableName = '';
$this->from($tableName);
}
if ($options !== null && $options !== []) {
foreach ($options as $key => $value) {
if (property_exists($this, $key)) {
$this->{$key} = $value;
}
}
}
}
/**
* Returns the current database connection
*
* @return BaseConnection
*/
public function db(): ConnectionInterface
{
return $this->db;
}
/**
* Sets a test mode status.
*
* @return $this
*/
public function testMode(bool $mode = true)
{
$this->testMode = $mode;
return $this;
}
/**
* Gets the name of the primary table.
*/
public function getTable(): string
{
return $this->tableName;
}
/**
* Returns an array of bind values and their
* named parameters for binding in the Query object later.
*/
public function getBinds(): array
{
return $this->binds;
}
/**
* Ignore
*
* Set ignore Flag for next insert,
* update or delete query.
*
* @return $this
*/
public function ignore(bool $ignore = true)
{
$this->QBIgnore = $ignore;
return $this;
}
/**
* Generates the SELECT portion of the query
*
* @param list<RawSql|string>|RawSql|string $select
* @param bool|null $escape Whether to protect identifiers
*
* @return $this
*/
public function select($select = '*', ?bool $escape = null)
{
// If the escape value was not set, we will base it on the global setting
if (! is_bool($escape)) {
$escape = $this->db->protectIdentifiers;
}
if ($select instanceof RawSql) {
$select = [$select];
}
if (is_string($select)) {
$select = ($escape === false) ? [$select] : explode(',', $select);
}
foreach ($select as $val) {
if ($val instanceof RawSql) {
$this->QBSelect[] = $val;
$this->QBNoEscape[] = false;
continue;
}
$val = trim($val);
if ($val !== '') {
$this->QBSelect[] = $val;
/*
* When doing 'SELECT NULL as field_alias FROM table'
* null gets taken as a field, and therefore escaped
* with backticks.
* This prevents NULL being escaped
* @see https://github.com/codeigniter4/CodeIgniter4/issues/1169
*/
if (mb_stripos($val, 'NULL') === 0) {
$this->QBNoEscape[] = false;
continue;
}
$this->QBNoEscape[] = $escape;
}
}
return $this;
}
/**
* Generates a SELECT MAX(field) portion of a query
*
* @return $this
*/
public function selectMax(string $select = '', string $alias = '')
{
return $this->maxMinAvgSum($select, $alias);
}
/**
* Generates a SELECT MIN(field) portion of a query
*
* @return $this
*/
public function selectMin(string $select = '', string $alias = '')
{
return $this->maxMinAvgSum($select, $alias, 'MIN');
}
/**
* Generates a SELECT AVG(field) portion of a query
*
* @return $this
*/
public function selectAvg(string $select = '', string $alias = '')
{
return $this->maxMinAvgSum($select, $alias, 'AVG');
}
/**
* Generates a SELECT SUM(field) portion of a query
*
* @return $this
*/
public function selectSum(string $select = '', string $alias = '')
{
return $this->maxMinAvgSum($select, $alias, 'SUM');
}
/**
* Generates a SELECT COUNT(field) portion of a query
*
* @return $this
*/
public function selectCount(string $select = '', string $alias = '')
{
return $this->maxMinAvgSum($select, $alias, 'COUNT');
}
/**
* Adds a subquery to the selection
*/
public function selectSubquery(BaseBuilder $subquery, string $as): self
{
$this->QBSelect[] = $this->buildSubquery($subquery, true, $as);
return $this;
}
/**
* SELECT [MAX|MIN|AVG|SUM|COUNT]()
*
* @used-by selectMax()
* @used-by selectMin()
* @used-by selectAvg()
* @used-by selectSum()
*
* @return $this
*
* @throws DatabaseException
* @throws DataException
*/
protected function maxMinAvgSum(string $select = '', string $alias = '', string $type = 'MAX')
{
if ($select === '') {
throw DataException::forEmptyInputGiven('Select');
}
if (str_contains($select, ',')) {
throw DataException::forInvalidArgument('column name not separated by comma');
}
$type = strtoupper($type);
if (! in_array($type, ['MAX', 'MIN', 'AVG', 'SUM', 'COUNT'], true)) {
throw new DatabaseException('Invalid function type: ' . $type);
}
if ($alias === '') {
$alias = $this->createAliasFromTable(trim($select));
}
$sql = $type . '(' . $this->db->protectIdentifiers(trim($select)) . ') AS ' . $this->db->escapeIdentifiers(trim($alias));
$this->QBSelect[] = $sql;
$this->QBNoEscape[] = null;
return $this;
}
/**
* Determines the alias name based on the table
*/
protected function createAliasFromTable(string $item): string
{
if (str_contains($item, '.')) {
$item = explode('.', $item);
return end($item);
}
return $item;
}
/**
* Sets a flag which tells the query string compiler to add DISTINCT
*
* @return $this
*/
public function distinct(bool $val = true)
{
$this->QBDistinct = $val;
return $this;
}
/**
* Generates the FROM portion of the query
*
* @param array|string $from
*
* @return $this
*/
public function from($from, bool $overwrite = false): self
{
if ($overwrite) {
$this->QBFrom = [];
$this->db->setAliasedTables([]);
}
foreach ((array) $from as $table) {
if (str_contains($table, ',')) {
$this->from(explode(',', $table));
} else {
$table = trim($table);
if ($table === '') {
continue;
}
$this->trackAliases($table);
$this->QBFrom[] = $this->db->protectIdentifiers($table, true, null, false);
}
}
return $this;
}
/**
* @param BaseBuilder $from Expected subquery
* @param string $alias Subquery alias
*
* @return $this
*/
public function fromSubquery(BaseBuilder $from, string $alias): self
{
$table = $this->buildSubquery($from, true, $alias);
$this->db->addTableAlias($alias);
$this->QBFrom[] = $table;
return $this;
}
/**
* Generates the JOIN portion of the query
*
* @param RawSql|string $cond
*
* @return $this
*/
public function join(string $table, $cond, string $type = '', ?bool $escape = null)
{
if ($type !== '') {
$type = strtoupper(trim($type));
if (! in_array($type, $this->joinTypes, true)) {
$type = '';
} else {
$type .= ' ';
}
}
// Extract any aliases that might exist. We use this information
// in the protectIdentifiers to know whether to add a table prefix
$this->trackAliases($table);
if (! is_bool($escape)) {
$escape = $this->db->protectIdentifiers;
}
// Do we want to escape the table name?
if ($escape === true) {
$table = $this->db->protectIdentifiers($table, true, null, false);
}
if ($cond instanceof RawSql) {
$this->QBJoin[] = $type . 'JOIN ' . $table . ' ON ' . $cond;
return $this;
}
if (! $this->hasOperator($cond)) {
$cond = ' USING (' . ($escape ? $this->db->escapeIdentifiers($cond) : $cond) . ')';
} elseif ($escape === false) {
$cond = ' ON ' . $cond;
} else {
// Split multiple conditions
// @TODO This does not parse `BETWEEN a AND b` correctly.
if (preg_match_all('/\sAND\s|\sOR\s/i', $cond, $joints, PREG_OFFSET_CAPTURE) >= 1) {
$conditions = [];
$joints = $joints[0];
array_unshift($joints, ['', 0]);
for ($i = count($joints) - 1, $pos = strlen($cond); $i >= 0; $i--) {
$joints[$i][1] += strlen($joints[$i][0]); // offset
$conditions[$i] = substr($cond, $joints[$i][1], $pos - $joints[$i][1]);
$pos = $joints[$i][1] - strlen($joints[$i][0]);
$joints[$i] = $joints[$i][0];
}
ksort($conditions);
} else {
$conditions = [$cond];
$joints = [''];
}
$cond = ' ON ';
foreach ($conditions as $i => $condition) {
$operator = $this->getOperator($condition);
// Workaround for BETWEEN
if ($operator === false) {
$cond .= $joints[$i] . $condition;
continue;
}
$cond .= $joints[$i];
$cond .= preg_match('/(\(*)?([\[\]\w\.\'-]+)' . preg_quote($operator, '/') . '(.*)/i', $condition, $match) ? $match[1] . $this->db->protectIdentifiers($match[2]) . $operator . $this->db->protectIdentifiers($match[3]) : $condition;
}
}
// Assemble the JOIN statement
$this->QBJoin[] = $type . 'JOIN ' . $table . $cond;
return $this;
}
/**
* Generates the WHERE portion of the query.
* Separates multiple calls with 'AND'.
*
* @param array|RawSql|string $key
* @param mixed $value
*
* @return $this
*/
public function where($key, $value = null, ?bool $escape = null)
{
return $this->whereHaving('QBWhere', $key, $value, 'AND ', $escape);
}
/**
* OR WHERE
*
* Generates the WHERE portion of the query.
* Separates multiple calls with 'OR'.
*
* @param array|RawSql|string $key
* @param mixed $value
*
* @return $this
*/
public function orWhere($key, $value = null, ?bool $escape = null)
{
return $this->whereHaving('QBWhere', $key, $value, 'OR ', $escape);
}
/**
* @used-by where()
* @used-by orWhere()
* @used-by having()
* @used-by orHaving()
*
* @param array|RawSql|string $key
* @param mixed $value
*
* @return $this
*/
protected function whereHaving(string $qbKey, $key, $value = null, string $type = 'AND ', ?bool $escape = null)
{
$rawSqlOnly = false;
if ($key instanceof RawSql) {
if ($value === null) {
$keyValue = [(string) $key => $key];
$rawSqlOnly = true;
} else {
$keyValue = [(string) $key => $value];
}
} elseif (! is_array($key)) {
$keyValue = [$key => $value];
} else {
$keyValue = $key;
}
// If the escape value was not set will base it on the global setting
if (! is_bool($escape)) {
$escape = $this->db->protectIdentifiers;
}
foreach ($keyValue as $k => $v) {
$prefix = empty($this->{$qbKey}) ? $this->groupGetType('') : $this->groupGetType($type);
if ($rawSqlOnly) {
$k = '';
$op = '';
} elseif ($v !== null) {
$op = $this->getOperatorFromWhereKey($k);
if (! empty($op)) {
$k = trim($k);
end($op);
$op = trim(current($op));
// Does the key end with operator?
if (str_ends_with($k, $op)) {
$k = rtrim(substr($k, 0, -strlen($op)));
$op = " {$op}";
} else {
$op = '';
}
} else {
$op = ' =';
}
if ($this->isSubquery($v)) {
$v = $this->buildSubquery($v, true);
} else {
$bind = $this->setBind($k, $v, $escape);
$v = " :{$bind}:";
}
} elseif (! $this->hasOperator($k) && $qbKey !== 'QBHaving') {
// value appears not to have been set, assign the test to IS NULL
$op = ' IS NULL';
} elseif (
// The key ends with !=, =, <>, IS, IS NOT
preg_match(
'/\s*(!?=|<>|IS(?:\s+NOT)?)\s*$/i',
$k,
$match,
PREG_OFFSET_CAPTURE,
)
) {
$k = substr($k, 0, $match[0][1]);
$op = $match[1][0] === '=' ? ' IS NULL' : ' IS NOT NULL';
} else {
$op = '';
}
if ($v instanceof RawSql) {
$this->{$qbKey}[] = [
'condition' => $v->with($prefix . $k . $op . $v),
'escape' => $escape,
];
} else {
$this->{$qbKey}[] = [
'condition' => $prefix . $k . $op . $v,
'escape' => $escape,
];
}
}
return $this;
}
/**
* Generates a WHERE field IN('item', 'item') SQL query,
* joined with 'AND' if appropriate.
*
* @param array|BaseBuilder|(Closure(BaseBuilder): BaseBuilder)|null $values The values searched on, or anonymous function with subquery
*
* @return $this
*/
public function whereIn(?string $key = null, $values = null, ?bool $escape = null)
{
return $this->_whereIn($key, $values, false, 'AND ', $escape);
}
/**
* Generates a WHERE field IN('item', 'item') SQL query,
* joined with 'OR' if appropriate.
*
* @param array|BaseBuilder|(Closure(BaseBuilder): BaseBuilder)|null $values The values searched on, or anonymous function with subquery
*
* @return $this
*/
public function orWhereIn(?string $key = null, $values = null, ?bool $escape = null)
{
return $this->_whereIn($key, $values, false, 'OR ', $escape);
}
/**
* Generates a WHERE field NOT IN('item', 'item') SQL query,
* joined with 'AND' if appropriate.
*
* @param array|BaseBuilder|(Closure(BaseBuilder): BaseBuilder)|null $values The values searched on, or anonymous function with subquery
*
* @return $this
*/
public function whereNotIn(?string $key = null, $values = null, ?bool $escape = null)
{
return $this->_whereIn($key, $values, true, 'AND ', $escape);
}
/**
* Generates a WHERE field NOT IN('item', 'item') SQL query,
* joined with 'OR' if appropriate.
*
* @param array|BaseBuilder|(Closure(BaseBuilder): BaseBuilder)|null $values The values searched on, or anonymous function with subquery
*
* @return $this
*/
public function orWhereNotIn(?string $key = null, $values = null, ?bool $escape = null)
{
return $this->_whereIn($key, $values, true, 'OR ', $escape);
}
/**
* Generates a HAVING field IN('item', 'item') SQL query,
* joined with 'AND' if appropriate.
*
* @param array|BaseBuilder|(Closure(BaseBuilder): BaseBuilder)|null $values The values searched on, or anonymous function with subquery
*
* @return $this
*/
public function havingIn(?string $key = null, $values = null, ?bool $escape = null)
{
return $this->_whereIn($key, $values, false, 'AND ', $escape, 'QBHaving');
}
/**
* Generates a HAVING field IN('item', 'item') SQL query,
* joined with 'OR' if appropriate.
*
* @param array|BaseBuilder|(Closure(BaseBuilder): BaseBuilder)|null $values The values searched on, or anonymous function with subquery
*
* @return $this
*/
public function orHavingIn(?string $key = null, $values = null, ?bool $escape = null)
{
return $this->_whereIn($key, $values, false, 'OR ', $escape, 'QBHaving');
}
/**
* Generates a HAVING field NOT IN('item', 'item') SQL query,
* joined with 'AND' if appropriate.
*
* @param array|BaseBuilder|(Closure(BaseBuilder):BaseBuilder)|null $values The values searched on, or anonymous function with subquery
*
* @return $this
*/
public function havingNotIn(?string $key = null, $values = null, ?bool $escape = null)
{
return $this->_whereIn($key, $values, true, 'AND ', $escape, 'QBHaving');
}
/**
* Generates a HAVING field NOT IN('item', 'item') SQL query,
* joined with 'OR' if appropriate.
*
* @param array|BaseBuilder|(Closure(BaseBuilder): BaseBuilder)|null $values The values searched on, or anonymous function with subquery
*
* @return $this
*/
public function orHavingNotIn(?string $key = null, $values = null, ?bool $escape = null)
{
return $this->_whereIn($key, $values, true, 'OR ', $escape, 'QBHaving');
}
/**
* @used-by WhereIn()
* @used-by orWhereIn()
* @used-by whereNotIn()
* @used-by orWhereNotIn()
*
* @param non-empty-string|null $key
* @param array|BaseBuilder|(Closure(BaseBuilder): BaseBuilder)|null $values The values searched on, or anonymous function with subquery
*
* @return $this
*
* @throws InvalidArgumentException
*/
protected function _whereIn(?string $key = null, $values = null, bool $not = false, string $type = 'AND ', ?bool $escape = null, string $clause = 'QBWhere')
{
if ($key === null || $key === '') {
throw new InvalidArgumentException(sprintf('%s() expects $key to be a non-empty string', debug_backtrace(0, 2)[1]['function']));
}
if ($values === null || (! is_array($values) && ! $this->isSubquery($values))) {
throw new InvalidArgumentException(sprintf('%s() expects $values to be of type array or closure', debug_backtrace(0, 2)[1]['function']));
}
if (! is_bool($escape)) {
$escape = $this->db->protectIdentifiers;
}
$ok = $key;
if ($escape === true) {
$key = $this->db->protectIdentifiers($key);
}
$not = ($not) ? ' NOT' : '';
if ($this->isSubquery($values)) {
$whereIn = $this->buildSubquery($values, true);
$escape = false;
} else {
$whereIn = array_values($values);
}
$ok = $this->setBind($ok, $whereIn, $escape);
$prefix = empty($this->{$clause}) ? $this->groupGetType('') : $this->groupGetType($type);
$whereIn = [
'condition' => "{$prefix}{$key}{$not} IN :{$ok}:",
'escape' => false,
];
$this->{$clause}[] = $whereIn;
return $this;
}
/**
* Generates a %LIKE% portion of the query.
* Separates multiple calls with 'AND'.
*
* @param array|RawSql|string $field
*
* @return $this
*/
public function like($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
{
return $this->_like($field, $match, 'AND ', $side, '', $escape, $insensitiveSearch);
}
/**
* Generates a NOT LIKE portion of the query.
* Separates multiple calls with 'AND'.
*
* @param array|RawSql|string $field
*
* @return $this
*/
public function notLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
{
return $this->_like($field, $match, 'AND ', $side, 'NOT', $escape, $insensitiveSearch);
}
/**
* Generates a %LIKE% portion of the query.
* Separates multiple calls with 'OR'.
*
* @param array|RawSql|string $field
*
* @return $this
*/
public function orLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
{
return $this->_like($field, $match, 'OR ', $side, '', $escape, $insensitiveSearch);
}
/**
* Generates a NOT LIKE portion of the query.
* Separates multiple calls with 'OR'.
*
* @param array|RawSql|string $field
*
* @return $this
*/
public function orNotLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
{
return $this->_like($field, $match, 'OR ', $side, 'NOT', $escape, $insensitiveSearch);
}
/**
* Generates a %LIKE% portion of the query.
* Separates multiple calls with 'AND'.
*
* @param array|RawSql|string $field
*
* @return $this
*/
public function havingLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
{
return $this->_like($field, $match, 'AND ', $side, '', $escape, $insensitiveSearch, 'QBHaving');
}
/**
* Generates a NOT LIKE portion of the query.
* Separates multiple calls with 'AND'.
*
* @param array|RawSql|string $field
*
* @return $this
*/
public function notHavingLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
{
return $this->_like($field, $match, 'AND ', $side, 'NOT', $escape, $insensitiveSearch, 'QBHaving');
}
/**
* Generates a %LIKE% portion of the query.
* Separates multiple calls with 'OR'.
*
* @param array|RawSql|string $field
*
* @return $this
*/
public function orHavingLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
{
return $this->_like($field, $match, 'OR ', $side, '', $escape, $insensitiveSearch, 'QBHaving');
}
/**
* Generates a NOT LIKE portion of the query.
* Separates multiple calls with 'OR'.
*
* @param array|RawSql|string $field
*
* @return $this
*/
public function orNotHavingLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
{
return $this->_like($field, $match, 'OR ', $side, 'NOT', $escape, $insensitiveSearch, 'QBHaving');
}
/**
* @used-by like()
* @used-by orLike()
* @used-by notLike()
* @used-by orNotLike()
* @used-by havingLike()
* @used-by orHavingLike()
* @used-by notHavingLike()
* @used-by orNotHavingLike()
*
* @param array<string, string>|RawSql|string $field
*
* @return $this
*/
protected function _like($field, string $match = '', string $type = 'AND ', string $side = 'both', string $not = '', ?bool $escape = null, bool $insensitiveSearch = false, string $clause = 'QBWhere')
{
$escape = is_bool($escape) ? $escape : $this->db->protectIdentifiers;
$side = strtolower($side);
if ($field instanceof RawSql) {
$k = (string) $field;
$v = $match;
$insensitiveSearch = false;
$prefix = empty($this->{$clause}) ? $this->groupGetType('') : $this->groupGetType($type);
if ($side === 'none') {
$bind = $this->setBind($field->getBindingKey(), $v, $escape);
} elseif ($side === 'before') {
$bind = $this->setBind($field->getBindingKey(), "%{$v}", $escape);
} elseif ($side === 'after') {
$bind = $this->setBind($field->getBindingKey(), "{$v}%", $escape);
} else {
$bind = $this->setBind($field->getBindingKey(), "%{$v}%", $escape);
}
$likeStatement = $this->_like_statement($prefix, $k, $not, $bind, $insensitiveSearch);
// some platforms require an escape sequence definition for LIKE wildcards
if ($escape === true && $this->db->likeEscapeStr !== '') {
$likeStatement .= sprintf($this->db->likeEscapeStr, $this->db->likeEscapeChar);
}
$this->{$clause}[] = [
'condition' => $field->with($likeStatement),
'escape' => $escape,
];
return $this;
}
$keyValue = ! is_array($field) ? [$field => $match] : $field;
foreach ($keyValue as $k => $v) {
if ($insensitiveSearch) {
$v = mb_strtolower($v, 'UTF-8');
}
$prefix = empty($this->{$clause}) ? $this->groupGetType('') : $this->groupGetType($type);
if ($side === 'none') {
$bind = $this->setBind($k, $v, $escape);
} elseif ($side === 'before') {
$bind = $this->setBind($k, "%{$v}", $escape);
} elseif ($side === 'after') {
$bind = $this->setBind($k, "{$v}%", $escape);
} else {
$bind = $this->setBind($k, "%{$v}%", $escape);
}
$likeStatement = $this->_like_statement($prefix, $k, $not, $bind, $insensitiveSearch);
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | true |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/BasePreparedQuery.php | system/Database/BasePreparedQuery.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\Database;
use ArgumentCountError;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\BadMethodCallException;
use ErrorException;
/**
* @template TConnection
* @template TStatement
* @template TResult
*
* @implements PreparedQueryInterface<TConnection, TStatement, TResult>
*/
abstract class BasePreparedQuery implements PreparedQueryInterface
{
/**
* The prepared statement itself.
*
* @var TStatement|null
*/
protected $statement;
/**
* The error code, if any.
*
* @var int
*/
protected $errorCode;
/**
* The error message, if any.
*
* @var string
*/
protected $errorString;
/**
* Holds the prepared query object
* that is cloned during execute.
*
* @var Query
*/
protected $query;
/**
* A reference to the db connection to use.
*
* @var BaseConnection<TConnection, TResult>
*/
protected $db;
public function __construct(BaseConnection $db)
{
$this->db = $db;
}
/**
* Prepares the query against the database, and saves the connection
* info necessary to execute the query later.
*
* NOTE: This version is based on SQL code. Child classes should
* override this method.
*
* @return $this
*/
public function prepare(string $sql, array $options = [], string $queryClass = Query::class)
{
// We only supports positional placeholders (?)
// in order to work with the execute method below, so we
// need to replace our named placeholders (:name)
$sql = preg_replace('/:[^\s,)]+/', '?', $sql);
/** @var Query $query */
$query = new $queryClass($this->db);
$query->setQuery($sql);
if (! empty($this->db->swapPre) && ! empty($this->db->DBPrefix)) {
$query->swapPrefix($this->db->DBPrefix, $this->db->swapPre);
}
$this->query = $query;
return $this->_prepare($query->getOriginalQuery(), $options);
}
/**
* The database-dependent portion of the prepare statement.
*
* @return $this
*/
abstract public function _prepare(string $sql, array $options = []);
/**
* Takes a new set of data and runs it against the currently
* prepared query. Upon success, will return a Results object.
*
* @return bool|ResultInterface<TConnection, TResult>
*
* @throws DatabaseException
*/
public function execute(...$data)
{
// Execute the Query.
$startTime = microtime(true);
try {
$exception = null;
$result = $this->_execute($data);
} catch (ArgumentCountError|ErrorException $exception) {
$result = false;
}
// Update our query object
$query = clone $this->query;
$query->setBinds($data);
if ($result === false) {
$query->setDuration($startTime, $startTime);
// This will trigger a rollback if transactions are being used
$this->db->handleTransStatus();
if ($this->db->DBDebug) {
// We call this function in order to roll-back queries
// if transactions are enabled. If we don't call this here
// the error message will trigger an exit, causing the
// transactions to remain in limbo.
while ($this->db->transDepth !== 0) {
$transDepth = $this->db->transDepth;
$this->db->transComplete();
if ($transDepth === $this->db->transDepth) {
log_message('error', 'Database: Failure during an automated transaction commit/rollback!');
break;
}
}
// Let others do something with this query.
Events::trigger('DBQuery', $query);
if ($exception !== null) {
throw new DatabaseException($exception->getMessage(), $exception->getCode(), $exception);
}
return false;
}
// Let others do something with this query.
Events::trigger('DBQuery', $query);
return false;
}
$query->setDuration($startTime);
// Let others do something with this query
Events::trigger('DBQuery', $query);
if ($this->db->isWriteType((string) $query)) {
return true;
}
// Return a result object
$resultClass = str_replace('PreparedQuery', 'Result', static::class);
$resultID = $this->_getResult();
return new $resultClass($this->db->connID, $resultID);
}
/**
* The database dependant version of the execute method.
*/
abstract public function _execute(array $data): bool;
/**
* Returns the result object for the prepared query.
*
* @return object|resource|null
*/
abstract public function _getResult();
/**
* Explicitly closes the prepared statement.
*
* @throws BadMethodCallException
*/
public function close(): bool
{
if (! isset($this->statement)) {
throw new BadMethodCallException('Cannot call close on a non-existing prepared statement.');
}
try {
return $this->_close();
} finally {
$this->statement = null;
}
}
/**
* The database-dependent version of the close method.
*/
abstract protected function _close(): bool;
/**
* Returns the SQL that has been prepared.
*/
public function getQueryString(): string
{
if (! $this->query instanceof QueryInterface) {
throw new BadMethodCallException('Cannot call getQueryString on a prepared query until after the query has been prepared.');
}
return $this->query->getQuery();
}
/**
* A helper to determine if any error exists.
*/
public function hasError(): bool
{
return ! empty($this->errorString);
}
/**
* Returns the error code created while executing this statement.
*/
public function getErrorCode(): int
{
return $this->errorCode;
}
/**
* Returns the error message created while executing this statement.
*/
public function getErrorMessage(): string
{
return $this->errorString;
}
/**
* Whether the input contain binary data.
*/
protected function isBinary(string $input): bool
{
return mb_detect_encoding($input, 'UTF-8', true) === false;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/QueryInterface.php | system/Database/QueryInterface.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\Database;
/**
* Interface QueryInterface
*
* Represents a single statement that can be executed against the database.
* Statements are platform-specific and can handle binding of binds.
*/
interface QueryInterface
{
/**
* Sets the raw query string to use for this statement.
*
* @param mixed $binds
*
* @return $this
*/
public function setQuery(string $sql, $binds = null, bool $setEscape = true);
/**
* Returns the final, processed query string after binding, etal
* has been performed.
*
* @return string
*/
public function getQuery();
/**
* Records the execution time of the statement using microtime(true)
* for it's start and end values. If no end value is present, will
* use the current time to determine total duration.
*
* @return $this
*/
public function setDuration(float $start, ?float $end = null);
/**
* Returns the duration of this query during execution, or null if
* the query has not been executed yet.
*
* @param int $decimals The accuracy of the returned time.
*/
public function getDuration(int $decimals = 6): string;
/**
* Stores the error description that happened for this query.
*
* @return $this
*/
public function setError(int $code, string $error);
/**
* Reports whether this statement created an error not.
*/
public function hasError(): bool;
/**
* Returns the error code created while executing this statement.
*/
public function getErrorCode(): int;
/**
* Returns the error message created while executing this statement.
*/
public function getErrorMessage(): string;
/**
* Determines if the statement is a write-type query or not.
*/
public function isWriteType(): bool;
/**
* Swaps out one table prefix for a new one.
*
* @return $this
*/
public function swapPrefix(string $orig, string $swap);
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/BaseUtils.php | system/Database/BaseUtils.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\Database;
use CodeIgniter\Database\Exceptions\DatabaseException;
/**
* Class BaseUtils
*/
abstract class BaseUtils
{
/**
* Database object
*
* @var object
*/
protected $db;
/**
* List databases statement
*
* @var bool|string
*/
protected $listDatabases = false;
/**
* OPTIMIZE TABLE statement
*
* @var bool|string
*/
protected $optimizeTable = false;
/**
* REPAIR TABLE statement
*
* @var bool|string
*/
protected $repairTable = false;
/**
* Class constructor
*/
public function __construct(ConnectionInterface $db)
{
$this->db = $db;
}
/**
* List databases
*
* @return array|bool
*
* @throws DatabaseException
*/
public function listDatabases()
{
// Is there a cached result?
if (isset($this->db->dataCache['db_names'])) {
return $this->db->dataCache['db_names'];
}
if ($this->listDatabases === false) {
if ($this->db->DBDebug) {
throw new DatabaseException('Unsupported feature of the database platform you are using.');
}
return false;
}
$this->db->dataCache['db_names'] = [];
$query = $this->db->query($this->listDatabases);
if ($query === false) {
return $this->db->dataCache['db_names'];
}
for ($i = 0, $query = $query->getResultArray(), $c = count($query); $i < $c; $i++) {
$this->db->dataCache['db_names'][] = current($query[$i]);
}
return $this->db->dataCache['db_names'];
}
/**
* Determine if a particular database exists
*/
public function databaseExists(string $databaseName): bool
{
return in_array($databaseName, $this->listDatabases(), true);
}
/**
* Optimize Table
*
* @return bool
*
* @throws DatabaseException
*/
public function optimizeTable(string $tableName)
{
if ($this->optimizeTable === false) {
if ($this->db->DBDebug) {
throw new DatabaseException('Unsupported feature of the database platform you are using.');
}
return false;
}
$query = $this->db->query(sprintf($this->optimizeTable, $this->db->escapeIdentifiers($tableName)));
return $query !== false;
}
/**
* Optimize Database
*
* @return mixed
*
* @throws DatabaseException
*/
public function optimizeDatabase()
{
if ($this->optimizeTable === false) {
if ($this->db->DBDebug) {
throw new DatabaseException('Unsupported feature of the database platform you are using.');
}
return false;
}
$result = [];
foreach ($this->db->listTables() as $tableName) {
$res = $this->db->query(sprintf($this->optimizeTable, $this->db->escapeIdentifiers($tableName)));
if (is_bool($res)) {
return $res;
}
// Build the result array...
$res = $res->getResultArray();
// Postgre & SQLite3 returns empty array
if (empty($res)) {
$key = $tableName;
} else {
$res = current($res);
$key = str_replace($this->db->database . '.', '', current($res));
$keys = array_keys($res);
unset($res[$keys[0]]);
}
$result[$key] = $res;
}
return $result;
}
/**
* Repair Table
*
* @return mixed
*
* @throws DatabaseException
*/
public function repairTable(string $tableName)
{
if ($this->repairTable === false) {
if ($this->db->DBDebug) {
throw new DatabaseException('Unsupported feature of the database platform you are using.');
}
return false;
}
$query = $this->db->query(sprintf($this->repairTable, $this->db->escapeIdentifiers($tableName)));
if (is_bool($query)) {
return $query;
}
$query = $query->getResultArray();
return current($query);
}
/**
* Generate CSV from a query result object
*
* @return string
*/
public function getCSVFromResult(ResultInterface $query, string $delim = ',', string $newline = "\n", string $enclosure = '"')
{
$out = '';
foreach ($query->getFieldNames() as $name) {
$out .= $enclosure . str_replace($enclosure, $enclosure . $enclosure, $name) . $enclosure . $delim;
}
$out = substr($out, 0, -strlen($delim)) . $newline;
// Next blast through the result array and build out the rows
while ($row = $query->getUnbufferedRow('array')) {
$line = [];
foreach ($row as $item) {
$line[] = $enclosure . str_replace(
$enclosure,
$enclosure . $enclosure,
(string) $item,
) . $enclosure;
}
$out .= implode($delim, $line) . $newline;
}
return $out;
}
/**
* Generate XML data from a query result object
*/
public function getXMLFromResult(ResultInterface $query, array $params = []): string
{
foreach (['root' => 'root', 'element' => 'element', 'newline' => "\n", 'tab' => "\t"] as $key => $val) {
if (! isset($params[$key])) {
$params[$key] = $val;
}
}
$root = $params['root'];
$newline = $params['newline'];
$tab = $params['tab'];
$element = $params['element'];
helper('xml');
$xml = '<' . $root . '>' . $newline;
while ($row = $query->getUnbufferedRow()) {
$xml .= $tab . '<' . $element . '>' . $newline;
foreach ($row as $key => $val) {
$val = (! empty($val)) ? xml_convert((string) $val) : '';
$xml .= $tab . $tab . '<' . $key . '>' . $val . '</' . $key . '>' . $newline;
}
$xml .= $tab . '</' . $element . '>' . $newline;
}
return $xml . '</' . $root . '>' . $newline;
}
/**
* Database Backup
*
* @param array|string $params
*
* @return false|never|string
*
* @throws DatabaseException
*/
public function backup($params = [])
{
if (is_string($params)) {
$params = ['tables' => $params];
}
$prefs = [
'tables' => [],
'ignore' => [],
'filename' => '',
'format' => 'gzip', // gzip, txt
'add_drop' => true,
'add_insert' => true,
'newline' => "\n",
'foreign_key_checks' => true,
];
if (! empty($params)) {
foreach (array_keys($prefs) as $key) {
if (isset($params[$key])) {
$prefs[$key] = $params[$key];
}
}
}
if (empty($prefs['tables'])) {
$prefs['tables'] = $this->db->listTables();
}
if (! in_array($prefs['format'], ['gzip', 'txt'], true)) {
$prefs['format'] = 'txt';
}
if ($prefs['format'] === 'gzip' && ! function_exists('gzencode')) {
if ($this->db->DBDebug) {
throw new DatabaseException('The file compression format you chose is not supported by your server.');
}
$prefs['format'] = 'txt';
}
if ($prefs['format'] === 'txt') {
return $this->_backup($prefs);
}
// @TODO gzencode() requires `ext-zlib`, but _backup() is not implemented in all databases.
return gzencode($this->_backup($prefs));
}
/**
* Platform dependent version of the backup function.
*
* @return false|never|string
*/
abstract public function _backup(?array $prefs = null);
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/Forge.php | system/Database/Forge.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\Database;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Exceptions\RuntimeException;
use Throwable;
/**
* The Forge class transforms migrations to executable
* SQL statements.
*/
class Forge
{
/**
* The active database connection.
*
* @var BaseConnection
*/
protected $db;
/**
* List of fields in the form `[name => attributes]`
*
* @var array<string, array<string, bool|string>|string>
*/
protected $fields = [];
/**
* List of keys.
*
* @var list<array{fields?: list<string>, keyName?: string}>
*/
protected $keys = [];
/**
* List of unique keys.
*
* @var array
*/
protected $uniqueKeys = [];
/**
* Primary keys.
*
* @var array{fields?: list<string>, keyName?: string}
*/
protected $primaryKeys = [];
/**
* List of foreign keys.
*
* @var array
*/
protected $foreignKeys = [];
/**
* Character set used.
*
* @var string
*/
protected $charset = '';
/**
* CREATE DATABASE statement
*
* @var false|string
*/
protected $createDatabaseStr = 'CREATE DATABASE %s';
/**
* CREATE DATABASE IF statement
*
* @var string
*/
protected $createDatabaseIfStr;
/**
* CHECK DATABASE EXIST statement
*
* @var string
*/
protected $checkDatabaseExistStr;
/**
* DROP DATABASE statement
*
* @var false|string
*/
protected $dropDatabaseStr = 'DROP DATABASE %s';
/**
* CREATE TABLE statement
*
* @var string
*/
protected $createTableStr = "%s %s (%s\n)";
/**
* CREATE TABLE IF statement
*
* @var bool|string
*
* @deprecated This is no longer used.
*/
protected $createTableIfStr = 'CREATE TABLE IF NOT EXISTS';
/**
* CREATE TABLE keys flag
*
* Whether table keys are created from within the
* CREATE TABLE statement.
*
* @var bool
*/
protected $createTableKeys = false;
/**
* DROP TABLE IF EXISTS statement
*
* @var bool|string
*/
protected $dropTableIfStr = 'DROP TABLE IF EXISTS';
/**
* RENAME TABLE statement
*
* @var false|string
*/
protected $renameTableStr = 'ALTER TABLE %s RENAME TO %s';
/**
* UNSIGNED support
*
* @var array|bool
*/
protected $unsigned = true;
/**
* NULL value representation in CREATE/ALTER TABLE statements
*
* @var string
*
* @internal Used for marking nullable fields. Not covered by BC promise.
*/
protected $null = 'NULL';
/**
* DEFAULT value representation in CREATE/ALTER TABLE statements
*
* @var false|string
*/
protected $default = ' DEFAULT ';
/**
* DROP CONSTRAINT statement
*
* @var string
*/
protected $dropConstraintStr;
/**
* DROP INDEX statement
*
* @var string
*/
protected $dropIndexStr = 'DROP INDEX %s ON %s';
/**
* Foreign Key Allowed Actions
*
* @var array
*/
protected $fkAllowActions = ['CASCADE', 'SET NULL', 'NO ACTION', 'RESTRICT', 'SET DEFAULT'];
/**
* Constructor.
*/
public function __construct(BaseConnection $db)
{
$this->db = $db;
}
/**
* Provides access to the forge's current database connection.
*
* @return ConnectionInterface
*/
public function getConnection()
{
return $this->db;
}
/**
* Create database
*
* @param bool $ifNotExists Whether to add IF NOT EXISTS condition
*
* @throws DatabaseException
*/
public function createDatabase(string $dbName, bool $ifNotExists = false): bool
{
if ($ifNotExists && $this->createDatabaseIfStr === null) {
if ($this->databaseExists($dbName)) {
return true;
}
$ifNotExists = false;
}
if ($this->createDatabaseStr === false) {
if ($this->db->DBDebug) {
throw new DatabaseException('This feature is not available for the database you are using.');
}
return false; // @codeCoverageIgnore
}
try {
if (! $this->db->query(
sprintf(
$ifNotExists ? $this->createDatabaseIfStr : $this->createDatabaseStr,
$this->db->escapeIdentifier($dbName),
$this->db->charset,
$this->db->DBCollat,
),
)) {
// @codeCoverageIgnoreStart
if ($this->db->DBDebug) {
throw new DatabaseException('Unable to create the specified database.');
}
return false;
// @codeCoverageIgnoreEnd
}
if (! empty($this->db->dataCache['db_names'])) {
$this->db->dataCache['db_names'][] = $dbName;
}
return true;
} catch (Throwable $e) {
if ($this->db->DBDebug) {
throw new DatabaseException('Unable to create the specified database.', 0, $e);
}
return false; // @codeCoverageIgnore
}
}
/**
* Determine if a database exists
*
* @throws DatabaseException
*/
private function databaseExists(string $dbName): bool
{
if ($this->checkDatabaseExistStr === null) {
if ($this->db->DBDebug) {
throw new DatabaseException('This feature is not available for the database you are using.');
}
return false;
}
return $this->db->query($this->checkDatabaseExistStr, $dbName)->getRow() !== null;
}
/**
* Drop database
*
* @throws DatabaseException
*/
public function dropDatabase(string $dbName): bool
{
if ($this->dropDatabaseStr === false) {
if ($this->db->DBDebug) {
throw new DatabaseException('This feature is not available for the database you are using.');
}
return false;
}
if (! $this->db->query(
sprintf($this->dropDatabaseStr, $this->db->escapeIdentifier($dbName)),
)) {
if ($this->db->DBDebug) {
throw new DatabaseException('Unable to drop the specified database.');
}
return false;
}
if (! empty($this->db->dataCache['db_names'])) {
$key = array_search(
strtolower($dbName),
array_map(strtolower(...), $this->db->dataCache['db_names']),
true,
);
if ($key !== false) {
unset($this->db->dataCache['db_names'][$key]);
}
}
return true;
}
/**
* Add Key
*
* @param array|string $key
*
* @return Forge
*/
public function addKey($key, bool $primary = false, bool $unique = false, string $keyName = '')
{
if ($primary) {
$this->primaryKeys = ['fields' => (array) $key, 'keyName' => $keyName];
} else {
$this->keys[] = ['fields' => (array) $key, 'keyName' => $keyName];
if ($unique) {
$this->uniqueKeys[] = count($this->keys) - 1;
}
}
return $this;
}
/**
* Add Primary Key
*
* @param array|string $key
*
* @return Forge
*/
public function addPrimaryKey($key, string $keyName = '')
{
return $this->addKey($key, true, false, $keyName);
}
/**
* Add Unique Key
*
* @param array|string $key
*
* @return Forge
*/
public function addUniqueKey($key, string $keyName = '')
{
return $this->addKey($key, false, true, $keyName);
}
/**
* Add Field
*
* @param array<string, array|string>|string $fields Field array or Field string
*
* @return Forge
*/
public function addField($fields)
{
if (is_string($fields)) {
if ($fields === 'id') {
$this->addField([
'id' => [
'type' => 'INT',
'constraint' => 9,
'auto_increment' => true,
],
]);
$this->addKey('id', true);
} else {
if (! str_contains($fields, ' ')) {
throw new InvalidArgumentException('Field information is required for that operation.');
}
$fieldName = explode(' ', $fields, 2)[0];
$fieldName = trim($fieldName, '`\'"');
$this->fields[$fieldName] = $fields;
}
}
if (is_array($fields)) {
foreach ($fields as $name => $attributes) {
if (is_string($attributes)) {
$this->addField($attributes);
continue;
}
if (is_array($attributes)) {
$this->fields = array_merge($this->fields, [$name => $attributes]);
}
}
}
return $this;
}
/**
* Add Foreign Key
*
* @param list<string>|string $fieldName
* @param list<string>|string $tableField
*
* @throws DatabaseException
*/
public function addForeignKey(
$fieldName = '',
string $tableName = '',
$tableField = '',
string $onUpdate = '',
string $onDelete = '',
string $fkName = '',
): Forge {
$fieldName = (array) $fieldName;
$tableField = (array) $tableField;
$this->foreignKeys[] = [
'field' => $fieldName,
'referenceTable' => $tableName,
'referenceField' => $tableField,
'onDelete' => strtoupper($onDelete),
'onUpdate' => strtoupper($onUpdate),
'fkName' => $fkName,
];
return $this;
}
/**
* Drop Key
*
* @throws DatabaseException
*/
public function dropKey(string $table, string $keyName, bool $prefixKeyName = true): bool
{
$keyName = $this->db->escapeIdentifiers(($prefixKeyName ? $this->db->DBPrefix : '') . $keyName);
$table = $this->db->escapeIdentifiers($this->db->DBPrefix . $table);
$dropKeyAsConstraint = $this->dropKeyAsConstraint($table, $keyName);
if ($dropKeyAsConstraint) {
$sql = sprintf(
$this->dropConstraintStr,
$table,
$keyName,
);
} else {
$sql = sprintf(
$this->dropIndexStr,
$keyName,
$table,
);
}
if ($sql === '') {
if ($this->db->DBDebug) {
throw new DatabaseException('This feature is not available for the database you are using.');
}
return false;
}
return $this->db->query($sql);
}
/**
* Checks if key needs to be dropped as a constraint.
*/
protected function dropKeyAsConstraint(string $table, string $constraintName): bool
{
$sql = $this->_dropKeyAsConstraint($table, $constraintName);
if ($sql === '') {
return false;
}
return $this->db->query($sql)->getResultArray() !== [];
}
/**
* Constructs sql to check if key is a constraint.
*/
protected function _dropKeyAsConstraint(string $table, string $constraintName): string
{
return '';
}
/**
* Drop Primary Key
*/
public function dropPrimaryKey(string $table, string $keyName = ''): bool
{
$sql = sprintf(
'ALTER TABLE %s DROP CONSTRAINT %s',
$this->db->escapeIdentifiers($this->db->DBPrefix . $table),
($keyName === '') ? $this->db->escapeIdentifiers('pk_' . $this->db->DBPrefix . $table) : $this->db->escapeIdentifiers($keyName),
);
return $this->db->query($sql);
}
/**
* @return bool
*
* @throws DatabaseException
*/
public function dropForeignKey(string $table, string $foreignName)
{
$sql = sprintf(
(string) $this->dropConstraintStr,
$this->db->escapeIdentifiers($this->db->DBPrefix . $table),
$this->db->escapeIdentifiers($foreignName),
);
if ($sql === '') {
if ($this->db->DBDebug) {
throw new DatabaseException('This feature is not available for the database you are using.');
}
return false;
}
return $this->db->query($sql);
}
/**
* @param array $attributes Table attributes
*
* @return bool
*
* @throws DatabaseException
*/
public function createTable(string $table, bool $ifNotExists = false, array $attributes = [])
{
if ($table === '') {
throw new InvalidArgumentException('A table name is required for that operation.');
}
$table = $this->db->DBPrefix . $table;
if ($this->fields === []) {
throw new RuntimeException('Field information is required.');
}
// If table exists lets stop here
if ($ifNotExists && $this->db->tableExists($table, false)) {
$this->reset();
return true;
}
$sql = $this->_createTable($table, false, $attributes);
if (($result = $this->db->query($sql)) !== false) {
if (isset($this->db->dataCache['table_names']) && ! in_array($table, $this->db->dataCache['table_names'], true)) {
$this->db->dataCache['table_names'][] = $table;
}
// Most databases don't support creating indexes from within the CREATE TABLE statement
if ($this->keys !== []) {
for ($i = 0, $sqls = $this->_processIndexes($table), $c = count($sqls); $i < $c; $i++) {
$this->db->query($sqls[$i]);
}
}
}
$this->reset();
return $result;
}
/**
* @param array $attributes Table attributes
*
* @return string SQL string
*
* @deprecated $ifNotExists is no longer used, and will be removed.
*/
protected function _createTable(string $table, bool $ifNotExists, array $attributes)
{
$processedFields = $this->_processFields(true);
for ($i = 0, $c = count($processedFields); $i < $c; $i++) {
$processedFields[$i] = ($processedFields[$i]['_literal'] !== false) ? "\n\t" . $processedFields[$i]['_literal']
: "\n\t" . $this->_processColumn($processedFields[$i]);
}
$processedFields = implode(',', $processedFields);
$processedFields .= $this->_processPrimaryKeys($table);
$processedFields .= current($this->_processForeignKeys($table));
if ($this->createTableKeys === true) {
$indexes = current($this->_processIndexes($table));
if (is_string($indexes)) {
$processedFields .= $indexes;
}
}
return sprintf(
$this->createTableStr . '%s',
'CREATE TABLE',
$this->db->escapeIdentifiers($table),
$processedFields,
$this->_createTableAttributes($attributes),
);
}
protected function _createTableAttributes(array $attributes): string
{
$sql = '';
foreach (array_keys($attributes) as $key) {
if (is_string($key)) {
$sql .= ' ' . strtoupper($key) . ' ' . $this->db->escape($attributes[$key]);
}
}
return $sql;
}
/**
* @return bool
*
* @throws DatabaseException
*/
public function dropTable(string $tableName, bool $ifExists = false, bool $cascade = false)
{
if ($tableName === '') {
if ($this->db->DBDebug) {
throw new DatabaseException('A table name is required for that operation.');
}
return false;
}
if ($this->db->DBPrefix !== '' && str_starts_with($tableName, $this->db->DBPrefix)) {
$tableName = substr($tableName, strlen($this->db->DBPrefix));
}
if (($query = $this->_dropTable($this->db->DBPrefix . $tableName, $ifExists, $cascade)) === true) {
return true;
}
$this->db->disableForeignKeyChecks();
$query = $this->db->query($query);
$this->db->enableForeignKeyChecks();
if ($query && ! empty($this->db->dataCache['table_names'])) {
$key = array_search(
strtolower($this->db->DBPrefix . $tableName),
array_map(strtolower(...), $this->db->dataCache['table_names']),
true,
);
if ($key !== false) {
unset($this->db->dataCache['table_names'][$key]);
}
}
return $query;
}
/**
* Generates a platform-specific DROP TABLE string
*
* @return bool|string
*/
protected function _dropTable(string $table, bool $ifExists, bool $cascade)
{
$sql = 'DROP TABLE';
if ($ifExists) {
if ($this->dropTableIfStr === false) {
if (! $this->db->tableExists($table)) {
return true;
}
} else {
$sql = sprintf($this->dropTableIfStr, $this->db->escapeIdentifiers($table));
}
}
return $sql . ' ' . $this->db->escapeIdentifiers($table);
}
/**
* @return bool
*
* @throws DatabaseException
*/
public function renameTable(string $tableName, string $newTableName)
{
if ($tableName === '' || $newTableName === '') {
throw new InvalidArgumentException('A table name is required for that operation.');
}
if ($this->renameTableStr === false) {
if ($this->db->DBDebug) {
throw new DatabaseException('This feature is not available for the database you are using.');
}
return false;
}
$result = $this->db->query(sprintf(
$this->renameTableStr,
$this->db->escapeIdentifiers($this->db->DBPrefix . $tableName),
$this->db->escapeIdentifiers($this->db->DBPrefix . $newTableName),
));
if ($result && ! empty($this->db->dataCache['table_names'])) {
$key = array_search(
strtolower($this->db->DBPrefix . $tableName),
array_map(strtolower(...), $this->db->dataCache['table_names']),
true,
);
if ($key !== false) {
$this->db->dataCache['table_names'][$key] = $this->db->DBPrefix . $newTableName;
}
}
return $result;
}
/**
* @param array<string, array|string>|string $fields Field array or Field string
*
* @throws DatabaseException
*/
public function addColumn(string $table, $fields): bool
{
// Work-around for literal column definitions
if (is_string($fields)) {
$fields = [$fields];
}
foreach (array_keys($fields) as $name) {
$this->addField([$name => $fields[$name]]);
}
$sqls = $this->_alterTable('ADD', $this->db->DBPrefix . $table, $this->_processFields());
$this->reset();
if ($sqls === false) {
if ($this->db->DBDebug) {
throw new DatabaseException('This feature is not available for the database you are using.');
}
return false;
}
foreach ($sqls as $sql) {
if ($this->db->query($sql) === false) {
return false;
}
}
return true;
}
/**
* @param list<string>|string $columnNames column names to DROP
*
* @return bool
*
* @throws DatabaseException
*/
public function dropColumn(string $table, $columnNames)
{
$sql = $this->_alterTable('DROP', $this->db->DBPrefix . $table, $columnNames);
if ($sql === false) {
if ($this->db->DBDebug) {
throw new DatabaseException('This feature is not available for the database you are using.');
}
return false;
}
return $this->db->query($sql);
}
/**
* @param array<string, array|string>|string $fields Field array or Field string
*
* @throws DatabaseException
*/
public function modifyColumn(string $table, $fields): bool
{
// Work-around for literal column definitions
if (is_string($fields)) {
$fields = [$fields];
}
foreach (array_keys($fields) as $name) {
$this->addField([$name => $fields[$name]]);
}
if ($this->fields === []) {
throw new RuntimeException('Field information is required');
}
$sqls = $this->_alterTable('CHANGE', $this->db->DBPrefix . $table, $this->_processFields());
$this->reset();
if ($sqls === false) {
if ($this->db->DBDebug) {
throw new DatabaseException('This feature is not available for the database you are using.');
}
return false;
}
if (is_array($sqls)) {
foreach ($sqls as $sql) {
if ($this->db->query($sql) === false) {
return false;
}
}
}
return true;
}
/**
* @param 'ADD'|'CHANGE'|'DROP' $alterType
* @param array|string $processedFields Processed column definitions
* or column names to DROP
*
* @return ($alterType is 'DROP' ? string : false|list<string>|null)
*/
protected function _alterTable(string $alterType, string $table, $processedFields)
{
$sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table) . ' ';
// DROP has everything it needs now.
if ($alterType === 'DROP') {
$columnNamesToDrop = $processedFields;
if (is_string($columnNamesToDrop)) {
$columnNamesToDrop = explode(',', $columnNamesToDrop);
}
$columnNamesToDrop = array_map(fn ($field): string => 'DROP COLUMN ' . $this->db->escapeIdentifiers(trim($field)), $columnNamesToDrop);
return $sql . implode(', ', $columnNamesToDrop);
}
$sql .= ($alterType === 'ADD') ? 'ADD ' : $alterType . ' COLUMN ';
$sqls = [];
foreach ($processedFields as $field) {
$sqls[] = $sql . ($field['_literal'] !== false
? $field['_literal']
: $this->_processColumn($field));
}
return $sqls;
}
/**
* Returns $processedFields array from $this->fields data.
*/
protected function _processFields(bool $createTable = false): array
{
$processedFields = [];
foreach ($this->fields as $name => $attributes) {
if (! is_array($attributes)) {
$processedFields[] = ['_literal' => $attributes];
continue;
}
$attributes = array_change_key_case($attributes, CASE_UPPER);
if ($createTable && empty($attributes['TYPE'])) {
continue;
}
if (isset($attributes['TYPE'])) {
$this->_attributeType($attributes);
}
$field = [
'name' => $name,
'new_name' => $attributes['NAME'] ?? null,
'type' => $attributes['TYPE'] ?? null,
'length' => '',
'unsigned' => '',
'null' => '',
'unique' => '',
'default' => '',
'auto_increment' => '',
'_literal' => false,
];
if (isset($attributes['TYPE'])) {
$this->_attributeUnsigned($attributes, $field);
}
if ($createTable === false) {
if (isset($attributes['AFTER'])) {
$field['after'] = $attributes['AFTER'];
} elseif (isset($attributes['FIRST'])) {
$field['first'] = (bool) $attributes['FIRST'];
}
}
$this->_attributeDefault($attributes, $field);
if (isset($attributes['NULL'])) {
$nullString = ' ' . $this->null;
if ($attributes['NULL'] === true) {
$field['null'] = empty($this->null) ? '' : $nullString;
} elseif ($attributes['NULL'] === $nullString) {
$field['null'] = $nullString;
} elseif ($attributes['NULL'] === '') {
$field['null'] = '';
} else {
$field['null'] = ' NOT ' . $this->null;
}
} elseif ($createTable) {
$field['null'] = ' NOT ' . $this->null;
}
$this->_attributeAutoIncrement($attributes, $field);
$this->_attributeUnique($attributes, $field);
if (isset($attributes['COMMENT'])) {
$field['comment'] = $this->db->escape($attributes['COMMENT']);
}
if (isset($attributes['TYPE']) && ! empty($attributes['CONSTRAINT'])) {
if (is_array($attributes['CONSTRAINT'])) {
$attributes['CONSTRAINT'] = $this->db->escape($attributes['CONSTRAINT']);
$attributes['CONSTRAINT'] = implode(',', $attributes['CONSTRAINT']);
}
$field['length'] = '(' . $attributes['CONSTRAINT'] . ')';
}
$processedFields[] = $field;
}
return $processedFields;
}
/**
* Converts $processedField array to field definition string.
*/
protected function _processColumn(array $processedField): string
{
return $this->db->escapeIdentifiers($processedField['name'])
. ' ' . $processedField['type'] . $processedField['length']
. $processedField['unsigned']
. $processedField['default']
. $processedField['null']
. $processedField['auto_increment']
. $processedField['unique'];
}
/**
* Performs a data type mapping between different databases.
*
* @return void
*/
protected function _attributeType(array &$attributes)
{
// Usually overridden by drivers
}
/**
* Depending on the unsigned property value:
*
* - TRUE will always set $field['unsigned'] to 'UNSIGNED'
* - FALSE will always set $field['unsigned'] to ''
* - array(TYPE) will set $field['unsigned'] to 'UNSIGNED',
* if $attributes['TYPE'] is found in the array
* - array(TYPE => UTYPE) will change $field['type'],
* from TYPE to UTYPE in case of a match
*
* @return void
*/
protected function _attributeUnsigned(array &$attributes, array &$field)
{
if (empty($attributes['UNSIGNED']) || $attributes['UNSIGNED'] !== true) {
return;
}
// Reset the attribute in order to avoid issues if we do type conversion
$attributes['UNSIGNED'] = false;
if (is_array($this->unsigned)) {
foreach (array_keys($this->unsigned) as $key) {
if (is_int($key) && strcasecmp($attributes['TYPE'], $this->unsigned[$key]) === 0) {
$field['unsigned'] = ' UNSIGNED';
return;
}
if (is_string($key) && strcasecmp($attributes['TYPE'], $key) === 0) {
$field['type'] = $key;
return;
}
}
return;
}
$field['unsigned'] = ($this->unsigned === true) ? ' UNSIGNED' : '';
}
/**
* @return void
*/
protected function _attributeDefault(array &$attributes, array &$field)
{
if ($this->default === false) {
return;
}
if (array_key_exists('DEFAULT', $attributes)) {
if ($attributes['DEFAULT'] === null) {
$field['default'] = empty($this->null) ? '' : $this->default . $this->null;
// Override the NULL attribute if that's our default
$attributes['NULL'] = true;
$field['null'] = empty($this->null) ? '' : ' ' . $this->null;
} elseif ($attributes['DEFAULT'] instanceof RawSql) {
$field['default'] = $this->default . $attributes['DEFAULT'];
} else {
$field['default'] = $this->default . $this->db->escape($attributes['DEFAULT']);
}
}
}
/**
* @return void
*/
protected function _attributeUnique(array &$attributes, array &$field)
{
if (! empty($attributes['UNIQUE']) && $attributes['UNIQUE'] === true) {
$field['unique'] = ' UNIQUE';
}
}
/**
* @return void
*/
protected function _attributeAutoIncrement(array &$attributes, array &$field)
{
if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true
&& str_contains(strtolower($field['type']), 'int')
) {
$field['auto_increment'] = ' AUTO_INCREMENT';
}
}
/**
* Generates SQL to add primary key
*
* @param bool $asQuery When true returns stand alone SQL, else partial SQL used with CREATE TABLE
*/
protected function _processPrimaryKeys(string $table, bool $asQuery = false): string
{
$sql = '';
if (isset($this->primaryKeys['fields'])) {
for ($i = 0, $c = count($this->primaryKeys['fields']); $i < $c; $i++) {
if (! isset($this->fields[$this->primaryKeys['fields'][$i]])) {
unset($this->primaryKeys['fields'][$i]);
}
}
}
if (isset($this->primaryKeys['fields']) && $this->primaryKeys['fields'] !== []) {
if ($asQuery) {
$sql .= 'ALTER TABLE ' . $this->db->escapeIdentifiers($this->db->DBPrefix . $table) . ' ADD ';
} else {
$sql .= ",\n\t";
}
$sql .= 'CONSTRAINT ' . $this->db->escapeIdentifiers(($this->primaryKeys['keyName'] === '' ?
'pk_' . $table :
$this->primaryKeys['keyName']))
. ' PRIMARY KEY(' . implode(', ', $this->db->escapeIdentifiers($this->primaryKeys['fields'])) . ')';
}
return $sql;
}
/**
* Executes Sql to add indexes without createTable
*/
public function processIndexes(string $table): bool
{
$sqls = [];
$fk = $this->foreignKeys;
if ($this->fields === []) {
$fieldData = $this->db->getFieldData($this->db->DBPrefix . $table);
$this->fields = array_combine(
array_map(static fn ($columnName) => $columnName->name, $fieldData),
array_fill(0, count($fieldData), []),
);
}
$fields = $this->fields;
if ($this->keys !== []) {
$sqls = $this->_processIndexes($this->db->DBPrefix . $table, true);
}
if ($this->primaryKeys !== []) {
$sqls[] = $this->_processPrimaryKeys($table, true);
}
$this->foreignKeys = $fk;
$this->fields = $fields;
if ($this->foreignKeys !== []) {
$sqls = array_merge($sqls, $this->_processForeignKeys($table, true));
}
foreach ($sqls as $sql) {
if ($this->db->query($sql) === false) {
return false;
}
}
$this->reset();
return true;
}
/**
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | true |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/Exceptions/DataException.php | system/Database/Exceptions/DataException.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\Database\Exceptions;
use CodeIgniter\Exceptions\DebugTraceableTrait;
use CodeIgniter\Exceptions\RuntimeException;
class DataException extends RuntimeException implements ExceptionInterface
{
use DebugTraceableTrait;
/**
* Used by the Model's trigger() method when the callback cannot be found.
*
* @return DataException
*/
public static function forInvalidMethodTriggered(string $method)
{
return new static(lang('Database.invalidEvent', [$method]));
}
/**
* Used by Model's insert/update methods when there isn't
* any data to actually work with.
*
* @return DataException
*/
public static function forEmptyDataset(string $mode)
{
return new static(lang('Database.emptyDataset', [$mode]));
}
/**
* Used by Model's insert/update methods when there is no
* primary key defined and Model has option `useAutoIncrement`
* set to false.
*
* @return DataException
*/
public static function forEmptyPrimaryKey(string $mode)
{
return new static(lang('Database.emptyPrimaryKey', [$mode]));
}
/**
* Thrown when an argument for one of the Model's methods
* were empty or otherwise invalid, and they could not be
* to work correctly for that method.
*
* @return DataException
*/
public static function forInvalidArgument(string $argument)
{
return new static(lang('Database.invalidArgument', [$argument]));
}
/**
* @return DataException
*/
public static function forInvalidAllowedFields(string $model)
{
return new static(lang('Database.invalidAllowedFields', [$model]));
}
/**
* @return DataException
*/
public static function forTableNotFound(string $table)
{
return new static(lang('Database.tableNotFound', [$table]));
}
/**
* @return DataException
*/
public static function forEmptyInputGiven(string $argument)
{
return new static(lang('Database.forEmptyInputGiven', [$argument]));
}
/**
* @return DataException
*/
public static function forFindColumnHaveMultipleColumns()
{
return new static(lang('Database.forFindColumnHaveMultipleColumns'));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/Exceptions/ExceptionInterface.php | system/Database/Exceptions/ExceptionInterface.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\Database\Exceptions;
/**
* Provides a domain-level interface for broad capture
* of all database-related exceptions.
*
* catch (\CodeIgniter\Database\Exceptions\ExceptionInterface) { ... }
*/
interface ExceptionInterface extends \CodeIgniter\Exceptions\ExceptionInterface
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/Exceptions/DatabaseException.php | system/Database/Exceptions/DatabaseException.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\Database\Exceptions;
use CodeIgniter\Exceptions\HasExitCodeInterface;
use CodeIgniter\Exceptions\RuntimeException;
class DatabaseException extends RuntimeException implements ExceptionInterface, HasExitCodeInterface
{
public function getExitCode(): int
{
return EXIT_DATABASE;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/SQLite3/Connection.php | system/Database/SQLite3/Connection.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\Database\SQLite3;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\TableName;
use CodeIgniter\Exceptions\InvalidArgumentException;
use Exception;
use SQLite3;
use SQLite3Result;
use stdClass;
/**
* Connection for SQLite3
*
* @extends BaseConnection<SQLite3, SQLite3Result>
*/
class Connection extends BaseConnection
{
/**
* Database driver
*
* @var string
*/
public $DBDriver = 'SQLite3';
/**
* Identifier escape character
*
* @var string
*/
public $escapeChar = '`';
/**
* @var bool Enable Foreign Key constraint or not
*/
protected $foreignKeys = false;
/**
* The milliseconds to sleep
*
* @var int|null milliseconds
*
* @see https://www.php.net/manual/en/sqlite3.busytimeout
*/
protected $busyTimeout;
/**
* The setting of the "synchronous" flag
*
* @var int<0, 3>|null flag
*
* @see https://www.sqlite.org/pragma.html#pragma_synchronous
*/
protected ?int $synchronous = null;
/**
* @return void
*/
public function initialize()
{
parent::initialize();
if ($this->foreignKeys) {
$this->enableForeignKeyChecks();
}
if (is_int($this->busyTimeout)) {
$this->connID->busyTimeout($this->busyTimeout);
}
if (is_int($this->synchronous)) {
if (! in_array($this->synchronous, [0, 1, 2, 3], true)) {
throw new InvalidArgumentException('Invalid synchronous value.');
}
$this->connID->exec('PRAGMA synchronous = ' . $this->synchronous);
}
}
/**
* Connect to the database.
*
* @return SQLite3
*
* @throws DatabaseException
*/
public function connect(bool $persistent = false)
{
if ($persistent && $this->DBDebug) {
throw new DatabaseException('SQLite3 doesn\'t support persistent connections.');
}
try {
if ($this->database !== ':memory:' && ! str_contains($this->database, DIRECTORY_SEPARATOR)) {
$this->database = WRITEPATH . $this->database;
}
$sqlite = (! isset($this->password) || $this->password !== '')
? new SQLite3($this->database)
: new SQLite3($this->database, SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, $this->password);
$sqlite->enableExceptions(true);
return $sqlite;
} catch (Exception $e) {
throw new DatabaseException('SQLite3 error: ' . $e->getMessage());
}
}
/**
* Keep or establish the connection if no queries have been sent for
* a length of time exceeding the server's idle timeout.
*
* @return void
*/
public function reconnect()
{
$this->close();
$this->initialize();
}
/**
* Close the database connection.
*
* @return void
*/
protected function _close()
{
$this->connID->close();
}
/**
* Select a specific database table to use.
*/
public function setDatabase(string $databaseName): bool
{
return false;
}
/**
* Returns a string containing the version of the database being used.
*/
public function getVersion(): string
{
if (isset($this->dataCache['version'])) {
return $this->dataCache['version'];
}
$version = SQLite3::version();
return $this->dataCache['version'] = $version['versionString'];
}
/**
* Execute the query
*
* @return false|SQLite3Result
*/
protected function execute(string $sql)
{
try {
return $this->isWriteType($sql)
? $this->connID->exec($sql)
: $this->connID->query($sql);
} catch (Exception $e) {
log_message('error', (string) $e);
if ($this->DBDebug) {
throw new DatabaseException($e->getMessage(), $e->getCode(), $e);
}
}
return false;
}
/**
* Returns the total number of rows affected by this query.
*/
public function affectedRows(): int
{
return $this->connID->changes();
}
/**
* Platform-dependant string escape
*/
protected function _escapeString(string $str): string
{
if (! $this->connID instanceof SQLite3) {
$this->initialize();
}
return $this->connID->escapeString($str);
}
/**
* Generates the SQL for listing tables in a platform-dependent manner.
*
* @param string|null $tableName If $tableName is provided will return only this table if exists.
*/
protected function _listTables(bool $prefixLimit = false, ?string $tableName = null): string
{
if ((string) $tableName !== '') {
return 'SELECT "NAME" FROM "SQLITE_MASTER" WHERE "TYPE" = \'table\''
. ' AND "NAME" NOT LIKE \'sqlite!_%\' ESCAPE \'!\''
. ' AND "NAME" LIKE ' . $this->escape($tableName);
}
return 'SELECT "NAME" FROM "SQLITE_MASTER" WHERE "TYPE" = \'table\''
. ' AND "NAME" NOT LIKE \'sqlite!_%\' ESCAPE \'!\''
. (($prefixLimit && $this->DBPrefix !== '')
? ' AND "NAME" LIKE \'' . $this->escapeLikeString($this->DBPrefix) . '%\' ' . sprintf($this->likeEscapeStr, $this->likeEscapeChar)
: '');
}
/**
* Generates a platform-specific query string so that the column names can be fetched.
*
* @param string|TableName $table
*/
protected function _listColumns($table = ''): string
{
if ($table instanceof TableName) {
$tableName = $this->escapeIdentifier($table);
} else {
$tableName = $this->protectIdentifiers($table, true, null, false);
}
return 'PRAGMA TABLE_INFO(' . $tableName . ')';
}
/**
* @param string|TableName $tableName
*
* @return false|list<string>
*
* @throws DatabaseException
*/
public function getFieldNames($tableName)
{
$table = ($tableName instanceof TableName) ? $tableName->getTableName() : $tableName;
// Is there a cached result?
if (isset($this->dataCache['field_names'][$table])) {
return $this->dataCache['field_names'][$table];
}
if (! $this->connID instanceof SQLite3) {
$this->initialize();
}
$sql = $this->_listColumns($tableName);
$query = $this->query($sql);
$this->dataCache['field_names'][$table] = [];
foreach ($query->getResultArray() as $row) {
// Do we know from where to get the column's name?
if (! isset($key)) {
if (isset($row['column_name'])) {
$key = 'column_name';
} elseif (isset($row['COLUMN_NAME'])) {
$key = 'COLUMN_NAME';
} elseif (isset($row['name'])) {
$key = 'name';
} else {
// We have no other choice but to just get the first element's key.
$key = key($row);
}
}
$this->dataCache['field_names'][$table][] = $row[$key];
}
return $this->dataCache['field_names'][$table];
}
/**
* Returns an array of objects with field data
*
* @return list<stdClass>
*
* @throws DatabaseException
*/
protected function _fieldData(string $table): array
{
if (false === $query = $this->query('PRAGMA TABLE_INFO(' . $this->protectIdentifiers($table, true, null, false) . ')')) {
throw new DatabaseException(lang('Database.failGetFieldData'));
}
$query = $query->getResultObject();
if (empty($query)) {
return [];
}
$retVal = [];
for ($i = 0, $c = count($query); $i < $c; $i++) {
$retVal[$i] = new stdClass();
$retVal[$i]->name = $query[$i]->name;
$retVal[$i]->type = $query[$i]->type;
$retVal[$i]->max_length = null;
$retVal[$i]->nullable = isset($query[$i]->notnull) && ! (bool) $query[$i]->notnull;
$retVal[$i]->default = $query[$i]->dflt_value;
// "pk" (either zero for columns that are not part of the primary key,
// or the 1-based index of the column within the primary key).
// https://www.sqlite.org/pragma.html#pragma_table_info
$retVal[$i]->primary_key = ($query[$i]->pk === 0) ? 0 : 1;
}
return $retVal;
}
/**
* Returns an array of objects with index data
*
* @return array<string, stdClass>
*
* @throws DatabaseException
*/
protected function _indexData(string $table): array
{
$sql = "SELECT 'PRIMARY' as indexname, l.name as fieldname, 'PRIMARY' as indextype
FROM pragma_table_info(" . $this->escape(strtolower($table)) . ") as l
WHERE l.pk <> 0
UNION ALL
SELECT sqlite_master.name as indexname, ii.name as fieldname,
CASE
WHEN ti.pk <> 0 AND sqlite_master.name LIKE 'sqlite_autoindex_%' THEN 'PRIMARY'
WHEN sqlite_master.name LIKE 'sqlite_autoindex_%' THEN 'UNIQUE'
WHEN sqlite_master.sql LIKE '% UNIQUE %' THEN 'UNIQUE'
ELSE 'INDEX'
END as indextype
FROM sqlite_master
INNER JOIN pragma_index_xinfo(sqlite_master.name) ii ON ii.name IS NOT NULL
LEFT JOIN pragma_table_info(" . $this->escape(strtolower($table)) . ") ti ON ti.name = ii.name
WHERE sqlite_master.type='index' AND sqlite_master.tbl_name = " . $this->escape(strtolower($table)) . ' COLLATE NOCASE';
if (($query = $this->query($sql)) === false) {
throw new DatabaseException(lang('Database.failGetIndexData'));
}
$query = $query->getResultObject();
$tempVal = [];
foreach ($query as $row) {
if ($row->indextype === 'PRIMARY') {
$tempVal['PRIMARY']['indextype'] = $row->indextype;
$tempVal['PRIMARY']['indexname'] = $row->indexname;
$tempVal['PRIMARY']['fields'][$row->fieldname] = $row->fieldname;
} else {
$tempVal[$row->indexname]['indextype'] = $row->indextype;
$tempVal[$row->indexname]['indexname'] = $row->indexname;
$tempVal[$row->indexname]['fields'][$row->fieldname] = $row->fieldname;
}
}
$retVal = [];
foreach ($tempVal as $val) {
$obj = new stdClass();
$obj->name = $val['indexname'];
$obj->fields = array_values($val['fields']);
$obj->type = $val['indextype'];
$retVal[$obj->name] = $obj;
}
return $retVal;
}
/**
* Returns an array of objects with Foreign key data
*
* @return array<string, stdClass>
*/
protected function _foreignKeyData(string $table): array
{
if (! $this->supportsForeignKeys()) {
return [];
}
$query = $this->query("PRAGMA foreign_key_list({$table})")->getResult();
$indexes = [];
foreach ($query as $row) {
$indexes[$row->id]['constraint_name'] = null;
$indexes[$row->id]['table_name'] = $table;
$indexes[$row->id]['foreign_table_name'] = $row->table;
$indexes[$row->id]['column_name'][] = $row->from;
$indexes[$row->id]['foreign_column_name'][] = $row->to;
$indexes[$row->id]['on_delete'] = $row->on_delete;
$indexes[$row->id]['on_update'] = $row->on_update;
$indexes[$row->id]['match'] = $row->match;
}
return $this->foreignKeyDataToObjects($indexes);
}
/**
* Returns platform-specific SQL to disable foreign key checks.
*
* @return string
*/
protected function _disableForeignKeyChecks()
{
return 'PRAGMA foreign_keys = OFF';
}
/**
* Returns platform-specific SQL to enable foreign key checks.
*
* @return string
*/
protected function _enableForeignKeyChecks()
{
return 'PRAGMA foreign_keys = ON';
}
/**
* Returns the last error code and message.
* Must return this format: ['code' => string|int, 'message' => string]
* intval(code) === 0 means "no error".
*
* @return array<string, int|string>
*/
public function error(): array
{
return [
'code' => $this->connID->lastErrorCode(),
'message' => $this->connID->lastErrorMsg(),
];
}
/**
* Insert ID
*/
public function insertID(): int
{
return $this->connID->lastInsertRowID();
}
/**
* Begin Transaction
*/
protected function _transBegin(): bool
{
return $this->connID->exec('BEGIN TRANSACTION');
}
/**
* Commit Transaction
*/
protected function _transCommit(): bool
{
return $this->connID->exec('END TRANSACTION');
}
/**
* Rollback Transaction
*/
protected function _transRollback(): bool
{
return $this->connID->exec('ROLLBACK');
}
/**
* Checks to see if the current install supports Foreign Keys
* and has them enabled.
*/
public function supportsForeignKeys(): bool
{
$result = $this->simpleQuery('PRAGMA foreign_keys');
return (bool) $result;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/SQLite3/Result.php | system/Database/SQLite3/Result.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\Database\SQLite3;
use Closure;
use CodeIgniter\Database\BaseResult;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Entity\Entity;
use SQLite3;
use SQLite3Result;
use stdClass;
/**
* Result for SQLite3
*
* @extends BaseResult<SQLite3, SQLite3Result>
*/
class Result extends BaseResult
{
/**
* Gets the number of fields in the result set.
*/
public function getFieldCount(): int
{
return $this->resultID->numColumns();
}
/**
* Generates an array of column names in the result set.
*/
public function getFieldNames(): array
{
$fieldNames = [];
for ($i = 0, $c = $this->getFieldCount(); $i < $c; $i++) {
$fieldNames[] = $this->resultID->columnName($i);
}
return $fieldNames;
}
/**
* Generates an array of objects representing field meta-data.
*/
public function getFieldData(): array
{
static $dataTypes = [
SQLITE3_INTEGER => 'integer',
SQLITE3_FLOAT => 'float',
SQLITE3_TEXT => 'text',
SQLITE3_BLOB => 'blob',
SQLITE3_NULL => 'null',
];
$retVal = [];
$this->resultID->fetchArray(SQLITE3_NUM);
for ($i = 0, $c = $this->getFieldCount(); $i < $c; $i++) {
$retVal[$i] = new stdClass();
$retVal[$i]->name = $this->resultID->columnName($i);
$type = $this->resultID->columnType($i);
$retVal[$i]->type = $type;
$retVal[$i]->type_name = $dataTypes[$type] ?? null;
$retVal[$i]->max_length = null;
$retVal[$i]->length = null;
}
$this->resultID->reset();
return $retVal;
}
/**
* Frees the current result.
*
* @return void
*/
public function freeResult()
{
if (is_object($this->resultID)) {
$this->resultID->finalize();
$this->resultID = false;
}
}
/**
* Moves the internal pointer to the desired offset. This is called
* internally before fetching results to make sure the result set
* starts at zero.
*
* @return bool
*
* @throws DatabaseException
*/
public function dataSeek(int $n = 0)
{
if ($n !== 0) {
throw new DatabaseException('SQLite3 doesn\'t support seeking to other offset.');
}
return $this->resultID->reset();
}
/**
* Returns the result set as an array.
*
* Overridden by driver classes.
*
* @return array|false
*/
protected function fetchAssoc()
{
return $this->resultID->fetchArray(SQLITE3_ASSOC);
}
/**
* Returns the result set as an object.
*
* Overridden by child classes.
*
* @return Entity|false|object|stdClass
*/
protected function fetchObject(string $className = 'stdClass')
{
// No native support for fetching rows as objects
if (($row = $this->fetchAssoc()) === false) {
return false;
}
if ($className === 'stdClass') {
return (object) $row;
}
$classObj = new $className();
if (is_subclass_of($className, Entity::class)) {
return $classObj->injectRawData($row);
}
$classSet = Closure::bind(function ($key, $value): void {
$this->{$key} = $value;
}, $classObj, $className);
foreach (array_keys($row) as $key) {
$classSet($key, $row[$key]);
}
return $classObj;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/SQLite3/Builder.php | system/Database/SQLite3/Builder.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\Database\SQLite3;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\RawSql;
use CodeIgniter\Exceptions\InvalidArgumentException;
/**
* Builder for SQLite3
*/
class Builder extends BaseBuilder
{
/**
* Default installs of SQLite typically do not
* support limiting delete clauses.
*
* @var bool
*/
protected $canLimitDeletes = false;
/**
* Default installs of SQLite do no support
* limiting update queries in combo with WHERE.
*
* @var bool
*/
protected $canLimitWhereUpdates = false;
/**
* ORDER BY random keyword
*
* @var array
*/
protected $randomKeyword = [
'RANDOM()',
];
/**
* @var array<string, string>
*/
protected $supportedIgnoreStatements = [
'insert' => 'OR IGNORE',
];
/**
* Replace statement
*
* Generates a platform-specific replace string from the supplied data
*/
protected function _replace(string $table, array $keys, array $values): string
{
return 'INSERT OR ' . parent::_replace($table, $keys, $values);
}
/**
* Generates a platform-specific truncate string from the supplied data
*
* If the database does not support the TRUNCATE statement,
* then this method maps to 'DELETE FROM table'
*/
protected function _truncate(string $table): string
{
return 'DELETE FROM ' . $table;
}
/**
* Generates a platform-specific batch update string from the supplied data
*/
protected function _updateBatch(string $table, array $keys, array $values): string
{
if (version_compare($this->db->getVersion(), '3.33.0') >= 0) {
return parent::_updateBatch($table, $keys, $values);
}
$constraints = $this->QBOptions['constraints'] ?? [];
if ($constraints === []) {
if ($this->db->DBDebug) {
throw new DatabaseException('You must specify a constraint to match on for batch updates.');
}
return ''; // @codeCoverageIgnore
}
if (count($constraints) > 1 || isset($this->QBOptions['setQueryAsData']) || (current($constraints) instanceof RawSql)) {
throw new DatabaseException('You are trying to use a feature which requires SQLite version 3.33 or higher.');
}
$index = current($constraints);
$ids = [];
$final = [];
foreach ($values as $val) {
$val = array_combine($keys, $val);
$ids[] = $val[$index];
foreach (array_keys($val) as $field) {
if ($field !== $index) {
$final[$field][] = 'WHEN ' . $index . ' = ' . $val[$index] . ' THEN ' . $val[$field];
}
}
}
$cases = '';
foreach ($final as $k => $v) {
$cases .= $k . " = CASE \n"
. implode("\n", $v) . "\n"
. 'ELSE ' . $k . ' END, ';
}
$this->where($index . ' IN(' . implode(',', $ids) . ')', null, false);
return 'UPDATE ' . $this->compileIgnore('update') . $table . ' SET ' . substr($cases, 0, -2) . $this->compileWhereHaving('QBWhere');
}
/**
* Generates a platform-specific upsertBatch string from the supplied data
*
* @throws DatabaseException
*/
protected function _upsertBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$constraints = $this->QBOptions['constraints'] ?? [];
if (empty($constraints)) {
$fieldNames = array_map(static fn ($columnName): string => trim($columnName, '`'), $keys);
$allIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames): bool {
$hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields);
return ($index->type === 'PRIMARY' || $index->type === 'UNIQUE') && $hasAllFields;
});
foreach ($allIndexes as $index) {
$constraints = $index->fields;
break;
}
$constraints = $this->onConstraint($constraints)->QBOptions['constraints'] ?? [];
}
if (empty($constraints)) {
if ($this->db->DBDebug) {
throw new DatabaseException('No constraint found for upsert.');
}
return ''; // @codeCoverageIgnore
}
$alias = $this->QBOptions['alias'] ?? '`excluded`';
if (strtolower($alias) !== '`excluded`') {
throw new InvalidArgumentException('SQLite alias is always named "excluded". A custom alias cannot be used.');
}
$updateFields = $this->QBOptions['updateFields'] ??
$this->updateFields($keys, false, $constraints)->QBOptions['updateFields'] ??
[];
$sql = 'INSERT INTO ' . $table . ' (';
$sql .= implode(', ', array_map(static fn ($columnName): string => $columnName, $keys));
$sql .= ")\n";
$sql .= '{:_table_:}';
$sql .= 'ON CONFLICT(' . implode(',', $constraints) . ")\n";
$sql .= "DO UPDATE SET\n";
$sql .= implode(
",\n",
array_map(
static fn ($key, $value): string => $key . ($value instanceof RawSql ?
" = {$value}" :
" = {$alias}.{$value}"),
array_keys($updateFields),
$updateFields,
),
);
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$hasWhere = stripos($this->QBOptions['setQueryAsData'], 'WHERE') > 0;
$data = $this->QBOptions['setQueryAsData'] . ($hasWhere ? '' : "\nWHERE 1 = 1\n");
} else {
$data = 'VALUES ' . implode(', ', $this->formatValues($values)) . "\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Generates a platform-specific batch update string from the supplied data
*/
protected function _deleteBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$constraints = $this->QBOptions['constraints'] ?? [];
if ($constraints === []) {
if ($this->db->DBDebug) {
throw new DatabaseException('You must specify a constraint to match on for batch deletes.'); // @codeCoverageIgnore
}
return ''; // @codeCoverageIgnore
}
$sql = 'DELETE FROM ' . $table . "\n";
if (current($constraints) instanceof RawSql && $this->db->DBDebug) {
throw new DatabaseException('You cannot use RawSql for constraint in SQLite.');
// @codeCoverageIgnore
}
if (is_string(current(array_keys($constraints)))) {
$concat1 = implode(' || ', array_keys($constraints));
$concat2 = implode(' || ', array_values($constraints));
} else {
$concat1 = implode(' || ', $constraints);
$concat2 = $concat1;
}
$sql .= "WHERE {$concat1} IN (SELECT {$concat2} FROM (\n{:_table_:}))";
// where is not supported
if ($this->QBWhere !== [] && $this->db->DBDebug) {
throw new DatabaseException('You cannot use WHERE with SQLite.');
// @codeCoverageIgnore
}
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" UNION ALL\n",
array_map(
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index): string => $index . ' ' . $key,
$keys,
$value,
)),
$values,
),
) . "\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/SQLite3/Table.php | system/Database/SQLite3/Table.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\Database\SQLite3;
use CodeIgniter\Database\Exceptions\DataException;
use stdClass;
/**
* Provides missing features for altering tables that are common
* in other supported databases, but are missing from SQLite.
* These are needed in order to support migrations during testing
* when another database is used as the primary engine, but
* SQLite in memory databases are used for faster test execution.
*/
class Table
{
/**
* All of the fields this table represents.
*
* @var array<string, array<string, bool|int|string|null>> [name => attributes]
*/
protected $fields = [];
/**
* All of the unique/primary keys in the table.
*
* @var array
*/
protected $keys = [];
/**
* All of the foreign keys in the table.
*
* @var array
*/
protected $foreignKeys = [];
/**
* The name of the table we're working with.
*
* @var string
*/
protected $tableName;
/**
* The name of the table, with database prefix
*
* @var string
*/
protected $prefixedTableName;
/**
* Database connection.
*
* @var Connection
*/
protected $db;
/**
* Handle to our forge.
*
* @var Forge
*/
protected $forge;
/**
* Table constructor.
*/
public function __construct(Connection $db, Forge $forge)
{
$this->db = $db;
$this->forge = $forge;
}
/**
* Reads an existing database table and
* collects all of the information needed to
* recreate this table.
*
* @return Table
*/
public function fromTable(string $table)
{
$this->prefixedTableName = $table;
$prefix = $this->db->DBPrefix;
if (! empty($prefix) && str_starts_with($table, $prefix)) {
$table = substr($table, strlen($prefix));
}
if (! $this->db->tableExists($this->prefixedTableName)) {
throw DataException::forTableNotFound($this->prefixedTableName);
}
$this->tableName = $table;
$this->fields = $this->formatFields($this->db->getFieldData($table));
$this->keys = array_merge($this->keys, $this->formatKeys($this->db->getIndexData($table)));
// if primary key index exists twice then remove psuedo index name 'primary'.
$primaryIndexes = array_filter($this->keys, static fn ($index): bool => $index['type'] === 'primary');
if ($primaryIndexes !== [] && count($primaryIndexes) > 1 && array_key_exists('primary', $this->keys)) {
unset($this->keys['primary']);
}
$this->foreignKeys = $this->db->getForeignKeyData($table);
return $this;
}
/**
* Called after `fromTable` and any actions, like `dropColumn`, etc,
* to finalize the action. It creates a temp table, creates the new
* table with modifications, and copies the data over to the new table.
* Resets the connection dataCache to be sure changes are collected.
*/
public function run(): bool
{
$this->db->query('PRAGMA foreign_keys = OFF');
$this->db->transStart();
$this->forge->renameTable($this->tableName, "temp_{$this->tableName}");
$this->forge->reset();
$this->createTable();
$this->copyData();
$this->forge->dropTable("temp_{$this->tableName}");
$success = $this->db->transComplete();
$this->db->query('PRAGMA foreign_keys = ON');
$this->db->resetDataCache();
return $success;
}
/**
* Drops columns from the table.
*
* @param list<string>|string $columns Column names to drop.
*
* @return Table
*/
public function dropColumn($columns)
{
if (is_string($columns)) {
$columns = explode(',', $columns);
}
foreach ($columns as $column) {
$column = trim($column);
if (isset($this->fields[$column])) {
unset($this->fields[$column]);
}
}
return $this;
}
/**
* Modifies a field, including changing data type, renaming, etc.
*
* @param list<array<string, bool|int|string|null>> $fieldsToModify
*
* @return Table
*/
public function modifyColumn(array $fieldsToModify)
{
foreach ($fieldsToModify as $field) {
$oldName = $field['name'];
unset($field['name']);
$this->fields[$oldName] = $field;
}
return $this;
}
/**
* Drops the primary key
*/
public function dropPrimaryKey(): Table
{
$primaryIndexes = array_filter($this->keys, static fn ($index): bool => strtolower($index['type']) === 'primary');
foreach (array_keys($primaryIndexes) as $key) {
unset($this->keys[$key]);
}
return $this;
}
/**
* Drops a foreign key from this table so that
* it won't be recreated in the future.
*
* @return Table
*/
public function dropForeignKey(string $foreignName)
{
if (empty($this->foreignKeys)) {
return $this;
}
if (isset($this->foreignKeys[$foreignName])) {
unset($this->foreignKeys[$foreignName]);
}
return $this;
}
/**
* Adds primary key
*/
public function addPrimaryKey(array $fields): Table
{
$primaryIndexes = array_filter($this->keys, static fn ($index): bool => strtolower($index['type']) === 'primary');
// if primary key already exists we can't add another one
if ($primaryIndexes !== []) {
return $this;
}
// add array to keys of fields
$pk = [
'fields' => $fields['fields'],
'type' => 'primary',
];
$this->keys['primary'] = $pk;
return $this;
}
/**
* Add a foreign key
*
* @return $this
*/
public function addForeignKey(array $foreignKeys)
{
$fk = [];
// convert to object
foreach ($foreignKeys as $row) {
$obj = new stdClass();
$obj->column_name = $row['field'];
$obj->foreign_table_name = $row['referenceTable'];
$obj->foreign_column_name = $row['referenceField'];
$obj->on_delete = $row['onDelete'];
$obj->on_update = $row['onUpdate'];
$fk[] = $obj;
}
$this->foreignKeys = array_merge($this->foreignKeys, $fk);
return $this;
}
/**
* Creates the new table based on our current fields.
*
* @return bool
*/
protected function createTable()
{
$this->dropIndexes();
$this->db->resetDataCache();
// Handle any modified columns.
$fields = [];
foreach ($this->fields as $name => $field) {
if (isset($field['new_name'])) {
$fields[$field['new_name']] = $field;
continue;
}
$fields[$name] = $field;
}
$this->forge->addField($fields);
$fieldNames = array_keys($fields);
$this->keys = array_filter(
$this->keys,
static fn ($index): bool => count(array_intersect($index['fields'], $fieldNames)) === count($index['fields']),
);
// Unique/Index keys
if (is_array($this->keys)) {
foreach ($this->keys as $keyName => $key) {
switch ($key['type']) {
case 'primary':
$this->forge->addPrimaryKey($key['fields']);
break;
case 'unique':
$this->forge->addUniqueKey($key['fields'], $keyName);
break;
case 'index':
$this->forge->addKey($key['fields'], false, false, $keyName);
break;
}
}
}
foreach ($this->foreignKeys as $foreignKey) {
$this->forge->addForeignKey(
$foreignKey->column_name,
trim($foreignKey->foreign_table_name, $this->db->DBPrefix),
$foreignKey->foreign_column_name,
);
}
return $this->forge->createTable($this->tableName);
}
/**
* Copies data from our old table to the new one,
* taking care map data correctly based on any columns
* that have been renamed.
*
* @return void
*/
protected function copyData()
{
$exFields = [];
$newFields = [];
foreach ($this->fields as $name => $details) {
$newFields[] = $details['new_name'] ?? $name;
$exFields[] = $name;
}
$exFields = implode(
', ',
array_map(fn ($item) => $this->db->protectIdentifiers($item), $exFields),
);
$newFields = implode(
', ',
array_map(fn ($item) => $this->db->protectIdentifiers($item), $newFields),
);
$this->db->query(
"INSERT INTO {$this->prefixedTableName}({$newFields}) SELECT {$exFields} FROM {$this->db->DBPrefix}temp_{$this->tableName}",
);
}
/**
* Converts fields retrieved from the database to
* the format needed for creating fields with Forge.
*
* @param array|bool $fields
*
* @return ($fields is array ? array : mixed)
*/
protected function formatFields($fields)
{
if (! is_array($fields)) {
return $fields;
}
$return = [];
foreach ($fields as $field) {
$return[$field->name] = [
'type' => $field->type,
'default' => $field->default,
'null' => $field->nullable,
];
if ($field->default === null) {
// `null` means that the default value is not defined.
unset($return[$field->name]['default']);
} elseif ($field->default === 'NULL') {
// 'NULL' means that the default value is NULL.
$return[$field->name]['default'] = null;
} else {
$default = trim($field->default, "'");
if ($this->isIntegerType($field->type)) {
$default = (int) $default;
} elseif ($this->isNumericType($field->type)) {
$default = (float) $default;
}
$return[$field->name]['default'] = $default;
}
if ($field->primary_key) {
$this->keys['primary'] = [
'fields' => [$field->name],
'type' => 'primary',
];
}
}
return $return;
}
/**
* Is INTEGER type?
*
* @param string $type SQLite data type (case-insensitive)
*
* @see https://www.sqlite.org/datatype3.html
*/
private function isIntegerType(string $type): bool
{
return str_contains(strtoupper($type), 'INT');
}
/**
* Is NUMERIC type?
*
* @param string $type SQLite data type (case-insensitive)
*
* @see https://www.sqlite.org/datatype3.html
*/
private function isNumericType(string $type): bool
{
return in_array(strtoupper($type), ['NUMERIC', 'DECIMAL'], true);
}
/**
* Converts keys retrieved from the database to
* the format needed to create later.
*
* @param array<string, stdClass> $keys
*
* @return array<string, array{fields: string, type: string}>
*/
protected function formatKeys($keys)
{
$return = [];
foreach ($keys as $name => $key) {
$return[strtolower($name)] = [
'fields' => $key->fields,
'type' => strtolower($key->type),
];
}
return $return;
}
/**
* Attempts to drop all indexes and constraints
* from the database for this table.
*
* @return void
*/
protected function dropIndexes()
{
if (! is_array($this->keys) || $this->keys === []) {
return;
}
foreach (array_keys($this->keys) as $name) {
if ($name === 'primary') {
continue;
}
$this->db->query("DROP INDEX IF EXISTS '{$name}'");
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/SQLite3/PreparedQuery.php | system/Database/SQLite3/PreparedQuery.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\Database\SQLite3;
use CodeIgniter\Database\BasePreparedQuery;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Exceptions\BadMethodCallException;
use Exception;
use SQLite3;
use SQLite3Result;
use SQLite3Stmt;
/**
* Prepared query for SQLite3
*
* @extends BasePreparedQuery<SQLite3, SQLite3Stmt, SQLite3Result>
*/
class PreparedQuery extends BasePreparedQuery
{
/**
* The SQLite3Result resource, or false.
*
* @var false|SQLite3Result
*/
protected $result;
/**
* Prepares the query against the database, and saves the connection
* info necessary to execute the query later.
*
* NOTE: This version is based on SQL code. Child classes should
* override this method.
*
* @param array $options Passed to the connection's prepare statement.
* Unused in the MySQLi driver.
*/
public function _prepare(string $sql, array $options = []): PreparedQuery
{
if (! ($this->statement = $this->db->connID->prepare($sql))) {
$this->errorCode = $this->db->connID->lastErrorCode();
$this->errorString = $this->db->connID->lastErrorMsg();
if ($this->db->DBDebug) {
throw new DatabaseException($this->errorString . ' code: ' . $this->errorCode);
}
}
return $this;
}
/**
* Takes a new set of data and runs it against the currently
* prepared query. Upon success, will return a Results object.
*/
public function _execute(array $data): bool
{
if (! isset($this->statement)) {
throw new BadMethodCallException('You must call prepare before trying to execute a prepared statement.');
}
foreach ($data as $key => $item) {
// Determine the type string
if (is_int($item)) {
$bindType = SQLITE3_INTEGER;
} elseif (is_float($item)) {
$bindType = SQLITE3_FLOAT;
} elseif (is_string($item) && $this->isBinary($item)) {
$bindType = SQLITE3_BLOB;
} else {
$bindType = SQLITE3_TEXT;
}
// Bind it
$this->statement->bindValue($key + 1, $item, $bindType);
}
try {
$this->result = $this->statement->execute();
} catch (Exception $e) {
if ($this->db->DBDebug) {
throw new DatabaseException($e->getMessage(), $e->getCode(), $e);
}
return false;
}
return $this->result !== false;
}
/**
* Returns the result object for the prepared query or false on failure.
*
* @return false|SQLite3Result
*/
public function _getResult()
{
return $this->result;
}
/**
* Deallocate prepared statements.
*/
protected function _close(): bool
{
return $this->statement->close();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/SQLite3/Utils.php | system/Database/SQLite3/Utils.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\Database\SQLite3;
use CodeIgniter\Database\BaseUtils;
use CodeIgniter\Database\Exceptions\DatabaseException;
/**
* Utils for SQLite3
*/
class Utils extends BaseUtils
{
/**
* OPTIMIZE TABLE statement
*
* @var string
*/
protected $optimizeTable = 'REINDEX %s';
/**
* Platform dependent version of the backup function.
*
* @return never
*/
public function _backup(?array $prefs = null)
{
throw new DatabaseException('Unsupported feature of the database platform you are using.');
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/SQLite3/Forge.php | system/Database/SQLite3/Forge.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\Database\SQLite3;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\Forge as BaseForge;
/**
* Forge for SQLite3
*/
class Forge extends BaseForge
{
/**
* DROP INDEX statement
*
* @var string
*/
protected $dropIndexStr = 'DROP INDEX %s';
/**
* @var Connection
*/
protected $db;
/**
* UNSIGNED support
*
* @var array|bool
*/
protected $_unsigned = false;
/**
* NULL value representation in CREATE/ALTER TABLE statements
*
* @var string
*
* @internal
*/
protected $null = 'NULL';
/**
* Constructor.
*/
public function __construct(BaseConnection $db)
{
parent::__construct($db);
if (version_compare($this->db->getVersion(), '3.3', '<')) {
$this->dropTableIfStr = false;
}
}
/**
* Create database
*
* @param bool $ifNotExists Whether to add IF NOT EXISTS condition
*/
public function createDatabase(string $dbName, bool $ifNotExists = false): bool
{
// In SQLite, a database is created when you connect to the database.
// We'll return TRUE so that an error isn't generated.
return true;
}
/**
* Drop database
*
* @throws DatabaseException
*/
public function dropDatabase(string $dbName): bool
{
// In SQLite, a database is dropped when we delete a file
if (! is_file($dbName)) {
if ($this->db->DBDebug) {
throw new DatabaseException('Unable to drop the specified database.');
}
return false;
}
// We need to close the pseudo-connection first
$this->db->close();
if (! @unlink($dbName)) {
if ($this->db->DBDebug) {
throw new DatabaseException('Unable to drop the specified database.');
}
return false;
}
if (! empty($this->db->dataCache['db_names'])) {
$key = array_search(strtolower($dbName), array_map(strtolower(...), $this->db->dataCache['db_names']), true);
if ($key !== false) {
unset($this->db->dataCache['db_names'][$key]);
}
}
return true;
}
/**
* @param list<string>|string $columnNames
*
* @throws DatabaseException
*/
public function dropColumn(string $table, $columnNames): bool
{
$columns = is_array($columnNames) ? $columnNames : array_map(trim(...), explode(',', $columnNames));
$result = (new Table($this->db, $this))
->fromTable($this->db->DBPrefix . $table)
->dropColumn($columns)
->run();
if (! $result && $this->db->DBDebug) {
throw new DatabaseException(sprintf(
'Failed to drop column%s "%s" on "%s" table.',
count($columns) > 1 ? 's' : '',
implode('", "', $columns),
$table,
));
}
return $result;
}
/**
* @param array|string $processedFields Processed column definitions
* or column names to DROP
*
* @return ($alterType is 'DROP' ? string : list<string>|null)
*/
protected function _alterTable(string $alterType, string $table, $processedFields)
{
switch ($alterType) {
case 'CHANGE':
$fieldsToModify = [];
foreach ($processedFields as $processedField) {
$name = $processedField['name'];
$newName = $processedField['new_name'];
$field = $this->fields[$name];
$field['name'] = $name;
$field['new_name'] = $newName;
// Unlike when creating a table, if `null` is not specified,
// the column will be `NULL`, not `NOT NULL`.
if ($processedField['null'] === '') {
$field['null'] = true;
}
$fieldsToModify[] = $field;
}
(new Table($this->db, $this))
->fromTable($table)
->modifyColumn($fieldsToModify)
->run();
return null; // Why null?
default:
return parent::_alterTable($alterType, $table, $processedFields);
}
}
/**
* Process column
*/
protected function _processColumn(array $processedField): string
{
if ($processedField['type'] === 'TEXT' && str_starts_with($processedField['length'], "('")) {
$processedField['type'] .= ' CHECK(' . $this->db->escapeIdentifiers($processedField['name'])
. ' IN ' . $processedField['length'] . ')';
}
return $this->db->escapeIdentifiers($processedField['name'])
. ' ' . $processedField['type']
. $processedField['auto_increment']
. $processedField['null']
. $processedField['unique']
. $processedField['default'];
}
/**
* Field attribute TYPE
*
* Performs a data type mapping between different databases.
*/
protected function _attributeType(array &$attributes)
{
switch (strtoupper($attributes['TYPE'])) {
case 'ENUM':
case 'SET':
$attributes['TYPE'] = 'TEXT';
break;
case 'BOOLEAN':
$attributes['TYPE'] = 'INT';
break;
default:
break;
}
}
/**
* Field attribute AUTO_INCREMENT
*/
protected function _attributeAutoIncrement(array &$attributes, array &$field)
{
if (
! empty($attributes['AUTO_INCREMENT'])
&& $attributes['AUTO_INCREMENT'] === true
&& str_contains(strtolower($field['type']), 'int')
) {
$field['type'] = 'INTEGER PRIMARY KEY';
$field['default'] = '';
$field['null'] = '';
$field['unique'] = '';
$field['auto_increment'] = ' AUTOINCREMENT';
$this->primaryKeys = [];
}
}
/**
* Foreign Key Drop
*
* @throws DatabaseException
*/
public function dropForeignKey(string $table, string $foreignName): bool
{
// If this version of SQLite doesn't support it, we're done here
if ($this->db->supportsForeignKeys() !== true) {
return true;
}
// Otherwise we have to copy the table and recreate
// without the foreign key being involved now
$sqlTable = new Table($this->db, $this);
return $sqlTable->fromTable($this->db->DBPrefix . $table)
->dropForeignKey($foreignName)
->run();
}
/**
* Drop Primary Key
*/
public function dropPrimaryKey(string $table, string $keyName = ''): bool
{
$sqlTable = new Table($this->db, $this);
return $sqlTable->fromTable($this->db->DBPrefix . $table)
->dropPrimaryKey()
->run();
}
public function addForeignKey($fieldName = '', string $tableName = '', $tableField = '', string $onUpdate = '', string $onDelete = '', string $fkName = ''): BaseForge
{
if ($fkName === '') {
return parent::addForeignKey($fieldName, $tableName, $tableField, $onUpdate, $onDelete, $fkName);
}
throw new DatabaseException('SQLite does not support foreign key names. CodeIgniter will refer to them in the format: prefix_table_column_referencecolumn_foreign');
}
/**
* Generates SQL to add primary key
*
* @param bool $asQuery When true recreates table with key, else partial SQL used with CREATE TABLE
*/
protected function _processPrimaryKeys(string $table, bool $asQuery = false): string
{
if ($asQuery === false) {
return parent::_processPrimaryKeys($table, $asQuery);
}
$sqlTable = new Table($this->db, $this);
$sqlTable->fromTable($this->db->DBPrefix . $table)
->addPrimaryKey($this->primaryKeys)
->run();
return '';
}
/**
* Generates SQL to add foreign keys
*
* @param bool $asQuery When true recreates table with key, else partial SQL used with CREATE TABLE
*/
protected function _processForeignKeys(string $table, bool $asQuery = false): array
{
if ($asQuery === false) {
return parent::_processForeignKeys($table, $asQuery);
}
$errorNames = [];
foreach ($this->foreignKeys as $name) {
foreach ($name['field'] as $f) {
if (! isset($this->fields[$f])) {
$errorNames[] = $f;
}
}
}
if ($errorNames !== []) {
$errorNames = [implode(', ', $errorNames)];
throw new DatabaseException(lang('Database.fieldNotExists', $errorNames));
}
$sqlTable = new Table($this->db, $this);
$sqlTable->fromTable($this->db->DBPrefix . $table)
->addForeignKey($this->foreignKeys)
->run();
return [];
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/Postgre/Connection.php | system/Database/Postgre/Connection.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\Database\Postgre;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\RawSql;
use CodeIgniter\Database\TableName;
use ErrorException;
use PgSql\Connection as PgSqlConnection;
use PgSql\Result as PgSqlResult;
use stdClass;
use Stringable;
/**
* Connection for Postgre
*
* @extends BaseConnection<PgSqlConnection, PgSqlResult>
*/
class Connection extends BaseConnection
{
/**
* Database driver
*
* @var string
*/
public $DBDriver = 'Postgre';
/**
* Database schema
*
* @var string
*/
public $schema = 'public';
/**
* Identifier escape character
*
* @var string
*/
public $escapeChar = '"';
protected $connect_timeout;
protected $options;
protected $sslmode;
protected $service;
/**
* Connect to the database.
*
* @return false|PgSqlConnection
*/
public function connect(bool $persistent = false)
{
if (empty($this->DSN)) {
$this->buildDSN();
}
// Convert DSN string
// @TODO This format is for PDO_PGSQL.
// https://www.php.net/manual/en/ref.pdo-pgsql.connection.php
// Should deprecate?
if (mb_strpos($this->DSN, 'pgsql:') === 0) {
$this->convertDSN();
}
$this->connID = $persistent ? pg_pconnect($this->DSN) : pg_connect($this->DSN);
if ($this->connID !== false) {
if (
$persistent
&& pg_connection_status($this->connID) === PGSQL_CONNECTION_BAD
&& pg_ping($this->connID) === false
) {
$error = pg_last_error($this->connID);
throw new DatabaseException($error);
}
if (! empty($this->schema)) {
$this->simpleQuery("SET search_path TO {$this->schema},public");
}
if ($this->setClientEncoding($this->charset) === false) {
$error = pg_last_error($this->connID);
throw new DatabaseException($error);
}
}
return $this->connID;
}
/**
* Converts the DSN with semicolon syntax.
*
* @return void
*/
private function convertDSN()
{
// Strip pgsql
$this->DSN = mb_substr($this->DSN, 6);
// Convert semicolons to spaces in DSN format like:
// pgsql:host=localhost;port=5432;dbname=database_name
// https://www.php.net/manual/en/function.pg-connect.php
$allowedParams = ['host', 'port', 'dbname', 'user', 'password', 'connect_timeout', 'options', 'sslmode', 'service'];
$parameters = explode(';', $this->DSN);
$output = '';
$previousParameter = '';
foreach ($parameters as $parameter) {
[$key, $value] = explode('=', $parameter, 2);
if (in_array($key, $allowedParams, true)) {
if ($previousParameter !== '') {
if (array_search($key, $allowedParams, true) < array_search($previousParameter, $allowedParams, true)) {
$output .= ';';
} else {
$output .= ' ';
}
}
$output .= $parameter;
$previousParameter = $key;
} else {
$output .= ';' . $parameter;
}
}
$this->DSN = $output;
}
/**
* Keep or establish the connection if no queries have been sent for
* a length of time exceeding the server's idle timeout.
*
* @return void
*/
public function reconnect()
{
if ($this->connID === false || pg_ping($this->connID) === false) {
$this->close();
$this->initialize();
}
}
/**
* Close the database connection.
*
* @return void
*/
protected function _close()
{
pg_close($this->connID);
}
/**
* Select a specific database table to use.
*/
public function setDatabase(string $databaseName): bool
{
return false;
}
/**
* Returns a string containing the version of the database being used.
*/
public function getVersion(): string
{
if (isset($this->dataCache['version'])) {
return $this->dataCache['version'];
}
if (! $this->connID) {
$this->initialize();
}
$pgVersion = pg_version($this->connID);
$this->dataCache['version'] = isset($pgVersion['server']) ?
(preg_match('/^(\d+\.\d+)/', $pgVersion['server'], $matches) ? $matches[1] : '') :
'';
return $this->dataCache['version'];
}
/**
* Executes the query against the database.
*
* @return false|PgSqlResult
*/
protected function execute(string $sql)
{
try {
return pg_query($this->connID, $sql);
} catch (ErrorException $e) {
log_message('error', (string) $e);
if ($this->DBDebug) {
throw new DatabaseException($e->getMessage(), $e->getCode(), $e);
}
}
return false;
}
/**
* Get the prefix of the function to access the DB.
*/
protected function getDriverFunctionPrefix(): string
{
return 'pg_';
}
/**
* Returns the total number of rows affected by this query.
*/
public function affectedRows(): int
{
if ($this->resultID === false) {
return 0;
}
return pg_affected_rows($this->resultID);
}
/**
* "Smart" Escape String
*
* Escapes data based on type
*
* @param array|bool|float|int|object|string|null $str
*
* @return ($str is array ? array : float|int|string)
*/
public function escape($str)
{
if (! $this->connID) {
$this->initialize();
}
if ($str instanceof Stringable) {
if ($str instanceof RawSql) {
return $str->__toString();
}
$str = (string) $str;
}
if (is_string($str)) {
return pg_escape_literal($this->connID, $str);
}
if (is_bool($str)) {
return $str ? 'TRUE' : 'FALSE';
}
return parent::escape($str);
}
/**
* Platform-dependant string escape
*/
protected function _escapeString(string $str): string
{
if (! $this->connID) {
$this->initialize();
}
return pg_escape_string($this->connID, $str);
}
/**
* Generates the SQL for listing tables in a platform-dependent manner.
*
* @param string|null $tableName If $tableName is provided will return only this table if exists.
*/
protected function _listTables(bool $prefixLimit = false, ?string $tableName = null): string
{
$sql = 'SELECT "table_name" FROM "information_schema"."tables" WHERE "table_schema" = \'' . $this->schema . "'";
if ($tableName !== null) {
return $sql . ' AND "table_name" LIKE ' . $this->escape($tableName);
}
if ($prefixLimit && $this->DBPrefix !== '') {
return $sql . ' AND "table_name" LIKE \''
. $this->escapeLikeString($this->DBPrefix) . "%' "
. sprintf($this->likeEscapeStr, $this->likeEscapeChar);
}
return $sql;
}
/**
* Generates a platform-specific query string so that the column names can be fetched.
*
* @param string|TableName $table
*/
protected function _listColumns($table = ''): string
{
if ($table instanceof TableName) {
$tableName = $this->escape($table->getActualTableName());
} else {
$tableName = $this->escape($this->DBPrefix . strtolower($table));
}
return 'SELECT "column_name"
FROM "information_schema"."columns"
WHERE LOWER("table_name") = ' . $tableName
. ' ORDER BY "ordinal_position"';
}
/**
* Returns an array of objects with field data
*
* @return list<stdClass>
*
* @throws DatabaseException
*/
protected function _fieldData(string $table): array
{
$sql = 'SELECT "column_name", "data_type", "character_maximum_length", "numeric_precision", "column_default", "is_nullable"
FROM "information_schema"."columns"
WHERE LOWER("table_name") = '
. $this->escape(strtolower($table))
. ' ORDER BY "ordinal_position"';
if (($query = $this->query($sql)) === false) {
throw new DatabaseException(lang('Database.failGetFieldData'));
}
$query = $query->getResultObject();
$retVal = [];
for ($i = 0, $c = count($query); $i < $c; $i++) {
$retVal[$i] = new stdClass();
$retVal[$i]->name = $query[$i]->column_name;
$retVal[$i]->type = $query[$i]->data_type;
$retVal[$i]->max_length = $query[$i]->character_maximum_length > 0 ? $query[$i]->character_maximum_length : $query[$i]->numeric_precision;
$retVal[$i]->nullable = $query[$i]->is_nullable === 'YES';
$retVal[$i]->default = $query[$i]->column_default;
}
return $retVal;
}
/**
* Returns an array of objects with index data
*
* @return array<string, stdClass>
*
* @throws DatabaseException
*/
protected function _indexData(string $table): array
{
$sql = 'SELECT "indexname", "indexdef"
FROM "pg_indexes"
WHERE LOWER("tablename") = ' . $this->escape(strtolower($table)) . '
AND "schemaname" = ' . $this->escape('public');
if (($query = $this->query($sql)) === false) {
throw new DatabaseException(lang('Database.failGetIndexData'));
}
$query = $query->getResultObject();
$retVal = [];
foreach ($query as $row) {
$obj = new stdClass();
$obj->name = $row->indexname;
$_fields = explode(',', preg_replace('/^.*\((.+?)\)$/', '$1', trim($row->indexdef)));
$obj->fields = array_map(static fn ($v): string => trim($v), $_fields);
if (str_starts_with($row->indexdef, 'CREATE UNIQUE INDEX pk')) {
$obj->type = 'PRIMARY';
} else {
$obj->type = (str_starts_with($row->indexdef, 'CREATE UNIQUE')) ? 'UNIQUE' : 'INDEX';
}
$retVal[$obj->name] = $obj;
}
return $retVal;
}
/**
* Returns an array of objects with Foreign key data
*
* @return array<string, stdClass>
*
* @throws DatabaseException
*/
protected function _foreignKeyData(string $table): array
{
$sql = 'SELECT c.constraint_name,
x.table_name,
x.column_name,
y.table_name as foreign_table_name,
y.column_name as foreign_column_name,
c.delete_rule,
c.update_rule,
c.match_option
FROM information_schema.referential_constraints c
JOIN information_schema.key_column_usage x
on x.constraint_name = c.constraint_name
JOIN information_schema.key_column_usage y
on y.ordinal_position = x.position_in_unique_constraint
and y.constraint_name = c.unique_constraint_name
WHERE x.table_name = ' . $this->escape($table) .
'order by c.constraint_name, x.ordinal_position';
if (($query = $this->query($sql)) === false) {
throw new DatabaseException(lang('Database.failGetForeignKeyData'));
}
$query = $query->getResultObject();
$indexes = [];
foreach ($query as $row) {
$indexes[$row->constraint_name]['constraint_name'] = $row->constraint_name;
$indexes[$row->constraint_name]['table_name'] = $table;
$indexes[$row->constraint_name]['column_name'][] = $row->column_name;
$indexes[$row->constraint_name]['foreign_table_name'] = $row->foreign_table_name;
$indexes[$row->constraint_name]['foreign_column_name'][] = $row->foreign_column_name;
$indexes[$row->constraint_name]['on_delete'] = $row->delete_rule;
$indexes[$row->constraint_name]['on_update'] = $row->update_rule;
$indexes[$row->constraint_name]['match'] = $row->match_option;
}
return $this->foreignKeyDataToObjects($indexes);
}
/**
* Returns platform-specific SQL to disable foreign key checks.
*
* @return string
*/
protected function _disableForeignKeyChecks()
{
return 'SET CONSTRAINTS ALL DEFERRED';
}
/**
* Returns platform-specific SQL to enable foreign key checks.
*
* @return string
*/
protected function _enableForeignKeyChecks()
{
return 'SET CONSTRAINTS ALL IMMEDIATE;';
}
/**
* Returns the last error code and message.
* Must return this format: ['code' => string|int, 'message' => string]
* intval(code) === 0 means "no error".
*
* @return array<string, int|string>
*/
public function error(): array
{
return [
'code' => '',
'message' => pg_last_error($this->connID),
];
}
/**
* @return int|string
*/
public function insertID()
{
$v = pg_version($this->connID);
// 'server' key is only available since PostgreSQL 7.4
$v = explode(' ', $v['server'])[0] ?? 0;
$table = func_num_args() > 0 ? func_get_arg(0) : null;
$column = func_num_args() > 1 ? func_get_arg(1) : null;
if ($table === null && $v >= '8.1') {
$sql = 'SELECT LASTVAL() AS ins_id';
} elseif ($table !== null) {
if ($column !== null && $v >= '8.0') {
$sql = "SELECT pg_get_serial_sequence('{$table}', '{$column}') AS seq";
$query = $this->query($sql);
$query = $query->getRow();
$seq = $query->seq;
} else {
// seq_name passed in table parameter
$seq = $table;
}
$sql = "SELECT CURRVAL('{$seq}') AS ins_id";
} else {
return pg_last_oid($this->resultID);
}
$query = $this->query($sql);
$query = $query->getRow();
return (int) $query->ins_id;
}
/**
* Build a DSN from the provided parameters
*
* @return void
*/
protected function buildDSN()
{
if ($this->DSN !== '') {
$this->DSN = '';
}
// If UNIX sockets are used, we shouldn't set a port
if (str_contains($this->hostname, '/')) {
$this->port = '';
}
if ($this->hostname !== '') {
$this->DSN = "host={$this->hostname} ";
}
// ctype_digit only accepts strings
$port = (string) $this->port;
if ($port !== '' && ctype_digit($port)) {
$this->DSN .= "port={$port} ";
}
if ($this->username !== '') {
$this->DSN .= "user={$this->username} ";
// An empty password is valid!
// password must be set to null to ignore it.
if ($this->password !== null) {
$this->DSN .= "password='{$this->password}' ";
}
}
if ($this->database !== '') {
$this->DSN .= "dbname={$this->database} ";
}
// We don't have these options as elements in our standard configuration
// array, but they might be set by parse_url() if the configuration was
// provided via string> Example:
//
// Postgre://username:password@localhost:5432/database?connect_timeout=5&sslmode=1
foreach (['connect_timeout', 'options', 'sslmode', 'service'] as $key) {
if (isset($this->{$key}) && is_string($this->{$key}) && $this->{$key} !== '') {
$this->DSN .= "{$key}='{$this->{$key}}' ";
}
}
$this->DSN = rtrim($this->DSN);
}
/**
* Set client encoding
*/
protected function setClientEncoding(string $charset): bool
{
return pg_set_client_encoding($this->connID, $charset) === 0;
}
/**
* Begin Transaction
*/
protected function _transBegin(): bool
{
return (bool) pg_query($this->connID, 'BEGIN');
}
/**
* Commit Transaction
*/
protected function _transCommit(): bool
{
return (bool) pg_query($this->connID, 'COMMIT');
}
/**
* Rollback Transaction
*/
protected function _transRollback(): bool
{
return (bool) pg_query($this->connID, 'ROLLBACK');
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/Postgre/Result.php | system/Database/Postgre/Result.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\Database\Postgre;
use CodeIgniter\Database\BaseResult;
use CodeIgniter\Entity\Entity;
use PgSql\Connection as PgSqlConnection;
use PgSql\Result as PgSqlResult;
use stdClass;
/**
* Result for Postgre
*
* @extends BaseResult<PgSqlConnection, PgSqlResult>
*/
class Result extends BaseResult
{
/**
* Gets the number of fields in the result set.
*/
public function getFieldCount(): int
{
return pg_num_fields($this->resultID);
}
/**
* Generates an array of column names in the result set.
*/
public function getFieldNames(): array
{
$fieldNames = [];
for ($i = 0, $c = $this->getFieldCount(); $i < $c; $i++) {
$fieldNames[] = pg_field_name($this->resultID, $i);
}
return $fieldNames;
}
/**
* Generates an array of objects representing field meta-data.
*/
public function getFieldData(): array
{
$retVal = [];
for ($i = 0, $c = $this->getFieldCount(); $i < $c; $i++) {
$retVal[$i] = new stdClass();
$retVal[$i]->name = pg_field_name($this->resultID, $i);
$retVal[$i]->type = pg_field_type_oid($this->resultID, $i);
$retVal[$i]->type_name = pg_field_type($this->resultID, $i);
$retVal[$i]->max_length = pg_field_size($this->resultID, $i);
$retVal[$i]->length = $retVal[$i]->max_length;
// $retVal[$i]->primary_key = (int)($fieldData[$i]->flags & 2);
// $retVal[$i]->default = $fieldData[$i]->def;
}
return $retVal;
}
/**
* Frees the current result.
*
* @return void
*/
public function freeResult()
{
if ($this->resultID !== false) {
pg_free_result($this->resultID);
$this->resultID = false;
}
}
/**
* Moves the internal pointer to the desired offset. This is called
* internally before fetching results to make sure the result set
* starts at zero.
*
* @return bool
*/
public function dataSeek(int $n = 0)
{
return pg_result_seek($this->resultID, $n);
}
/**
* Returns the result set as an array.
*
* Overridden by driver classes.
*
* @return array|false
*/
protected function fetchAssoc()
{
return pg_fetch_assoc($this->resultID);
}
/**
* Returns the result set as an object.
*
* Overridden by child classes.
*
* @return Entity|false|object|stdClass
*/
protected function fetchObject(string $className = 'stdClass')
{
if (is_subclass_of($className, Entity::class)) {
return empty($data = $this->fetchAssoc()) ? false : (new $className())->injectRawData($data);
}
return pg_fetch_object($this->resultID, null, $className);
}
/**
* Returns the number of rows in the resultID (i.e., PostgreSQL query result resource)
*/
public function getNumRows(): int
{
if (! is_int($this->numRows)) {
$this->numRows = pg_num_rows($this->resultID);
}
return $this->numRows;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/Postgre/Builder.php | system/Database/Postgre/Builder.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\Database\Postgre;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\RawSql;
use CodeIgniter\Exceptions\InvalidArgumentException;
/**
* Builder for Postgre
*/
class Builder extends BaseBuilder
{
/**
* ORDER BY random keyword
*
* @var array
*/
protected $randomKeyword = [
'RANDOM()',
];
/**
* Specifies which sql statements
* support the ignore option.
*
* @var array<string, string>
*/
protected $supportedIgnoreStatements = [
'insert' => 'ON CONFLICT DO NOTHING',
];
/**
* Checks if the ignore option is supported by
* the Database Driver for the specific statement.
*
* @return string
*/
protected function compileIgnore(string $statement)
{
$sql = parent::compileIgnore($statement);
if (! empty($sql)) {
$sql = ' ' . trim($sql);
}
return $sql;
}
/**
* ORDER BY
*
* @param string $direction ASC, DESC or RANDOM
*
* @return BaseBuilder
*/
public function orderBy(string $orderBy, string $direction = '', ?bool $escape = null)
{
$direction = strtoupper(trim($direction));
if ($direction === 'RANDOM') {
if (ctype_digit($orderBy)) {
$orderBy = (float) ($orderBy > 1 ? "0.{$orderBy}" : $orderBy);
}
if (is_float($orderBy)) {
$this->db->simpleQuery("SET SEED {$orderBy}");
}
$orderBy = $this->randomKeyword[0];
$direction = '';
$escape = false;
}
return parent::orderBy($orderBy, $direction, $escape);
}
/**
* Increments a numeric column by the specified value.
*
* @return mixed
*
* @throws DatabaseException
*/
public function increment(string $column, int $value = 1)
{
$column = $this->db->protectIdentifiers($column);
$sql = $this->_update($this->QBFrom[0], [$column => "to_number({$column}, '9999999') + {$value}"]);
if (! $this->testMode) {
$this->resetWrite();
return $this->db->query($sql, $this->binds, false);
}
return true;
}
/**
* Decrements a numeric column by the specified value.
*
* @return mixed
*
* @throws DatabaseException
*/
public function decrement(string $column, int $value = 1)
{
$column = $this->db->protectIdentifiers($column);
$sql = $this->_update($this->QBFrom[0], [$column => "to_number({$column}, '9999999') - {$value}"]);
if (! $this->testMode) {
$this->resetWrite();
return $this->db->query($sql, $this->binds, false);
}
return true;
}
/**
* Compiles an replace into string and runs the query.
* Because PostgreSQL doesn't support the replace into command,
* we simply do a DELETE and an INSERT on the first key/value
* combo, assuming that it's either the primary key or a unique key.
*
* @param array|null $set An associative array of insert values
*
* @return mixed
*
* @throws DatabaseException
*/
public function replace(?array $set = null)
{
if ($set !== null) {
$this->set($set);
}
if ($this->QBSet === []) {
if ($this->db->DBDebug) {
throw new DatabaseException('You must use the "set" method to update an entry.');
}
return false; // @codeCoverageIgnore
}
$table = $this->QBFrom[0];
$set = $this->binds;
array_walk($set, static function (array &$item): void {
$item = $item[0];
});
$key = array_key_first($set);
$value = $set[$key];
$builder = $this->db->table($table);
$exists = $builder->where($key, $value, true)->get()->getFirstRow();
if (empty($exists) && $this->testMode) {
$result = $this->getCompiledInsert();
} elseif (empty($exists)) {
$result = $builder->insert($set);
} elseif ($this->testMode) {
$result = $this->where($key, $value, true)->getCompiledUpdate();
} else {
array_shift($set);
$result = $builder->where($key, $value, true)->update($set);
}
unset($builder);
$this->resetWrite();
$this->binds = [];
return $result;
}
/**
* Generates a platform-specific insert string from the supplied data
*/
protected function _insert(string $table, array $keys, array $unescapedKeys): string
{
return trim(sprintf('INSERT INTO %s (%s) VALUES (%s) %s', $table, implode(', ', $keys), implode(', ', $unescapedKeys), $this->compileIgnore('insert')));
}
/**
* Generates a platform-specific insert string from the supplied data.
*/
protected function _insertBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$sql = 'INSERT INTO ' . $table . '(' . implode(', ', $keys) . ")\n{:_table_:}\n";
$sql .= $this->compileIgnore('insert');
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = 'VALUES ' . implode(', ', $this->formatValues($values));
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Compiles a delete string and runs the query
*
* @param mixed $where
*
* @return mixed
*
* @throws DatabaseException
*/
public function delete($where = '', ?int $limit = null, bool $resetData = true)
{
if ($limit !== null && $limit !== 0 || ! empty($this->QBLimit)) {
throw new DatabaseException('PostgreSQL does not allow LIMITs on DELETE queries.');
}
return parent::delete($where, $limit, $resetData);
}
/**
* Generates a platform-specific LIMIT clause.
*/
protected function _limit(string $sql, bool $offsetIgnore = false): string
{
return $sql . ' LIMIT ' . $this->QBLimit . ($this->QBOffset ? " OFFSET {$this->QBOffset}" : '');
}
/**
* Generates a platform-specific update string from the supplied data
*
* @throws DatabaseException
*/
protected function _update(string $table, array $values): string
{
if (! empty($this->QBLimit)) {
throw new DatabaseException('Postgres does not support LIMITs with UPDATE queries.');
}
$this->QBOrderBy = [];
return parent::_update($table, $values);
}
/**
* Generates a platform-specific delete string from the supplied data
*/
protected function _delete(string $table): string
{
$this->QBLimit = false;
return parent::_delete($table);
}
/**
* Generates a platform-specific truncate string from the supplied data
*
* If the database does not support the truncate() command,
* then this method maps to 'DELETE FROM table'
*/
protected function _truncate(string $table): string
{
return 'TRUNCATE ' . $table . ' RESTART IDENTITY';
}
/**
* Platform independent LIKE statement builder.
*
* In PostgreSQL, the ILIKE operator will perform case insensitive
* searches according to the current locale.
*
* @see https://www.postgresql.org/docs/9.2/static/functions-matching.html
*/
protected function _like_statement(?string $prefix, string $column, ?string $not, string $bind, bool $insensitiveSearch = false): string
{
$op = $insensitiveSearch ? 'ILIKE' : 'LIKE';
return "{$prefix} {$column} {$not} {$op} :{$bind}:";
}
/**
* Generates the JOIN portion of the query
*
* @param RawSql|string $cond
*
* @return BaseBuilder
*/
public function join(string $table, $cond, string $type = '', ?bool $escape = null)
{
if (! in_array('FULL OUTER', $this->joinTypes, true)) {
$this->joinTypes = array_merge($this->joinTypes, ['FULL OUTER']);
}
return parent::join($table, $cond, $type, $escape);
}
/**
* Generates a platform-specific batch update string from the supplied data
*
* @used-by batchExecute()
*
* @param string $table Protected table name
* @param list<string> $keys QBKeys
* @param list<list<int|string>> $values QBSet
*/
protected function _updateBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$constraints = $this->QBOptions['constraints'] ?? [];
if ($constraints === []) {
if ($this->db->DBDebug) {
throw new DatabaseException('You must specify a constraint to match on for batch updates.'); // @codeCoverageIgnore
}
return ''; // @codeCoverageIgnore
}
$updateFields = $this->QBOptions['updateFields'] ??
$this->updateFields($keys, false, $constraints)->QBOptions['updateFields'] ??
[];
$alias = $this->QBOptions['alias'] ?? '_u';
$sql = 'UPDATE ' . $this->compileIgnore('update') . $table . "\n";
$sql .= "SET\n";
$that = $this;
$sql .= implode(
",\n",
array_map(
static fn ($key, $value): string => $key . ($value instanceof RawSql ?
' = ' . $value :
' = ' . $that->cast($alias . '.' . $value, $that->getFieldType($table, $key))),
array_keys($updateFields),
$updateFields,
),
) . "\n";
$sql .= "FROM (\n{:_table_:}";
$sql .= ') ' . $alias . "\n";
$sql .= 'WHERE ' . implode(
' AND ',
array_map(
static function ($key, $value) use ($table, $alias, $that): string|RawSql {
if ($value instanceof RawSql && is_string($key)) {
return $table . '.' . $key . ' = ' . $value;
}
if ($value instanceof RawSql) {
return $value;
}
return $table . '.' . $value . ' = '
. $that->cast($alias . '.' . $value, $that->getFieldType($table, $value));
},
array_keys($constraints),
$constraints,
),
);
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" UNION ALL\n",
array_map(
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index): string => $index . ' ' . $key,
$keys,
$value,
)),
$values,
),
) . "\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Returns cast expression.
*
* @TODO move this to BaseBuilder in 4.5.0
*/
private function cast(string $expression, ?string $type): string
{
return ($type === null) ? $expression : 'CAST(' . $expression . ' AS ' . strtoupper($type) . ')';
}
/**
* Returns the filed type from database meta data.
*
* @param string $table Protected table name.
* @param string $fieldName Field name. May be protected.
*/
private function getFieldType(string $table, string $fieldName): ?string
{
$fieldName = trim($fieldName, $this->db->escapeChar);
if (! isset($this->QBOptions['fieldTypes'][$table])) {
$this->QBOptions['fieldTypes'][$table] = [];
foreach ($this->db->getFieldData($table) as $field) {
$type = $field->type;
// If `character` (or `char`) lacks a specifier, it is equivalent
// to `character(1)`.
// See https://www.postgresql.org/docs/current/datatype-character.html
if ($field->type === 'character') {
$type = $field->type . '(' . $field->max_length . ')';
}
$this->QBOptions['fieldTypes'][$table][$field->name] = $type;
}
}
return $this->QBOptions['fieldTypes'][$table][$fieldName] ?? null;
}
/**
* Generates a platform-specific upsertBatch string from the supplied data
*
* @throws DatabaseException
*/
protected function _upsertBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$fieldNames = array_map(static fn ($columnName): string => trim($columnName, '"'), $keys);
$constraints = $this->QBOptions['constraints'] ?? [];
if (empty($constraints)) {
$allIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames): bool {
$hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields);
return ($index->type === 'UNIQUE' || $index->type === 'PRIMARY') && $hasAllFields;
});
foreach ($allIndexes as $index) {
$constraints = $index->fields;
break;
}
$constraints = $this->onConstraint($constraints)->QBOptions['constraints'] ?? [];
}
if (empty($constraints)) {
if ($this->db->DBDebug) {
throw new DatabaseException('No constraint found for upsert.');
}
return ''; // @codeCoverageIgnore
}
// in value set - replace null with DEFAULT where constraint is presumed not null
// autoincrement identity field must use DEFAULT and not NULL
// this could be removed in favour of leaving to developer but does make things easier and function like other DBMS
foreach ($constraints as $constraint) {
$key = array_search(trim((string) $constraint, '"'), $fieldNames, true);
if ($key !== false) {
foreach ($values as $arrayKey => $value) {
if (strtoupper((string) $value[$key]) === 'NULL') {
$values[$arrayKey][$key] = 'DEFAULT';
}
}
}
}
$alias = $this->QBOptions['alias'] ?? '"excluded"';
if (strtolower($alias) !== '"excluded"') {
throw new InvalidArgumentException('Postgres alias is always named "excluded". A custom alias cannot be used.');
}
$updateFields = $this->QBOptions['updateFields'] ?? $this->updateFields($keys, false, $constraints)->QBOptions['updateFields'] ?? [];
$sql = 'INSERT INTO ' . $table . ' (';
$sql .= implode(', ', $keys);
$sql .= ")\n";
$sql .= '{:_table_:}';
$sql .= 'ON CONFLICT(' . implode(',', $constraints) . ")\n";
$sql .= "DO UPDATE SET\n";
$sql .= implode(
",\n",
array_map(
static fn ($key, $value): string => $key . ($value instanceof RawSql ?
" = {$value}" :
" = {$alias}.{$value}"),
array_keys($updateFields),
$updateFields,
),
);
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = 'VALUES ' . implode(', ', $this->formatValues($values)) . "\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Generates a platform-specific batch update string from the supplied data
*/
protected function _deleteBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$constraints = $this->QBOptions['constraints'] ?? [];
if ($constraints === []) {
if ($this->db->DBDebug) {
throw new DatabaseException('You must specify a constraint to match on for batch deletes.'); // @codeCoverageIgnore
}
return ''; // @codeCoverageIgnore
}
$alias = $this->QBOptions['alias'] ?? '_u';
$sql = 'DELETE FROM ' . $table . "\n";
$sql .= "USING (\n{:_table_:}";
$sql .= ') ' . $alias . "\n";
$that = $this;
$sql .= 'WHERE ' . implode(
' AND ',
array_map(
static function ($key, $value) use ($table, $alias, $that): RawSql|string {
if ($value instanceof RawSql) {
return $value;
}
if (is_string($key)) {
return $table . '.' . $key . ' = '
. $that->cast(
$alias . '.' . $value,
$that->getFieldType($table, $key),
);
}
return $table . '.' . $value . ' = ' . $alias . '.' . $value;
},
array_keys($constraints),
$constraints,
),
);
// convert binds in where
foreach ($this->QBWhere as $key => $where) {
foreach ($this->binds as $field => $bind) {
$this->QBWhere[$key]['condition'] = str_replace(':' . $field . ':', $bind[0], $where['condition']);
}
}
$sql .= ' ' . str_replace(
'WHERE ',
'AND ',
$this->compileWhereHaving('QBWhere'),
);
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" UNION ALL\n",
array_map(
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index): string => $index . ' ' . $key,
$keys,
$value,
)),
$values,
),
) . "\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/Postgre/PreparedQuery.php | system/Database/Postgre/PreparedQuery.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\Database\Postgre;
use CodeIgniter\Database\BasePreparedQuery;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Exceptions\BadMethodCallException;
use Exception;
use PgSql\Connection as PgSqlConnection;
use PgSql\Result as PgSqlResult;
/**
* Prepared query for Postgre
*
* @extends BasePreparedQuery<PgSqlConnection, PgSqlResult, PgSqlResult>
*/
class PreparedQuery extends BasePreparedQuery
{
/**
* Stores the name this query can be
* used under by postgres. Only used internally.
*
* @var string
*/
protected $name;
/**
* The result resource from a successful
* pg_exec. Or false.
*
* @var false|PgSqlResult
*/
protected $result;
/**
* Prepares the query against the database, and saves the connection
* info necessary to execute the query later.
*
* NOTE: This version is based on SQL code. Child classes should
* override this method.
*
* @param array $options Passed to the connection's prepare statement.
* Unused in the MySQLi driver.
*
* @throws Exception
*/
public function _prepare(string $sql, array $options = []): PreparedQuery
{
$this->name = (string) random_int(1, 10_000_000_000_000_000);
$sql = $this->parameterize($sql);
// Update the query object since the parameters are slightly different
// than what was put in.
$this->query->setQuery($sql);
if (! $this->statement = pg_prepare($this->db->connID, $this->name, $sql)) {
$this->errorCode = 0;
$this->errorString = pg_last_error($this->db->connID);
if ($this->db->DBDebug) {
throw new DatabaseException($this->errorString . ' code: ' . $this->errorCode);
}
}
return $this;
}
/**
* Takes a new set of data and runs it against the currently
* prepared query. Upon success, will return a Results object.
*/
public function _execute(array $data): bool
{
if (! isset($this->statement)) {
throw new BadMethodCallException('You must call prepare before trying to execute a prepared statement.');
}
foreach ($data as &$item) {
if (is_string($item) && $this->isBinary($item)) {
$item = pg_escape_bytea($this->db->connID, $item);
}
}
$this->result = pg_execute($this->db->connID, $this->name, $data);
return (bool) $this->result;
}
/**
* Returns the result object for the prepared query or false on failure.
*
* @return PgSqlResult|null
*/
public function _getResult()
{
return $this->result;
}
/**
* Deallocate prepared statements.
*/
protected function _close(): bool
{
return pg_query($this->db->connID, 'DEALLOCATE "' . $this->db->escapeIdentifiers($this->name) . '"') !== false;
}
/**
* Replaces the ? placeholders with $1, $2, etc parameters for use
* within the prepared query.
*/
public function parameterize(string $sql): string
{
// Track our current value
$count = 0;
return preg_replace_callback('/\?/', static function () use (&$count): string {
$count++;
return "\${$count}";
}, $sql);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/Postgre/Utils.php | system/Database/Postgre/Utils.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\Database\Postgre;
use CodeIgniter\Database\BaseUtils;
use CodeIgniter\Database\Exceptions\DatabaseException;
/**
* Utils for Postgre
*/
class Utils extends BaseUtils
{
/**
* List databases statement
*
* @var string
*/
protected $listDatabases = 'SELECT datname FROM pg_database';
/**
* OPTIMIZE TABLE statement
*
* @var string
*/
protected $optimizeTable = 'REINDEX TABLE %s';
/**
* Platform dependent version of the backup function.
*
* @return never
*/
public function _backup(?array $prefs = null)
{
throw new DatabaseException('Unsupported feature of the database platform you are using.');
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/Postgre/Forge.php | system/Database/Postgre/Forge.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\Database\Postgre;
use CodeIgniter\Database\Forge as BaseForge;
/**
* Forge for Postgre
*/
class Forge extends BaseForge
{
/**
* CHECK DATABASE EXIST statement
*
* @var string
*/
protected $checkDatabaseExistStr = 'SELECT 1 FROM pg_database WHERE datname = ?';
/**
* DROP CONSTRAINT statement
*
* @var string
*/
protected $dropConstraintStr = 'ALTER TABLE %s DROP CONSTRAINT %s';
/**
* DROP INDEX statement
*
* @var string
*/
protected $dropIndexStr = 'DROP INDEX %s';
/**
* UNSIGNED support
*
* @var array
*/
protected $_unsigned = [
'INT2' => 'INTEGER',
'SMALLINT' => 'INTEGER',
'INT' => 'BIGINT',
'INT4' => 'BIGINT',
'INTEGER' => 'BIGINT',
'INT8' => 'NUMERIC',
'BIGINT' => 'NUMERIC',
'REAL' => 'DOUBLE PRECISION',
'FLOAT' => 'DOUBLE PRECISION',
];
/**
* NULL value representation in CREATE/ALTER TABLE statements
*
* @var string
*
* @internal
*/
protected $null = 'NULL';
/**
* @var Connection
*/
protected $db;
/**
* CREATE TABLE attributes
*
* @param array $attributes Associative array of table attributes
*/
protected function _createTableAttributes(array $attributes): string
{
return '';
}
/**
* @param array|string $processedFields Processed column definitions
* or column names to DROP
*
* @return ($alterType is 'DROP' ? string : false|list<string>)
*/
protected function _alterTable(string $alterType, string $table, $processedFields)
{
if (in_array($alterType, ['DROP', 'ADD'], true)) {
return parent::_alterTable($alterType, $table, $processedFields);
}
$sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table);
$sqls = [];
foreach ($processedFields as $field) {
if ($field['_literal'] !== false) {
return false;
}
if (version_compare($this->db->getVersion(), '8', '>=') && isset($field['type'])) {
$sqls[] = $sql . ' ALTER COLUMN ' . $this->db->escapeIdentifiers($field['name'])
. " TYPE {$field['type']}{$field['length']}";
}
if (! empty($field['default'])) {
$sqls[] = $sql . ' ALTER COLUMN ' . $this->db->escapeIdentifiers($field['name'])
. " SET DEFAULT {$field['default']}";
}
$nullable = true; // Nullable by default.
if (isset($field['null']) && ($field['null'] === false || $field['null'] === ' NOT ' . $this->null)) {
$nullable = false;
}
$sqls[] = $sql . ' ALTER COLUMN ' . $this->db->escapeIdentifiers($field['name'])
. ($nullable ? ' DROP' : ' SET') . ' NOT NULL';
if (! empty($field['new_name'])) {
$sqls[] = $sql . ' RENAME COLUMN ' . $this->db->escapeIdentifiers($field['name'])
. ' TO ' . $this->db->escapeIdentifiers($field['new_name']);
}
if (! empty($field['comment'])) {
$sqls[] = 'COMMENT ON COLUMN' . $this->db->escapeIdentifiers($table)
. '.' . $this->db->escapeIdentifiers($field['name'])
. " IS {$field['comment']}";
}
}
return $sqls;
}
/**
* Process column
*/
protected function _processColumn(array $processedField): string
{
return $this->db->escapeIdentifiers($processedField['name'])
. ' ' . $processedField['type'] . ($processedField['type'] === 'text' ? '' : $processedField['length'])
. $processedField['default']
. $processedField['null']
. $processedField['auto_increment']
. $processedField['unique'];
}
/**
* Performs a data type mapping between different databases.
*/
protected function _attributeType(array &$attributes)
{
// Reset field lengths for data types that don't support it
if (isset($attributes['CONSTRAINT']) && str_contains(strtolower($attributes['TYPE']), 'int')) {
$attributes['CONSTRAINT'] = null;
}
switch (strtoupper($attributes['TYPE'])) {
case 'TINYINT':
$attributes['TYPE'] = 'SMALLINT';
$attributes['UNSIGNED'] = false;
break;
case 'MEDIUMINT':
$attributes['TYPE'] = 'INTEGER';
$attributes['UNSIGNED'] = false;
break;
case 'DATETIME':
$attributes['TYPE'] = 'TIMESTAMP';
break;
case 'BLOB':
$attributes['TYPE'] = 'BYTEA';
break;
default:
break;
}
}
/**
* Field attribute AUTO_INCREMENT
*/
protected function _attributeAutoIncrement(array &$attributes, array &$field)
{
if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true) {
$field['type'] = $field['type'] === 'NUMERIC' || $field['type'] === 'BIGINT' ? 'BIGSERIAL' : 'SERIAL';
}
}
/**
* Generates a platform-specific DROP TABLE string
*/
protected function _dropTable(string $table, bool $ifExists, bool $cascade): string
{
$sql = parent::_dropTable($table, $ifExists, $cascade);
if ($cascade) {
$sql .= ' CASCADE';
}
return $sql;
}
/**
* Constructs sql to check if key is a constraint.
*/
protected function _dropKeyAsConstraint(string $table, string $constraintName): string
{
return "SELECT con.conname
FROM pg_catalog.pg_constraint con
INNER JOIN pg_catalog.pg_class rel
ON rel.oid = con.conrelid
INNER JOIN pg_catalog.pg_namespace nsp
ON nsp.oid = connamespace
WHERE nsp.nspname = '{$this->db->schema}'
AND rel.relname = '" . trim($table, '"') . "'
AND con.conname = '" . trim($constraintName, '"') . "'";
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/MySQLi/Connection.php | system/Database/MySQLi/Connection.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\Database\MySQLi;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\TableName;
use CodeIgniter\Exceptions\LogicException;
use mysqli;
use mysqli_result;
use mysqli_sql_exception;
use stdClass;
use Throwable;
/**
* Connection for MySQLi
*
* @extends BaseConnection<mysqli, mysqli_result>
*/
class Connection extends BaseConnection
{
/**
* Database driver
*
* @var string
*/
public $DBDriver = 'MySQLi';
/**
* DELETE hack flag
*
* Whether to use the MySQL "delete hack" which allows the number
* of affected rows to be shown. Uses a preg_replace when enabled,
* adding a bit more processing to all queries.
*
* @var bool
*/
public $deleteHack = true;
/**
* Identifier escape character
*
* @var string
*/
public $escapeChar = '`';
/**
* MySQLi object
*
* Has to be preserved without being assigned to $connId.
*
* @var false|mysqli
*/
public $mysqli;
/**
* MySQLi constant
*
* For unbuffered queries use `MYSQLI_USE_RESULT`.
*
* Default mode for buffered queries uses `MYSQLI_STORE_RESULT`.
*
* @var int
*/
public $resultMode = MYSQLI_STORE_RESULT;
/**
* Use MYSQLI_OPT_INT_AND_FLOAT_NATIVE
*
* @var bool
*/
public $numberNative = false;
/**
* Use MYSQLI_CLIENT_FOUND_ROWS
*
* Whether affectedRows() should return number of rows found,
* or number of rows changed, after an UPDATE query.
*
* @var bool
*/
public $foundRows = false;
/**
* Connect to the database.
*
* @return false|mysqli
*
* @throws DatabaseException
*/
public function connect(bool $persistent = false)
{
// Do we have a socket path?
if ($this->hostname[0] === '/') {
$hostname = null;
$port = null;
$socket = $this->hostname;
} else {
$hostname = $persistent ? 'p:' . $this->hostname : $this->hostname;
$port = empty($this->port) ? null : $this->port;
$socket = '';
}
$clientFlags = ($this->compress === true) ? MYSQLI_CLIENT_COMPRESS : 0;
$this->mysqli = mysqli_init();
mysqli_report(MYSQLI_REPORT_ALL & ~MYSQLI_REPORT_INDEX);
$this->mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);
if ($this->numberNative === true) {
$this->mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
}
if (isset($this->strictOn)) {
if ($this->strictOn) {
$this->mysqli->options(
MYSQLI_INIT_COMMAND,
"SET SESSION sql_mode = CONCAT(@@sql_mode, ',', 'STRICT_ALL_TABLES')",
);
} else {
$this->mysqli->options(
MYSQLI_INIT_COMMAND,
"SET SESSION sql_mode = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
@@sql_mode,
'STRICT_ALL_TABLES,', ''),
',STRICT_ALL_TABLES', ''),
'STRICT_ALL_TABLES', ''),
'STRICT_TRANS_TABLES,', ''),
',STRICT_TRANS_TABLES', ''),
'STRICT_TRANS_TABLES', '')",
);
}
}
if (is_array($this->encrypt)) {
$ssl = [];
if (! empty($this->encrypt['ssl_key'])) {
$ssl['key'] = $this->encrypt['ssl_key'];
}
if (! empty($this->encrypt['ssl_cert'])) {
$ssl['cert'] = $this->encrypt['ssl_cert'];
}
if (! empty($this->encrypt['ssl_ca'])) {
$ssl['ca'] = $this->encrypt['ssl_ca'];
}
if (! empty($this->encrypt['ssl_capath'])) {
$ssl['capath'] = $this->encrypt['ssl_capath'];
}
if (! empty($this->encrypt['ssl_cipher'])) {
$ssl['cipher'] = $this->encrypt['ssl_cipher'];
}
if ($ssl !== []) {
if (isset($this->encrypt['ssl_verify'])) {
if ($this->encrypt['ssl_verify']) {
if (defined('MYSQLI_OPT_SSL_VERIFY_SERVER_CERT')) {
$this->mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, 1);
}
}
// Apparently (when it exists), setting MYSQLI_OPT_SSL_VERIFY_SERVER_CERT
// to FALSE didn't do anything, so PHP 5.6.16 introduced yet another
// constant ...
//
// https://secure.php.net/ChangeLog-5.php#5.6.16
// https://bugs.php.net/bug.php?id=68344
elseif (defined('MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT') && version_compare($this->mysqli->client_info, 'mysqlnd 5.6', '>=')) {
$clientFlags += MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
}
}
$this->mysqli->ssl_set(
$ssl['key'] ?? null,
$ssl['cert'] ?? null,
$ssl['ca'] ?? null,
$ssl['capath'] ?? null,
$ssl['cipher'] ?? null,
);
}
$clientFlags += MYSQLI_CLIENT_SSL;
}
if ($this->foundRows) {
$clientFlags += MYSQLI_CLIENT_FOUND_ROWS;
}
try {
if ($this->mysqli->real_connect(
$hostname,
$this->username,
$this->password,
$this->database,
$port,
$socket,
$clientFlags,
)) {
// Prior to version 5.7.3, MySQL silently downgrades to an unencrypted connection if SSL setup fails
if (($clientFlags & MYSQLI_CLIENT_SSL) !== 0 && version_compare($this->mysqli->client_info, 'mysqlnd 5.7.3', '<=')
&& empty($this->mysqli->query("SHOW STATUS LIKE 'ssl_cipher'")->fetch_object()->Value)
) {
$this->mysqli->close();
$message = 'MySQLi was configured for an SSL connection, but got an unencrypted connection instead!';
log_message('error', $message);
if ($this->DBDebug) {
throw new DatabaseException($message);
}
return false;
}
if (! $this->mysqli->set_charset($this->charset)) {
log_message('error', "Database: Unable to set the configured connection charset ('{$this->charset}').");
$this->mysqli->close();
if ($this->DBDebug) {
throw new DatabaseException('Unable to set client connection character set: ' . $this->charset);
}
return false;
}
return $this->mysqli;
}
} catch (Throwable $e) {
// Clean sensitive information from errors.
$msg = $e->getMessage();
$msg = str_replace($this->username, '****', $msg);
$msg = str_replace($this->password, '****', $msg);
throw new DatabaseException($msg, $e->getCode(), $e);
}
return false;
}
/**
* Keep or establish the connection if no queries have been sent for
* a length of time exceeding the server's idle timeout.
*
* @return void
*/
public function reconnect()
{
$this->close();
$this->initialize();
}
/**
* Close the database connection.
*
* @return void
*/
protected function _close()
{
$this->connID->close();
}
/**
* Select a specific database table to use.
*/
public function setDatabase(string $databaseName): bool
{
if ($databaseName === '') {
$databaseName = $this->database;
}
if (empty($this->connID)) {
$this->initialize();
}
if ($this->connID->select_db($databaseName)) {
$this->database = $databaseName;
return true;
}
return false;
}
/**
* Returns a string containing the version of the database being used.
*/
public function getVersion(): string
{
if (isset($this->dataCache['version'])) {
return $this->dataCache['version'];
}
if (empty($this->mysqli)) {
$this->initialize();
}
return $this->dataCache['version'] = $this->mysqli->server_info;
}
/**
* Executes the query against the database.
*
* @return false|mysqli_result
*/
protected function execute(string $sql)
{
while ($this->connID->more_results()) {
$this->connID->next_result();
if ($res = $this->connID->store_result()) {
$res->free();
}
}
try {
return $this->connID->query($this->prepQuery($sql), $this->resultMode);
} catch (mysqli_sql_exception $e) {
log_message('error', (string) $e);
if ($this->DBDebug) {
throw new DatabaseException($e->getMessage(), $e->getCode(), $e);
}
}
return false;
}
/**
* Prep the query. If needed, each database adapter can prep the query string
*/
protected function prepQuery(string $sql): string
{
// mysqli_affected_rows() returns 0 for "DELETE FROM TABLE" queries. This hack
// modifies the query so that it a proper number of affected rows is returned.
if ($this->deleteHack === true && preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $sql)) {
return trim($sql) . ' WHERE 1=1';
}
return $sql;
}
/**
* Returns the total number of rows affected by this query.
*/
public function affectedRows(): int
{
return $this->connID->affected_rows ?? 0;
}
/**
* Platform-dependant string escape
*/
protected function _escapeString(string $str): string
{
if (! $this->connID) {
$this->initialize();
}
return $this->connID->real_escape_string($str);
}
/**
* Escape Like String Direct
* There are a few instances where MySQLi queries cannot take the
* additional "ESCAPE x" parameter for specifying the escape character
* in "LIKE" strings, and this handles those directly with a backslash.
*
* @param list<string>|string $str Input string
*
* @return list<string>|string
*/
public function escapeLikeStringDirect($str)
{
if (is_array($str)) {
foreach ($str as $key => $val) {
$str[$key] = $this->escapeLikeStringDirect($val);
}
return $str;
}
$str = $this->_escapeString($str);
// Escape LIKE condition wildcards
return str_replace(
[$this->likeEscapeChar, '%', '_'],
['\\' . $this->likeEscapeChar, '\\%', '\\_'],
$str,
);
}
/**
* Generates the SQL for listing tables in a platform-dependent manner.
* Uses escapeLikeStringDirect().
*
* @param string|null $tableName If $tableName is provided will return only this table if exists.
*/
protected function _listTables(bool $prefixLimit = false, ?string $tableName = null): string
{
$sql = 'SHOW TABLES FROM ' . $this->escapeIdentifier($this->database);
if ((string) $tableName !== '') {
return $sql . ' LIKE ' . $this->escape($tableName);
}
if ($prefixLimit && $this->DBPrefix !== '') {
return $sql . " LIKE '" . $this->escapeLikeStringDirect($this->DBPrefix) . "%'";
}
return $sql;
}
/**
* Generates a platform-specific query string so that the column names can be fetched.
*
* @param string|TableName $table
*/
protected function _listColumns($table = ''): string
{
$tableName = $this->protectIdentifiers(
$table,
true,
null,
false,
);
return 'SHOW COLUMNS FROM ' . $tableName;
}
/**
* Returns an array of objects with field data
*
* @return list<stdClass>
*
* @throws DatabaseException
*/
protected function _fieldData(string $table): array
{
$table = $this->protectIdentifiers($table, true, null, false);
if (($query = $this->query('SHOW COLUMNS FROM ' . $table)) === false) {
throw new DatabaseException(lang('Database.failGetFieldData'));
}
$query = $query->getResultObject();
$retVal = [];
for ($i = 0, $c = count($query); $i < $c; $i++) {
$retVal[$i] = new stdClass();
$retVal[$i]->name = $query[$i]->Field;
sscanf($query[$i]->Type, '%[a-z](%d)', $retVal[$i]->type, $retVal[$i]->max_length);
$retVal[$i]->nullable = $query[$i]->Null === 'YES';
$retVal[$i]->default = $query[$i]->Default;
$retVal[$i]->primary_key = (int) ($query[$i]->Key === 'PRI');
}
return $retVal;
}
/**
* Returns an array of objects with index data
*
* @return array<string, stdClass>
*
* @throws DatabaseException
* @throws LogicException
*/
protected function _indexData(string $table): array
{
$table = $this->protectIdentifiers($table, true, null, false);
if (($query = $this->query('SHOW INDEX FROM ' . $table)) === false) {
throw new DatabaseException(lang('Database.failGetIndexData'));
}
$indexes = $query->getResultArray();
if ($indexes === []) {
return [];
}
$keys = [];
foreach ($indexes as $index) {
if (empty($keys[$index['Key_name']])) {
$keys[$index['Key_name']] = new stdClass();
$keys[$index['Key_name']]->name = $index['Key_name'];
if ($index['Key_name'] === 'PRIMARY') {
$type = 'PRIMARY';
} elseif ($index['Index_type'] === 'FULLTEXT') {
$type = 'FULLTEXT';
} elseif ($index['Non_unique']) {
$type = $index['Index_type'] === 'SPATIAL' ? 'SPATIAL' : 'INDEX';
} else {
$type = 'UNIQUE';
}
$keys[$index['Key_name']]->type = $type;
}
$keys[$index['Key_name']]->fields[] = $index['Column_name'];
}
return $keys;
}
/**
* Returns an array of objects with Foreign key data
*
* @return array<string, stdClass>
*
* @throws DatabaseException
*/
protected function _foreignKeyData(string $table): array
{
$sql = '
SELECT
tc.CONSTRAINT_NAME,
tc.TABLE_NAME,
kcu.COLUMN_NAME,
rc.REFERENCED_TABLE_NAME,
kcu.REFERENCED_COLUMN_NAME,
rc.DELETE_RULE,
rc.UPDATE_RULE,
rc.MATCH_OPTION
FROM information_schema.table_constraints AS tc
INNER JOIN information_schema.referential_constraints AS rc
ON tc.constraint_name = rc.constraint_name
AND tc.constraint_schema = rc.constraint_schema
INNER JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
AND tc.constraint_schema = kcu.constraint_schema
WHERE
tc.constraint_type = ' . $this->escape('FOREIGN KEY') . ' AND
tc.table_schema = ' . $this->escape($this->database) . ' AND
tc.table_name = ' . $this->escape($table);
if (($query = $this->query($sql)) === false) {
throw new DatabaseException(lang('Database.failGetForeignKeyData'));
}
$query = $query->getResultObject();
$indexes = [];
foreach ($query as $row) {
$indexes[$row->CONSTRAINT_NAME]['constraint_name'] = $row->CONSTRAINT_NAME;
$indexes[$row->CONSTRAINT_NAME]['table_name'] = $row->TABLE_NAME;
$indexes[$row->CONSTRAINT_NAME]['column_name'][] = $row->COLUMN_NAME;
$indexes[$row->CONSTRAINT_NAME]['foreign_table_name'] = $row->REFERENCED_TABLE_NAME;
$indexes[$row->CONSTRAINT_NAME]['foreign_column_name'][] = $row->REFERENCED_COLUMN_NAME;
$indexes[$row->CONSTRAINT_NAME]['on_delete'] = $row->DELETE_RULE;
$indexes[$row->CONSTRAINT_NAME]['on_update'] = $row->UPDATE_RULE;
$indexes[$row->CONSTRAINT_NAME]['match'] = $row->MATCH_OPTION;
}
return $this->foreignKeyDataToObjects($indexes);
}
/**
* Returns platform-specific SQL to disable foreign key checks.
*
* @return string
*/
protected function _disableForeignKeyChecks()
{
return 'SET FOREIGN_KEY_CHECKS=0';
}
/**
* Returns platform-specific SQL to enable foreign key checks.
*
* @return string
*/
protected function _enableForeignKeyChecks()
{
return 'SET FOREIGN_KEY_CHECKS=1';
}
/**
* Returns the last error code and message.
* Must return this format: ['code' => string|int, 'message' => string]
* intval(code) === 0 means "no error".
*
* @return array<string, int|string>
*/
public function error(): array
{
if (! empty($this->mysqli->connect_errno)) {
return [
'code' => $this->mysqli->connect_errno,
'message' => $this->mysqli->connect_error,
];
}
return [
'code' => $this->connID->errno,
'message' => $this->connID->error,
];
}
/**
* Insert ID
*/
public function insertID(): int
{
return $this->connID->insert_id;
}
/**
* Begin Transaction
*/
protected function _transBegin(): bool
{
$this->connID->autocommit(false);
return $this->connID->begin_transaction();
}
/**
* Commit Transaction
*/
protected function _transCommit(): bool
{
if ($this->connID->commit()) {
$this->connID->autocommit(true);
return true;
}
return false;
}
/**
* Rollback Transaction
*/
protected function _transRollback(): bool
{
if ($this->connID->rollback()) {
$this->connID->autocommit(true);
return true;
}
return false;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/MySQLi/Result.php | system/Database/MySQLi/Result.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\Database\MySQLi;
use CodeIgniter\Database\BaseResult;
use CodeIgniter\Entity\Entity;
use mysqli;
use mysqli_result;
use stdClass;
/**
* Result for MySQLi
*
* @extends BaseResult<mysqli, mysqli_result>
*/
class Result extends BaseResult
{
/**
* Gets the number of fields in the result set.
*/
public function getFieldCount(): int
{
return $this->resultID->field_count;
}
/**
* Generates an array of column names in the result set.
*/
public function getFieldNames(): array
{
$fieldNames = [];
$this->resultID->field_seek(0);
while ($field = $this->resultID->fetch_field()) {
$fieldNames[] = $field->name;
}
return $fieldNames;
}
/**
* Generates an array of objects representing field meta-data.
*/
public function getFieldData(): array
{
static $dataTypes = [
MYSQLI_TYPE_DECIMAL => 'decimal',
MYSQLI_TYPE_NEWDECIMAL => 'newdecimal',
MYSQLI_TYPE_FLOAT => 'float',
MYSQLI_TYPE_DOUBLE => 'double',
MYSQLI_TYPE_BIT => 'bit',
MYSQLI_TYPE_SHORT => 'short',
MYSQLI_TYPE_LONG => 'long',
MYSQLI_TYPE_LONGLONG => 'longlong',
MYSQLI_TYPE_INT24 => 'int24',
MYSQLI_TYPE_YEAR => 'year',
MYSQLI_TYPE_TIMESTAMP => 'timestamp',
MYSQLI_TYPE_DATE => 'date',
MYSQLI_TYPE_TIME => 'time',
MYSQLI_TYPE_DATETIME => 'datetime',
MYSQLI_TYPE_NEWDATE => 'newdate',
MYSQLI_TYPE_SET => 'set',
MYSQLI_TYPE_VAR_STRING => 'var_string',
MYSQLI_TYPE_STRING => 'string',
MYSQLI_TYPE_GEOMETRY => 'geometry',
MYSQLI_TYPE_TINY_BLOB => 'tiny_blob',
MYSQLI_TYPE_MEDIUM_BLOB => 'medium_blob',
MYSQLI_TYPE_LONG_BLOB => 'long_blob',
MYSQLI_TYPE_BLOB => 'blob',
];
$retVal = [];
$fieldData = $this->resultID->fetch_fields();
foreach ($fieldData as $i => $data) {
$retVal[$i] = new stdClass();
$retVal[$i]->name = $data->name;
$retVal[$i]->type = $data->type;
$retVal[$i]->type_name = in_array($data->type, [1, 247], true) ? 'char' : ($dataTypes[$data->type] ?? null);
$retVal[$i]->max_length = $data->max_length;
$retVal[$i]->primary_key = $data->flags & 2;
$retVal[$i]->length = $data->length;
$retVal[$i]->default = $data->def;
}
return $retVal;
}
/**
* Frees the current result.
*
* @return void
*/
public function freeResult()
{
if (is_object($this->resultID)) {
$this->resultID->free();
$this->resultID = false;
}
}
/**
* Moves the internal pointer to the desired offset. This is called
* internally before fetching results to make sure the result set
* starts at zero.
*
* @return bool
*/
public function dataSeek(int $n = 0)
{
return $this->resultID->data_seek($n);
}
/**
* Returns the result set as an array.
*
* Overridden by driver classes.
*
* @return array|false|null
*/
protected function fetchAssoc()
{
return $this->resultID->fetch_assoc();
}
/**
* Returns the result set as an object.
*
* Overridden by child classes.
*
* @return Entity|false|object|stdClass
*/
protected function fetchObject(string $className = 'stdClass')
{
if (is_subclass_of($className, Entity::class)) {
return empty($data = $this->fetchAssoc()) ? false : (new $className())->injectRawData($data);
}
return $this->resultID->fetch_object($className);
}
/**
* Returns the number of rows in the resultID (i.e., mysqli_result object)
*/
public function getNumRows(): int
{
if (! is_int($this->numRows)) {
$this->numRows = $this->resultID->num_rows;
}
return $this->numRows;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/MySQLi/Builder.php | system/Database/MySQLi/Builder.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\Database\MySQLi;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\RawSql;
/**
* Builder for MySQLi
*/
class Builder extends BaseBuilder
{
/**
* Identifier escape character
*
* @var string
*/
protected $escapeChar = '`';
/**
* Specifies which sql statements
* support the ignore option.
*
* @var array<string, string>
*/
protected $supportedIgnoreStatements = [
'update' => 'IGNORE',
'insert' => 'IGNORE',
'delete' => 'IGNORE',
];
/**
* FROM tables
*
* Groups tables in FROM clauses if needed, so there is no confusion
* about operator precedence.
*
* Note: This is only used (and overridden) by MySQL.
*/
protected function _fromTables(): string
{
if ($this->QBJoin !== [] && count($this->QBFrom) > 1) {
return '(' . implode(', ', $this->QBFrom) . ')';
}
return implode(', ', $this->QBFrom);
}
/**
* Generates a platform-specific batch update string from the supplied data
*/
protected function _updateBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$constraints = $this->QBOptions['constraints'] ?? [];
if ($constraints === []) {
if ($this->db->DBDebug) {
throw new DatabaseException('You must specify a constraint to match on for batch updates.'); // @codeCoverageIgnore
}
return ''; // @codeCoverageIgnore
}
$updateFields = $this->QBOptions['updateFields'] ??
$this->updateFields($keys, false, $constraints)->QBOptions['updateFields'] ??
[];
$alias = $this->QBOptions['alias'] ?? '`_u`';
$sql = 'UPDATE ' . $this->compileIgnore('update') . $table . "\n";
$sql .= "INNER JOIN (\n{:_table_:}";
$sql .= ') ' . $alias . "\n";
$sql .= 'ON ' . implode(
' AND ',
array_map(
static fn ($key, $value) => (
($value instanceof RawSql && is_string($key))
?
$table . '.' . $key . ' = ' . $value
:
(
$value instanceof RawSql
?
$value
:
$table . '.' . $value . ' = ' . $alias . '.' . $value
)
),
array_keys($constraints),
$constraints,
),
) . "\n";
$sql .= "SET\n";
$sql .= implode(
",\n",
array_map(
static fn ($key, $value): string => $table . '.' . $key . ($value instanceof RawSql ?
' = ' . $value :
' = ' . $alias . '.' . $value),
array_keys($updateFields),
$updateFields,
),
);
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" UNION ALL\n",
array_map(
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index): string => $index . ' ' . $key,
$keys,
$value,
)),
$values,
),
) . "\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/MySQLi/PreparedQuery.php | system/Database/MySQLi/PreparedQuery.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\Database\MySQLi;
use CodeIgniter\Database\BasePreparedQuery;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Exceptions\BadMethodCallException;
use mysqli;
use mysqli_result;
use mysqli_sql_exception;
use mysqli_stmt;
/**
* Prepared query for MySQLi
*
* @extends BasePreparedQuery<mysqli, mysqli_stmt, mysqli_result>
*/
class PreparedQuery extends BasePreparedQuery
{
/**
* Prepares the query against the database, and saves the connection
* info necessary to execute the query later.
*
* NOTE: This version is based on SQL code. Child classes should
* override this method.
*
* @param array $options Passed to the connection's prepare statement.
* Unused in the MySQLi driver.
*/
public function _prepare(string $sql, array $options = []): PreparedQuery
{
// Mysqli driver doesn't like statements
// with terminating semicolons.
$sql = rtrim($sql, ';');
if (! $this->statement = $this->db->mysqli->prepare($sql)) {
$this->errorCode = $this->db->mysqli->errno;
$this->errorString = $this->db->mysqli->error;
if ($this->db->DBDebug) {
throw new DatabaseException($this->errorString . ' code: ' . $this->errorCode);
}
}
return $this;
}
/**
* Takes a new set of data and runs it against the currently
* prepared query. Upon success, will return a Results object.
*/
public function _execute(array $data): bool
{
if (! isset($this->statement)) {
throw new BadMethodCallException('You must call prepare before trying to execute a prepared statement.');
}
// First off - bind the parameters
$bindTypes = '';
$binaryData = [];
// Determine the type string
foreach ($data as $key => $item) {
if (is_int($item)) {
$bindTypes .= 'i';
} elseif (is_numeric($item)) {
$bindTypes .= 'd';
} elseif (is_string($item) && $this->isBinary($item)) {
$bindTypes .= 'b';
$binaryData[$key] = $item;
} else {
$bindTypes .= 's';
}
}
// Bind it
$this->statement->bind_param($bindTypes, ...$data);
// Stream binary data
foreach ($binaryData as $key => $value) {
$this->statement->send_long_data($key, $value);
}
try {
return $this->statement->execute();
} catch (mysqli_sql_exception $e) {
if ($this->db->DBDebug) {
throw new DatabaseException($e->getMessage(), $e->getCode(), $e);
}
return false;
}
}
/**
* Returns the result object for the prepared query or false on failure.
*
* @return false|mysqli_result
*/
public function _getResult()
{
return $this->statement->get_result();
}
/**
* Deallocate prepared statements.
*/
protected function _close(): bool
{
return $this->statement->close();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/MySQLi/Utils.php | system/Database/MySQLi/Utils.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\Database\MySQLi;
use CodeIgniter\Database\BaseUtils;
use CodeIgniter\Database\Exceptions\DatabaseException;
/**
* Utils for MySQLi
*/
class Utils extends BaseUtils
{
/**
* List databases statement
*
* @var string
*/
protected $listDatabases = 'SHOW DATABASES';
/**
* OPTIMIZE TABLE statement
*
* @var string
*/
protected $optimizeTable = 'OPTIMIZE TABLE %s';
/**
* Platform dependent version of the backup function.
*
* @return never
*/
public function _backup(?array $prefs = null)
{
throw new DatabaseException('Unsupported feature of the database platform you are using.');
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/MySQLi/Forge.php | system/Database/MySQLi/Forge.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\Database\MySQLi;
use CodeIgniter\Database\Forge as BaseForge;
/**
* Forge for MySQLi
*/
class Forge extends BaseForge
{
/**
* CREATE DATABASE statement
*
* @var string
*/
protected $createDatabaseStr = 'CREATE DATABASE %s CHARACTER SET %s COLLATE %s';
/**
* CREATE DATABASE IF statement
*
* @var string
*/
protected $createDatabaseIfStr = 'CREATE DATABASE IF NOT EXISTS %s CHARACTER SET %s COLLATE %s';
/**
* DROP CONSTRAINT statement
*
* @var string
*/
protected $dropConstraintStr = 'ALTER TABLE %s DROP FOREIGN KEY %s';
/**
* CREATE TABLE keys flag
*
* Whether table keys are created from within the
* CREATE TABLE statement.
*
* @var bool
*/
protected $createTableKeys = true;
/**
* UNSIGNED support
*
* @var array
*/
protected $_unsigned = [
'TINYINT',
'SMALLINT',
'MEDIUMINT',
'INT',
'INTEGER',
'BIGINT',
'REAL',
'DOUBLE',
'DOUBLE PRECISION',
'FLOAT',
'DECIMAL',
'NUMERIC',
];
/**
* Table Options list which required to be quoted
*
* @var array
*/
protected $_quoted_table_options = [
'COMMENT',
'COMPRESSION',
'CONNECTION',
'DATA DIRECTORY',
'INDEX DIRECTORY',
'ENCRYPTION',
'PASSWORD',
];
/**
* NULL value representation in CREATE/ALTER TABLE statements
*
* @var string
*
* @internal
*/
protected $null = 'NULL';
/**
* CREATE TABLE attributes
*
* @param array $attributes Associative array of table attributes
*/
protected function _createTableAttributes(array $attributes): string
{
$sql = '';
foreach (array_keys($attributes) as $key) {
if (is_string($key)) {
$sql .= ' ' . strtoupper($key) . ' = ';
if (in_array(strtoupper($key), $this->_quoted_table_options, true)) {
$sql .= $this->db->escape($attributes[$key]);
} else {
$sql .= $this->db->escapeString($attributes[$key]);
}
}
}
if ($this->db->charset !== '' && ! str_contains($sql, 'CHARACTER SET') && ! str_contains($sql, 'CHARSET')) {
$sql .= ' DEFAULT CHARACTER SET = ' . $this->db->escapeString($this->db->charset);
}
if ($this->db->DBCollat !== '' && ! str_contains($sql, 'COLLATE')) {
$sql .= ' COLLATE = ' . $this->db->escapeString($this->db->DBCollat);
}
return $sql;
}
/**
* ALTER TABLE
*
* @param string $alterType ALTER type
* @param string $table Table name
* @param array|string $processedFields Processed column definitions
* or column names to DROP
*
* @return ($alterType is 'DROP' ? string : list<string>)
*/
protected function _alterTable(string $alterType, string $table, $processedFields)
{
if ($alterType === 'DROP') {
return parent::_alterTable($alterType, $table, $processedFields);
}
$sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table);
foreach ($processedFields as $i => $field) {
if ($field['_literal'] !== false) {
$processedFields[$i] = ($alterType === 'ADD') ? "\n\tADD " . $field['_literal'] : "\n\tMODIFY " . $field['_literal'];
} else {
if ($alterType === 'ADD') {
$processedFields[$i]['_literal'] = "\n\tADD ";
} else {
$processedFields[$i]['_literal'] = empty($field['new_name']) ? "\n\tMODIFY " : "\n\tCHANGE ";
}
$processedFields[$i] = $processedFields[$i]['_literal'] . $this->_processColumn($processedFields[$i]);
}
}
return [$sql . implode(',', $processedFields)];
}
/**
* Process column
*/
protected function _processColumn(array $processedField): string
{
$extraClause = isset($processedField['after']) ? ' AFTER ' . $this->db->escapeIdentifiers($processedField['after']) : '';
if (empty($extraClause) && isset($processedField['first']) && $processedField['first'] === true) {
$extraClause = ' FIRST';
}
return $this->db->escapeIdentifiers($processedField['name'])
. (empty($processedField['new_name']) ? '' : ' ' . $this->db->escapeIdentifiers($processedField['new_name']))
. ' ' . $processedField['type'] . $processedField['length']
. $processedField['unsigned']
. $processedField['null']
. $processedField['default']
. $processedField['auto_increment']
. $processedField['unique']
. (empty($processedField['comment']) ? '' : ' COMMENT ' . $processedField['comment'])
. $extraClause;
}
/**
* Generates SQL to add indexes
*
* @param bool $asQuery When true returns stand alone SQL, else partial SQL used with CREATE TABLE
*/
protected function _processIndexes(string $table, bool $asQuery = false): array
{
$sqls = [''];
$index = 0;
for ($i = 0, $c = count($this->keys); $i < $c; $i++) {
$index = $i;
if ($asQuery === false) {
$index = 0;
}
if (isset($this->keys[$i]['fields'])) {
for ($i2 = 0, $c2 = count($this->keys[$i]['fields']); $i2 < $c2; $i2++) {
if (! isset($this->fields[$this->keys[$i]['fields'][$i2]])) {
unset($this->keys[$i]['fields'][$i2]);
continue;
}
}
}
if (! is_array($this->keys[$i]['fields'])) {
$this->keys[$i]['fields'] = [$this->keys[$i]['fields']];
}
$unique = in_array($i, $this->uniqueKeys, true) ? 'UNIQUE ' : '';
$keyName = $this->db->escapeIdentifiers(($this->keys[$i]['keyName'] === '') ?
implode('_', $this->keys[$i]['fields']) :
$this->keys[$i]['keyName']);
if ($asQuery) {
$sqls[$index] = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table) . " ADD {$unique}KEY "
. $keyName
. ' (' . implode(', ', $this->db->escapeIdentifiers($this->keys[$i]['fields'])) . ')';
} else {
$sqls[$index] .= ",\n\t{$unique}KEY " . $keyName
. ' (' . implode(', ', $this->db->escapeIdentifiers($this->keys[$i]['fields'])) . ')';
}
}
$this->keys = [];
return $sqls;
}
/**
* Drop Key
*/
public function dropKey(string $table, string $keyName, bool $prefixKeyName = true): bool
{
$sql = sprintf(
$this->dropIndexStr,
$this->db->escapeIdentifiers($keyName),
$this->db->escapeIdentifiers($this->db->DBPrefix . $table),
);
return $this->db->query($sql);
}
/**
* Drop Primary Key
*/
public function dropPrimaryKey(string $table, string $keyName = ''): bool
{
$sql = sprintf(
'ALTER TABLE %s DROP PRIMARY KEY',
$this->db->escapeIdentifiers($this->db->DBPrefix . $table),
);
return $this->db->query($sql);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/SQLSRV/Connection.php | system/Database/SQLSRV/Connection.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\Database\SQLSRV;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\TableName;
use stdClass;
/**
* Connection for SQLSRV
*
* @extends BaseConnection<resource, resource>
*/
class Connection extends BaseConnection
{
/**
* Database driver
*
* @var string
*/
public $DBDriver = 'SQLSRV';
/**
* Database name
*
* @var string
*/
public $database;
/**
* Scrollable flag
*
* Determines what cursor type to use when executing queries.
*
* FALSE or SQLSRV_CURSOR_FORWARD would increase performance,
* but would disable num_rows() (and possibly insert_id())
*
* @var false|string
*/
public $scrollable;
/**
* Identifier escape character
*
* @var string
*/
public $escapeChar = '"';
/**
* Database schema
*
* @var string
*/
public $schema = 'dbo';
/**
* Quoted identifier flag
*
* Whether to use SQL-92 standard quoted identifier
* (double quotes) or brackets for identifier escaping.
*
* @var bool
*/
protected $_quoted_identifier = true;
/**
* List of reserved identifiers
*
* Identifiers that must NOT be escaped.
*
* @var list<string>
*/
protected $_reserved_identifiers = ['*'];
/**
* Class constructor
*/
public function __construct(array $params)
{
parent::__construct($params);
// This is only supported as of SQLSRV 3.0
if ($this->scrollable === null) {
$this->scrollable = defined('SQLSRV_CURSOR_CLIENT_BUFFERED') ? SQLSRV_CURSOR_CLIENT_BUFFERED : false;
}
}
/**
* Connect to the database.
*
* @return false|resource
*
* @throws DatabaseException
*/
public function connect(bool $persistent = false)
{
$charset = in_array(strtolower($this->charset), ['utf-8', 'utf8'], true) ? 'UTF-8' : SQLSRV_ENC_CHAR;
$connection = [
'UID' => empty($this->username) ? '' : $this->username,
'PWD' => empty($this->password) ? '' : $this->password,
'Database' => $this->database,
'ConnectionPooling' => $persistent ? 1 : 0,
'CharacterSet' => $charset,
'Encrypt' => $this->encrypt === true ? 1 : 0,
'ReturnDatesAsStrings' => 1,
];
// If the username and password are both empty, assume this is a
// 'Windows Authentication Mode' connection.
if (empty($connection['UID']) && empty($connection['PWD'])) {
unset($connection['UID'], $connection['PWD']);
}
if (! str_contains($this->hostname, ',') && $this->port !== '') {
$this->hostname .= ', ' . $this->port;
}
sqlsrv_configure('WarningsReturnAsErrors', 0);
$this->connID = sqlsrv_connect($this->hostname, $connection);
if ($this->connID !== false) {
// Determine how identifiers are escaped
$query = $this->query('SELECT CASE WHEN (@@OPTIONS | 256) = @@OPTIONS THEN 1 ELSE 0 END AS qi');
$query = $query->getResultObject();
$this->_quoted_identifier = empty($query) ? false : (bool) $query[0]->qi;
$this->escapeChar = ($this->_quoted_identifier) ? '"' : ['[', ']'];
return $this->connID;
}
throw new DatabaseException($this->getAllErrorMessages());
}
/**
* For exception message
*
* @internal
*/
public function getAllErrorMessages(): string
{
$errors = [];
foreach (sqlsrv_errors() as $error) {
$errors[] = $error['message']
. ' SQLSTATE: ' . $error['SQLSTATE'] . ', code: ' . $error['code'];
}
return implode("\n", $errors);
}
/**
* Keep or establish the connection if no queries have been sent for
* a length of time exceeding the server's idle timeout.
*
* @return void
*/
public function reconnect()
{
$this->close();
$this->initialize();
}
/**
* Close the database connection.
*
* @return void
*/
protected function _close()
{
sqlsrv_close($this->connID);
}
/**
* Platform-dependant string escape
*/
protected function _escapeString(string $str): string
{
return str_replace("'", "''", remove_invisible_characters($str, false));
}
/**
* Insert ID
*/
public function insertID(): int
{
return (int) ($this->query('SELECT SCOPE_IDENTITY() AS insert_id')->getRow()->insert_id ?? 0);
}
/**
* Generates the SQL for listing tables in a platform-dependent manner.
*
* @param string|null $tableName If $tableName is provided will return only this table if exists.
*/
protected function _listTables(bool $prefixLimit = false, ?string $tableName = null): string
{
$sql = 'SELECT [TABLE_NAME] AS "name"'
. ' FROM [INFORMATION_SCHEMA].[TABLES] '
. ' WHERE '
. " [TABLE_SCHEMA] = '" . $this->schema . "' ";
if ($tableName !== null) {
return $sql .= ' AND [TABLE_NAME] LIKE ' . $this->escape($tableName);
}
if ($prefixLimit && $this->DBPrefix !== '') {
$sql .= " AND [TABLE_NAME] LIKE '" . $this->escapeLikeString($this->DBPrefix) . "%' "
. sprintf($this->likeEscapeStr, $this->likeEscapeChar);
}
return $sql;
}
/**
* Generates a platform-specific query string so that the column names can be fetched.
*
* @param string|TableName $table
*/
protected function _listColumns($table = ''): string
{
if ($table instanceof TableName) {
$tableName = $this->escape(strtolower($table->getActualTableName()));
} else {
$tableName = $this->escape($this->DBPrefix . strtolower($table));
}
return 'SELECT [COLUMN_NAME] '
. ' FROM [INFORMATION_SCHEMA].[COLUMNS]'
. ' WHERE [TABLE_NAME] = ' . $tableName
. ' AND [TABLE_SCHEMA] = ' . $this->escape($this->schema);
}
/**
* Returns an array of objects with index data
*
* @return array<string, stdClass>
*
* @throws DatabaseException
*/
protected function _indexData(string $table): array
{
$sql = 'EXEC sp_helpindex ' . $this->escape($this->schema . '.' . $table);
if (($query = $this->query($sql)) === false) {
throw new DatabaseException(lang('Database.failGetIndexData'));
}
$query = $query->getResultObject();
$retVal = [];
foreach ($query as $row) {
$obj = new stdClass();
$obj->name = $row->index_name;
$_fields = explode(',', trim($row->index_keys));
$obj->fields = array_map(static fn ($v): string => trim($v), $_fields);
if (str_contains($row->index_description, 'primary key located on')) {
$obj->type = 'PRIMARY';
} else {
$obj->type = (str_contains($row->index_description, 'nonclustered, unique')) ? 'UNIQUE' : 'INDEX';
}
$retVal[$obj->name] = $obj;
}
return $retVal;
}
/**
* Returns an array of objects with Foreign key data
* referenced_object_id parent_object_id
*
* @return array<string, stdClass>
*
* @throws DatabaseException
*/
protected function _foreignKeyData(string $table): array
{
$sql = 'SELECT
f.name as constraint_name,
OBJECT_NAME (f.parent_object_id) as table_name,
COL_NAME(fc.parent_object_id,fc.parent_column_id) column_name,
OBJECT_NAME(f.referenced_object_id) foreign_table_name,
COL_NAME(fc.referenced_object_id,fc.referenced_column_id) foreign_column_name,
rc.delete_rule,
rc.update_rule,
rc.match_option
FROM
sys.foreign_keys AS f
INNER JOIN sys.foreign_key_columns AS fc ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN sys.tables t ON t.OBJECT_ID = fc.referenced_object_id
INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc ON rc.CONSTRAINT_NAME = f.name
WHERE OBJECT_NAME (f.parent_object_id) = ' . $this->escape($table);
if (($query = $this->query($sql)) === false) {
throw new DatabaseException(lang('Database.failGetForeignKeyData'));
}
$query = $query->getResultObject();
$indexes = [];
foreach ($query as $row) {
$indexes[$row->constraint_name]['constraint_name'] = $row->constraint_name;
$indexes[$row->constraint_name]['table_name'] = $row->table_name;
$indexes[$row->constraint_name]['column_name'][] = $row->column_name;
$indexes[$row->constraint_name]['foreign_table_name'] = $row->foreign_table_name;
$indexes[$row->constraint_name]['foreign_column_name'][] = $row->foreign_column_name;
$indexes[$row->constraint_name]['on_delete'] = $row->delete_rule;
$indexes[$row->constraint_name]['on_update'] = $row->update_rule;
$indexes[$row->constraint_name]['match'] = $row->match_option;
}
return $this->foreignKeyDataToObjects($indexes);
}
/**
* Disables foreign key checks temporarily.
*
* @return string
*/
protected function _disableForeignKeyChecks()
{
return 'EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT ALL"';
}
/**
* Enables foreign key checks temporarily.
*
* @return string
*/
protected function _enableForeignKeyChecks()
{
return 'EXEC sp_MSforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT ALL"';
}
/**
* Returns an array of objects with field data
*
* @return list<stdClass>
*
* @throws DatabaseException
*/
protected function _fieldData(string $table): array
{
$sql = 'SELECT
COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, NUMERIC_PRECISION,
COLUMN_DEFAULT, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME= ' . $this->escape(($table));
if (($query = $this->query($sql)) === false) {
throw new DatabaseException(lang('Database.failGetFieldData'));
}
$query = $query->getResultObject();
$retVal = [];
for ($i = 0, $c = count($query); $i < $c; $i++) {
$retVal[$i] = new stdClass();
$retVal[$i]->name = $query[$i]->COLUMN_NAME;
$retVal[$i]->type = $query[$i]->DATA_TYPE;
$retVal[$i]->max_length = $query[$i]->CHARACTER_MAXIMUM_LENGTH > 0
? $query[$i]->CHARACTER_MAXIMUM_LENGTH
: (
$query[$i]->CHARACTER_MAXIMUM_LENGTH === -1
? 'max'
: $query[$i]->NUMERIC_PRECISION
);
$retVal[$i]->nullable = $query[$i]->IS_NULLABLE !== 'NO';
$retVal[$i]->default = $query[$i]->COLUMN_DEFAULT;
}
return $retVal;
}
/**
* Begin Transaction
*/
protected function _transBegin(): bool
{
return sqlsrv_begin_transaction($this->connID);
}
/**
* Commit Transaction
*/
protected function _transCommit(): bool
{
return sqlsrv_commit($this->connID);
}
/**
* Rollback Transaction
*/
protected function _transRollback(): bool
{
return sqlsrv_rollback($this->connID);
}
/**
* Returns the last error code and message.
* Must return this format: ['code' => string|int, 'message' => string]
* intval(code) === 0 means "no error".
*
* @return array<string, int|string>
*/
public function error(): array
{
$error = [
'code' => '00000',
'message' => '',
];
$sqlsrvErrors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
if (! is_array($sqlsrvErrors)) {
return $error;
}
$sqlsrvError = array_shift($sqlsrvErrors);
if (isset($sqlsrvError['SQLSTATE'])) {
$error['code'] = isset($sqlsrvError['code']) ? $sqlsrvError['SQLSTATE'] . '/' . $sqlsrvError['code'] : $sqlsrvError['SQLSTATE'];
} elseif (isset($sqlsrvError['code'])) {
$error['code'] = $sqlsrvError['code'];
}
if (isset($sqlsrvError['message'])) {
$error['message'] = $sqlsrvError['message'];
}
return $error;
}
/**
* Returns the total number of rows affected by this query.
*/
public function affectedRows(): int
{
if ($this->resultID === false) {
return 0;
}
return sqlsrv_rows_affected($this->resultID);
}
/**
* Select a specific database table to use.
*
* @return bool
*/
public function setDatabase(?string $databaseName = null)
{
if ($databaseName === null || $databaseName === '') {
$databaseName = $this->database;
}
if (empty($this->connID)) {
$this->initialize();
}
if ($this->execute('USE ' . $this->_escapeString($databaseName))) {
$this->database = $databaseName;
$this->dataCache = [];
return true;
}
return false;
}
/**
* Executes the query against the database.
*
* @return false|resource
*/
protected function execute(string $sql)
{
$stmt = ($this->scrollable === false || $this->isWriteType($sql)) ?
sqlsrv_query($this->connID, $sql) :
sqlsrv_query($this->connID, $sql, [], ['Scrollable' => $this->scrollable]);
if ($stmt === false) {
$error = $this->error();
log_message('error', $error['message']);
if ($this->DBDebug) {
throw new DatabaseException($error['message']);
}
}
return $stmt;
}
/**
* Returns the last error encountered by this connection.
*
* @return array<string, int|string>
*
* @deprecated Use `error()` instead.
*/
public function getError()
{
$error = [
'code' => '00000',
'message' => '',
];
$sqlsrvErrors = sqlsrv_errors(SQLSRV_ERR_ERRORS);
if (! is_array($sqlsrvErrors)) {
return $error;
}
$sqlsrvError = array_shift($sqlsrvErrors);
if (isset($sqlsrvError['SQLSTATE'])) {
$error['code'] = isset($sqlsrvError['code']) ? $sqlsrvError['SQLSTATE'] . '/' . $sqlsrvError['code'] : $sqlsrvError['SQLSTATE'];
} elseif (isset($sqlsrvError['code'])) {
$error['code'] = $sqlsrvError['code'];
}
if (isset($sqlsrvError['message'])) {
$error['message'] = $sqlsrvError['message'];
}
return $error;
}
/**
* The name of the platform in use (MySQLi, mssql, etc)
*/
public function getPlatform(): string
{
return $this->DBDriver;
}
/**
* Returns a string containing the version of the database being used.
*/
public function getVersion(): string
{
$info = [];
if (isset($this->dataCache['version'])) {
return $this->dataCache['version'];
}
if (! $this->connID) {
$this->initialize();
}
if (($info = sqlsrv_server_info($this->connID)) === []) {
return '';
}
return isset($info['SQLServerVersion']) ? $this->dataCache['version'] = $info['SQLServerVersion'] : '';
}
/**
* Determines if a query is a "write" type.
*
* Overrides BaseConnection::isWriteType, adding additional read query types.
*
* @param string $sql
*/
public function isWriteType($sql): bool
{
if (preg_match('/^\s*"?(EXEC\s*sp_rename)\s/i', $sql)) {
return true;
}
return parent::isWriteType($sql);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/SQLSRV/Result.php | system/Database/SQLSRV/Result.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\Database\SQLSRV;
use CodeIgniter\Database\BaseResult;
use CodeIgniter\Entity\Entity;
use stdClass;
/**
* Result for SQLSRV
*
* @extends BaseResult<resource, resource>
*/
class Result extends BaseResult
{
/**
* Gets the number of fields in the result set.
*/
public function getFieldCount(): int
{
return @sqlsrv_num_fields($this->resultID);
}
/**
* Generates an array of column names in the result set.
*/
public function getFieldNames(): array
{
$fieldNames = [];
foreach (sqlsrv_field_metadata($this->resultID) as $field) {
$fieldNames[] = $field['Name'];
}
return $fieldNames;
}
/**
* Generates an array of objects representing field meta-data.
*/
public function getFieldData(): array
{
static $dataTypes = [
SQLSRV_SQLTYPE_BIGINT => 'bigint',
SQLSRV_SQLTYPE_BIT => 'bit',
SQLSRV_SQLTYPE_CHAR => 'char',
SQLSRV_SQLTYPE_DATE => 'date',
SQLSRV_SQLTYPE_DATETIME => 'datetime',
SQLSRV_SQLTYPE_DATETIME2 => 'datetime2',
SQLSRV_SQLTYPE_DATETIMEOFFSET => 'datetimeoffset',
SQLSRV_SQLTYPE_DECIMAL => 'decimal',
SQLSRV_SQLTYPE_FLOAT => 'float',
SQLSRV_SQLTYPE_IMAGE => 'image',
SQLSRV_SQLTYPE_INT => 'int',
SQLSRV_SQLTYPE_MONEY => 'money',
SQLSRV_SQLTYPE_NCHAR => 'nchar',
SQLSRV_SQLTYPE_NUMERIC => 'numeric',
SQLSRV_SQLTYPE_NVARCHAR => 'nvarchar',
SQLSRV_SQLTYPE_NTEXT => 'ntext',
SQLSRV_SQLTYPE_REAL => 'real',
SQLSRV_SQLTYPE_SMALLDATETIME => 'smalldatetime',
SQLSRV_SQLTYPE_SMALLINT => 'smallint',
SQLSRV_SQLTYPE_SMALLMONEY => 'smallmoney',
SQLSRV_SQLTYPE_TEXT => 'text',
SQLSRV_SQLTYPE_TIME => 'time',
SQLSRV_SQLTYPE_TIMESTAMP => 'timestamp',
SQLSRV_SQLTYPE_TINYINT => 'tinyint',
SQLSRV_SQLTYPE_UNIQUEIDENTIFIER => 'uniqueidentifier',
SQLSRV_SQLTYPE_UDT => 'udt',
SQLSRV_SQLTYPE_VARBINARY => 'varbinary',
SQLSRV_SQLTYPE_VARCHAR => 'varchar',
SQLSRV_SQLTYPE_XML => 'xml',
];
$retVal = [];
foreach (sqlsrv_field_metadata($this->resultID) as $i => $field) {
$retVal[$i] = new stdClass();
$retVal[$i]->name = $field['Name'];
$retVal[$i]->type = $field['Type'];
$retVal[$i]->type_name = $dataTypes[$field['Type']] ?? null;
$retVal[$i]->max_length = $field['Size'];
}
return $retVal;
}
/**
* Frees the current result.
*
* @return void
*/
public function freeResult()
{
if (is_resource($this->resultID)) {
sqlsrv_free_stmt($this->resultID);
$this->resultID = false;
}
}
/**
* Moves the internal pointer to the desired offset. This is called
* internally before fetching results to make sure the result set
* starts at zero.
*
* @return bool
*/
public function dataSeek(int $n = 0)
{
if ($n > 0) {
for ($i = 0; $i < $n; $i++) {
if (sqlsrv_fetch($this->resultID) === false) {
return false;
}
}
}
return true;
}
/**
* Returns the result set as an array.
*
* Overridden by driver classes.
*
* @return array|false|null
*/
protected function fetchAssoc()
{
return sqlsrv_fetch_array($this->resultID, SQLSRV_FETCH_ASSOC);
}
/**
* Returns the result set as an object.
*
* @return Entity|false|object|stdClass
*/
protected function fetchObject(string $className = 'stdClass')
{
if (is_subclass_of($className, Entity::class)) {
return empty($data = $this->fetchAssoc()) ? false : (new $className())->injectRawData($data);
}
return sqlsrv_fetch_object($this->resultID, $className);
}
/**
* Returns the number of rows in the resultID (i.e., SQLSRV query result resource)
*/
public function getNumRows(): int
{
if (! is_int($this->numRows)) {
$this->numRows = sqlsrv_num_rows($this->resultID);
}
return $this->numRows;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/SQLSRV/Builder.php | system/Database/SQLSRV/Builder.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\Database\SQLSRV;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\Exceptions\DataException;
use CodeIgniter\Database\RawSql;
use CodeIgniter\Database\ResultInterface;
use Config\Feature;
/**
* Builder for SQLSRV
*
* @todo auto check for TextCastToInt
* @todo auto check for InsertIndexValue
* @todo replace: delete index entries before insert
*/
class Builder extends BaseBuilder
{
/**
* ORDER BY random keyword
*
* @var array
*/
protected $randomKeyword = [
'NEWID()',
'RAND(%d)',
];
/**
* Quoted identifier flag
*
* Whether to use SQL-92 standard quoted identifier
* (double quotes) or brackets for identifier escaping.
*
* @var bool
*/
protected $_quoted_identifier = true;
/**
* Handle increment/decrement on text
*
* @var bool
*/
public $castTextToInt = true;
/**
* Handle IDENTITY_INSERT property/
*
* @var bool
*/
public $keyPermission = false;
/**
* Groups tables in FROM clauses if needed, so there is no confusion
* about operator precedence.
*/
protected function _fromTables(): string
{
$from = [];
foreach ($this->QBFrom as $value) {
$from[] = str_starts_with($value, '(SELECT') ? $value : $this->getFullName($value);
}
return implode(', ', $from);
}
/**
* Generates a platform-specific truncate string from the supplied data
*
* If the database does not support the truncate() command,
* then this method maps to 'DELETE FROM table'
*/
protected function _truncate(string $table): string
{
return 'TRUNCATE TABLE ' . $this->getFullName($table);
}
/**
* Generates the JOIN portion of the query
*
* @param RawSql|string $cond
*
* @return $this
*/
public function join(string $table, $cond, string $type = '', ?bool $escape = null)
{
if ($type !== '') {
$type = strtoupper(trim($type));
if (! in_array($type, $this->joinTypes, true)) {
$type = '';
} else {
$type .= ' ';
}
}
// Extract any aliases that might exist. We use this information
// in the protectIdentifiers to know whether to add a table prefix
$this->trackAliases($table);
if (! is_bool($escape)) {
$escape = $this->db->protectIdentifiers;
}
if (! $this->hasOperator($cond)) {
$cond = ' USING (' . ($escape ? $this->db->escapeIdentifiers($cond) : $cond) . ')';
} elseif ($escape === false) {
$cond = ' ON ' . $cond;
} else {
// Split multiple conditions
if (preg_match_all('/\sAND\s|\sOR\s/i', $cond, $joints, PREG_OFFSET_CAPTURE) >= 1) {
$conditions = [];
$joints = $joints[0];
array_unshift($joints, ['', 0]);
for ($i = count($joints) - 1, $pos = strlen($cond); $i >= 0; $i--) {
$joints[$i][1] += strlen($joints[$i][0]); // offset
$conditions[$i] = substr($cond, $joints[$i][1], $pos - $joints[$i][1]);
$pos = $joints[$i][1] - strlen($joints[$i][0]);
$joints[$i] = $joints[$i][0];
}
ksort($conditions);
} else {
$conditions = [$cond];
$joints = [''];
}
$cond = ' ON ';
foreach ($conditions as $i => $condition) {
$operator = $this->getOperator($condition);
// Workaround for BETWEEN
if ($operator === false) {
$cond .= $joints[$i] . $condition;
continue;
}
$cond .= $joints[$i];
$cond .= preg_match('/(\(*)?([\[\]\w\.\'-]+)' . preg_quote($operator, '/') . '(.*)/i', $condition, $match) ? $match[1] . $this->db->protectIdentifiers($match[2]) . $operator . $this->db->protectIdentifiers($match[3]) : $condition;
}
}
// Do we want to escape the table name?
if ($escape === true) {
$table = $this->db->protectIdentifiers($table, true, null, false);
}
// Assemble the JOIN statement
$this->QBJoin[] = $type . 'JOIN ' . $this->getFullName($table) . $cond;
return $this;
}
/**
* Generates a platform-specific insert string from the supplied data
*
* @todo implement check for this instead static $insertKeyPermission
*/
protected function _insert(string $table, array $keys, array $unescapedKeys): string
{
$fullTableName = $this->getFullName($table);
// insert statement
$statement = 'INSERT INTO ' . $fullTableName . ' (' . implode(',', $keys) . ') VALUES (' . implode(', ', $unescapedKeys) . ')';
return $this->keyPermission ? $this->addIdentity($fullTableName, $statement) : $statement;
}
/**
* Insert batch statement
*
* Generates a platform-specific insert string from the supplied data.
*/
protected function _insertBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$sql = 'INSERT ' . $this->compileIgnore('insert') . 'INTO ' . $this->getFullName($table)
. ' (' . implode(', ', $keys) . ")\n{:_table_:}";
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = 'VALUES ' . implode(', ', $this->formatValues($values));
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Generates a platform-specific update string from the supplied data
*/
protected function _update(string $table, array $values): string
{
$valstr = [];
foreach ($values as $key => $val) {
$valstr[] = $key . ' = ' . $val;
}
$fullTableName = $this->getFullName($table);
$statement = sprintf('UPDATE %s%s SET ', empty($this->QBLimit) ? '' : 'TOP(' . $this->QBLimit . ') ', $fullTableName);
$statement .= implode(', ', $valstr)
. $this->compileWhereHaving('QBWhere')
. $this->compileOrderBy();
return $this->keyPermission ? $this->addIdentity($fullTableName, $statement) : $statement;
}
/**
* Increments a numeric column by the specified value.
*
* @return bool
*/
public function increment(string $column, int $value = 1)
{
$column = $this->db->protectIdentifiers($column);
if ($this->castTextToInt) {
$values = [$column => "CONVERT(VARCHAR(MAX),CONVERT(INT,CONVERT(VARCHAR(MAX), {$column})) + {$value})"];
} else {
$values = [$column => "{$column} + {$value}"];
}
$sql = $this->_update($this->QBFrom[0], $values);
if (! $this->testMode) {
$this->resetWrite();
return $this->db->query($sql, $this->binds, false);
}
return true;
}
/**
* Decrements a numeric column by the specified value.
*
* @return bool
*/
public function decrement(string $column, int $value = 1)
{
$column = $this->db->protectIdentifiers($column);
if ($this->castTextToInt) {
$values = [$column => "CONVERT(VARCHAR(MAX),CONVERT(INT,CONVERT(VARCHAR(MAX), {$column})) - {$value})"];
} else {
$values = [$column => "{$column} + {$value}"];
}
$sql = $this->_update($this->QBFrom[0], $values);
if (! $this->testMode) {
$this->resetWrite();
return $this->db->query($sql, $this->binds, false);
}
return true;
}
/**
* Get full name of the table
*/
private function getFullName(string $table): string
{
$alias = '';
if (str_contains($table, ' ')) {
$alias = explode(' ', $table);
$table = array_shift($alias);
$alias = ' ' . implode(' ', $alias);
}
if ($this->db->escapeChar === '"') {
if (str_contains($table, '.') && ! str_starts_with($table, '.') && ! str_ends_with($table, '.')) {
$dbInfo = explode('.', $table);
$database = $this->db->getDatabase();
$table = $dbInfo[0];
if (count($dbInfo) === 3) {
$database = str_replace('"', '', $dbInfo[0]);
$schema = str_replace('"', '', $dbInfo[1]);
$tableName = str_replace('"', '', $dbInfo[2]);
} else {
$schema = str_replace('"', '', $dbInfo[0]);
$tableName = str_replace('"', '', $dbInfo[1]);
}
return '"' . $database . '"."' . $schema . '"."' . str_replace('"', '', $tableName) . '"' . $alias;
}
return '"' . $this->db->getDatabase() . '"."' . $this->db->schema . '"."' . str_replace('"', '', $table) . '"' . $alias;
}
return '[' . $this->db->getDatabase() . '].[' . $this->db->schema . '].[' . str_replace('"', '', $table) . ']' . str_replace('"', '', $alias);
}
/**
* Add permision statements for index value inserts
*/
private function addIdentity(string $fullTable, string $insert): string
{
return 'SET IDENTITY_INSERT ' . $fullTable . " ON\n" . $insert . "\nSET IDENTITY_INSERT " . $fullTable . ' OFF';
}
/**
* Local implementation of limit
*/
protected function _limit(string $sql, bool $offsetIgnore = false): string
{
// SQL Server cannot handle `LIMIT 0`.
// DatabaseException:
// [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The number of
// rows provided for a FETCH clause must be greater then zero.
$limitZeroAsAll = config(Feature::class)->limitZeroAsAll ?? true;
if (! $limitZeroAsAll && $this->QBLimit === 0) {
return "SELECT * \nFROM " . $this->_fromTables() . ' WHERE 1=0 ';
}
if (empty($this->QBOrderBy)) {
$sql .= ' ORDER BY (SELECT NULL) ';
}
if ($offsetIgnore) {
$sql .= ' OFFSET 0 ';
} else {
$sql .= is_int($this->QBOffset) ? ' OFFSET ' . $this->QBOffset : ' OFFSET 0 ';
}
return $sql . ' ROWS FETCH NEXT ' . $this->QBLimit . ' ROWS ONLY ';
}
/**
* Compiles a replace into string and runs the query
*
* @return mixed
*
* @throws DatabaseException
*/
public function replace(?array $set = null)
{
if ($set !== null) {
$this->set($set);
}
if ($this->QBSet === []) {
if ($this->db->DBDebug) {
throw new DatabaseException('You must use the "set" method to update an entry.');
}
return false; // @codeCoverageIgnore
}
$table = $this->QBFrom[0];
$sql = $this->_replace($table, array_keys($this->QBSet), array_values($this->QBSet));
$this->resetWrite();
if ($this->testMode) {
return $sql;
}
$this->db->simpleQuery('SET IDENTITY_INSERT ' . $this->getFullName($table) . ' ON');
$result = $this->db->query($sql, $this->binds, false);
$this->db->simpleQuery('SET IDENTITY_INSERT ' . $this->getFullName($table) . ' OFF');
return $result;
}
/**
* Generates a platform-specific replace string from the supplied data
* on match delete and insert
*/
protected function _replace(string $table, array $keys, array $values): string
{
// check whether the existing keys are part of the primary key.
// if so then use them for the "ON" part and exclude them from the $values and $keys
$pKeys = $this->db->getIndexData($table);
$keyFields = [];
foreach ($pKeys as $key) {
if ($key->type === 'PRIMARY') {
$keyFields = array_merge($keyFields, $key->fields);
}
if ($key->type === 'UNIQUE') {
$keyFields = array_merge($keyFields, $key->fields);
}
}
// Get the unique field names
$escKeyFields = array_map(fn (string $field): string => $this->db->protectIdentifiers($field), array_values(array_unique($keyFields)));
// Get the binds
$binds = $this->binds;
array_walk($binds, static function (&$item): void {
$item = $item[0];
});
// Get the common field and values from the keys data and index fields
$common = array_intersect($keys, $escKeyFields);
$bingo = [];
foreach ($common as $v) {
$k = array_search($v, $keys, true);
$bingo[$keys[$k]] = $binds[trim($values[$k], ':')];
}
// Querying existing data
$builder = $this->db->table($table);
foreach ($bingo as $k => $v) {
$builder->where($k, $v);
}
$q = $builder->get()->getResult();
// Delete entries if we find them
if ($q !== []) {
$delete = $this->db->table($table);
foreach ($bingo as $k => $v) {
$delete->where($k, $v);
}
$delete->delete();
}
return sprintf('INSERT INTO %s (%s) VALUES (%s);', $this->getFullName($table), implode(',', $keys), implode(',', $values));
}
/**
* SELECT [MAX|MIN|AVG|SUM|COUNT]()
*
* Handle float return value
*
* @return BaseBuilder
*/
protected function maxMinAvgSum(string $select = '', string $alias = '', string $type = 'MAX')
{
// int functions can be handled by parent
if ($type !== 'AVG') {
return parent::maxMinAvgSum($select, $alias, $type);
}
if ($select === '') {
throw DataException::forEmptyInputGiven('Select');
}
if (str_contains($select, ',')) {
throw DataException::forInvalidArgument('Column name not separated by comma');
}
if ($alias === '') {
$alias = $this->createAliasFromTable(trim($select));
}
$sql = $type . '( CAST( ' . $this->db->protectIdentifiers(trim($select)) . ' AS FLOAT ) ) AS ' . $this->db->escapeIdentifiers(trim($alias));
$this->QBSelect[] = $sql;
$this->QBNoEscape[] = null;
return $this;
}
/**
* "Count All" query
*
* Generates a platform-specific query string that counts all records in
* the particular table
*
* @param bool $reset Are we want to clear query builder values?
*
* @return int|string when $test = true
*/
public function countAll(bool $reset = true)
{
$table = $this->QBFrom[0];
$sql = $this->countString . $this->db->escapeIdentifiers('numrows') . ' FROM ' . $this->getFullName($table);
if ($this->testMode) {
return $sql;
}
$query = $this->db->query($sql, null, false);
if (empty($query->getResult())) {
return 0;
}
$query = $query->getRow();
if ($reset) {
$this->resetSelect();
}
return (int) $query->numrows;
}
/**
* Delete statement
*/
protected function _delete(string $table): string
{
return 'DELETE' . (empty($this->QBLimit) ? '' : ' TOP (' . $this->QBLimit . ') ') . ' FROM ' . $this->getFullName($table) . $this->compileWhereHaving('QBWhere');
}
/**
* Compiles a delete string and runs the query
*
* @param mixed $where
*
* @return mixed
*
* @throws DatabaseException
*/
public function delete($where = '', ?int $limit = null, bool $resetData = true)
{
$table = $this->db->protectIdentifiers($this->QBFrom[0], true, null, false);
if ($where !== '') {
$this->where($where);
}
if ($this->QBWhere === []) {
if ($this->db->DBDebug) {
throw new DatabaseException('Deletes are not allowed unless they contain a "where" or "like" clause.');
}
return false; // @codeCoverageIgnore
}
if ($limit !== null && $limit !== 0) {
$this->QBLimit = $limit;
}
$sql = $this->_delete($table);
if ($resetData) {
$this->resetWrite();
}
return $this->testMode ? $sql : $this->db->query($sql, $this->binds, false);
}
/**
* Compile the SELECT statement
*
* Generates a query string based on which functions were used.
*
* @param bool $selectOverride
*/
protected function compileSelect($selectOverride = false): string
{
// Write the "select" portion of the query
if ($selectOverride !== false) {
$sql = $selectOverride;
} else {
$sql = (! $this->QBDistinct) ? 'SELECT ' : 'SELECT DISTINCT ';
// SQL Server can't work with select * if group by is specified
if (empty($this->QBSelect) && $this->QBGroupBy !== [] && is_array($this->QBGroupBy)) {
foreach ($this->QBGroupBy as $field) {
$this->QBSelect[] = is_array($field) ? $field['field'] : $field;
}
}
if (empty($this->QBSelect)) {
$sql .= '*';
} else {
// Cycle through the "select" portion of the query and prep each column name.
// The reason we protect identifiers here rather than in the select() function
// is because until the user calls the from() function we don't know if there are aliases
foreach ($this->QBSelect as $key => $val) {
$noEscape = $this->QBNoEscape[$key] ?? null;
$this->QBSelect[$key] = $this->db->protectIdentifiers($val, false, $noEscape);
}
$sql .= implode(', ', $this->QBSelect);
}
}
// Write the "FROM" portion of the query
if ($this->QBFrom !== []) {
$sql .= "\nFROM " . $this->_fromTables();
}
// Write the "JOIN" portion of the query
if (! empty($this->QBJoin)) {
$sql .= "\n" . implode("\n", $this->QBJoin);
}
$sql .= $this->compileWhereHaving('QBWhere')
. $this->compileGroupBy()
. $this->compileWhereHaving('QBHaving')
. $this->compileOrderBy(); // ORDER BY
// LIMIT
$limitZeroAsAll = config(Feature::class)->limitZeroAsAll ?? true;
if ($limitZeroAsAll) {
if ($this->QBLimit) {
$sql = $this->_limit($sql . "\n");
}
} elseif ($this->QBLimit !== false || $this->QBOffset) {
$sql = $this->_limit($sql . "\n");
}
return $this->unionInjection($sql);
}
/**
* Compiles the select statement based on the other functions called
* and runs the query
*
* @return ResultInterface
*/
public function get(?int $limit = null, int $offset = 0, bool $reset = true)
{
$limitZeroAsAll = config(Feature::class)->limitZeroAsAll ?? true;
if ($limitZeroAsAll && $limit === 0) {
$limit = null;
}
if ($limit !== null) {
$this->limit($limit, $offset);
}
$result = $this->testMode ? $this->getCompiledSelect($reset) : $this->db->query($this->compileSelect(), $this->binds, false);
if ($reset) {
$this->resetSelect();
// Clear our binds so we don't eat up memory
$this->binds = [];
}
return $result;
}
/**
* Generates a platform-specific upsertBatch string from the supplied data
*
* @throws DatabaseException
*/
protected function _upsertBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$fullTableName = $this->getFullName($table);
$constraints = $this->QBOptions['constraints'] ?? [];
$tableIdentity = $this->QBOptions['tableIdentity'] ?? '';
$sql = "SELECT name from syscolumns where id = Object_ID('" . $table . "') and colstat = 1";
if (($query = $this->db->query($sql)) === false) {
throw new DatabaseException('Failed to get table identity');
}
$query = $query->getResultObject();
foreach ($query as $row) {
$tableIdentity = '"' . $row->name . '"';
}
$this->QBOptions['tableIdentity'] = $tableIdentity;
$identityInFields = in_array($tableIdentity, $keys, true);
$fieldNames = array_map(static fn ($columnName): string => trim($columnName, '"'), $keys);
if (empty($constraints)) {
$tableIndexes = $this->db->getIndexData($table);
$uniqueIndexes = array_filter($tableIndexes, static function ($index) use ($fieldNames): bool {
$hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields);
return $index->type === 'PRIMARY' && $hasAllFields;
});
// if no primary found then look for unique - since indexes have no order
if ($uniqueIndexes === []) {
$uniqueIndexes = array_filter($tableIndexes, static function ($index) use ($fieldNames): bool {
$hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields);
return $index->type === 'UNIQUE' && $hasAllFields;
});
}
// only take first index
foreach ($uniqueIndexes as $index) {
$constraints = $index->fields;
break;
}
$constraints = $this->onConstraint($constraints)->QBOptions['constraints'] ?? [];
}
if (empty($constraints)) {
if ($this->db->DBDebug) {
throw new DatabaseException('No constraint found for upsert.');
}
return ''; // @codeCoverageIgnore
}
$alias = $this->QBOptions['alias'] ?? '"_upsert"';
$updateFields = $this->QBOptions['updateFields'] ?? $this->updateFields($keys, false, $constraints)->QBOptions['updateFields'] ?? [];
$sql = 'MERGE INTO ' . $fullTableName . "\nUSING (\n";
$sql .= '{:_table_:}';
$sql .= ") {$alias} (";
$sql .= implode(', ', $keys);
$sql .= ')';
$sql .= "\nON (";
$sql .= implode(
' AND ',
array_map(
static fn ($key, $value) => (
($value instanceof RawSql && is_string($key))
?
$fullTableName . '.' . $key . ' = ' . $value
:
(
$value instanceof RawSql
?
$value
:
$fullTableName . '.' . $value . ' = ' . $alias . '.' . $value
)
),
array_keys($constraints),
$constraints,
),
) . ")\n";
$sql .= "WHEN MATCHED THEN UPDATE SET\n";
$sql .= implode(
",\n",
array_map(
static fn ($key, $value): string => $key . ($value instanceof RawSql ?
' = ' . $value :
" = {$alias}.{$value}"),
array_keys($updateFields),
$updateFields,
),
);
$sql .= "\nWHEN NOT MATCHED THEN INSERT (" . implode(', ', $keys) . ")\nVALUES ";
$sql .= (
'(' . implode(
', ',
array_map(
static fn ($columnName): string => $columnName === $tableIdentity
? "CASE WHEN {$alias}.{$columnName} IS NULL THEN (SELECT "
. 'isnull(IDENT_CURRENT(\'' . $fullTableName . '\')+IDENT_INCR(\''
. $fullTableName . "'),1)) ELSE {$alias}.{$columnName} END"
: "{$alias}.{$columnName}",
$keys,
),
) . ');'
);
$sql = $identityInFields ? $this->addIdentity($fullTableName, $sql) : $sql;
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = 'VALUES ' . implode(', ', $this->formatValues($values)) . "\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Gets column names from a select query
*/
protected function fieldsFromQuery(string $sql): array
{
return $this->db->query('SELECT TOP 1 * FROM (' . $sql . ') _u_')->getFieldNames();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/SQLSRV/PreparedQuery.php | system/Database/SQLSRV/PreparedQuery.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\Database\SQLSRV;
use CodeIgniter\Database\BasePreparedQuery;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Exceptions\BadMethodCallException;
/**
* Prepared query for Postgre
*
* @extends BasePreparedQuery<resource, resource, resource>
*/
class PreparedQuery extends BasePreparedQuery
{
/**
* Parameters array used to store the dynamic variables.
*
* @var array
*/
protected $parameters = [];
/**
* A reference to the db connection to use.
*
* @var Connection
*/
protected $db;
public function __construct(Connection $db)
{
parent::__construct($db);
}
/**
* Prepares the query against the database, and saves the connection
* info necessary to execute the query later.
*
* NOTE: This version is based on SQL code. Child classes should
* override this method.
*
* @param array $options Options takes an associative array;
*
* @throws DatabaseException
*/
public function _prepare(string $sql, array $options = []): PreparedQuery
{
// Prepare parameters for the query
$queryString = $this->getQueryString();
$parameters = $this->parameterize($queryString, $options);
// Prepare the query
$this->statement = sqlsrv_prepare($this->db->connID, $sql, $parameters);
if (! $this->statement) {
if ($this->db->DBDebug) {
throw new DatabaseException($this->db->getAllErrorMessages());
}
$info = $this->db->error();
$this->errorCode = $info['code'];
$this->errorString = $info['message'];
}
return $this;
}
/**
* Takes a new set of data and runs it against the currently
* prepared query.
*/
public function _execute(array $data): bool
{
if (! isset($this->statement)) {
throw new BadMethodCallException('You must call prepare before trying to execute a prepared statement.');
}
foreach ($data as $key => $value) {
$this->parameters[$key] = $value;
}
$result = sqlsrv_execute($this->statement);
if ($result === false && $this->db->DBDebug) {
throw new DatabaseException($this->db->getAllErrorMessages());
}
return $result;
}
/**
* Returns the statement resource for the prepared query or false when preparing failed.
*
* @return resource|null
*/
public function _getResult()
{
return $this->statement;
}
/**
* Deallocate prepared statements.
*/
protected function _close(): bool
{
return sqlsrv_free_stmt($this->statement);
}
/**
* Handle parameters.
*
* @param array<int, mixed> $options
*/
protected function parameterize(string $queryString, array $options): array
{
$numberOfVariables = substr_count($queryString, '?');
$params = [];
for ($c = 0; $c < $numberOfVariables; $c++) {
$this->parameters[$c] = null;
if (isset($options[$c])) {
$params[] = [&$this->parameters[$c], SQLSRV_PARAM_IN, $options[$c]];
} else {
$params[] = &$this->parameters[$c];
}
}
return $params;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/SQLSRV/Utils.php | system/Database/SQLSRV/Utils.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\Database\SQLSRV;
use CodeIgniter\Database\BaseUtils;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Database\Exceptions\DatabaseException;
/**
* Utils for SQLSRV
*/
class Utils extends BaseUtils
{
/**
* List databases statement
*
* @var string
*/
protected $listDatabases = 'EXEC sp_helpdb'; // Can also be: EXEC sp_databases
/**
* OPTIMIZE TABLE statement
*
* @var string
*/
protected $optimizeTable = 'ALTER INDEX all ON %s REORGANIZE';
public function __construct(ConnectionInterface $db)
{
parent::__construct($db);
$this->optimizeTable = 'ALTER INDEX all ON ' . $this->db->schema . '.%s REORGANIZE';
}
/**
* Platform dependent version of the backup function.
*
* @return never
*/
public function _backup(?array $prefs = null)
{
throw new DatabaseException('Unsupported feature of the database platform you are using.');
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/SQLSRV/Forge.php | system/Database/SQLSRV/Forge.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\Database\SQLSRV;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\Forge as BaseForge;
use Throwable;
/**
* Forge for SQLSRV
*/
class Forge extends BaseForge
{
/**
* DROP CONSTRAINT statement
*
* @var string
*/
protected $dropConstraintStr;
/**
* DROP INDEX statement
*
* @var string
*/
protected $dropIndexStr;
/**
* CREATE DATABASE IF statement
*
* @todo missing charset, collat & check for existent
*
* @var string
*/
protected $createDatabaseIfStr = "DECLARE @DBName VARCHAR(255) = '%s'\nDECLARE @SQL VARCHAR(max) = 'IF DB_ID( ''' + @DBName + ''' ) IS NULL CREATE DATABASE %s'\nEXEC( @SQL )";
/**
* CREATE DATABASE IF statement
*
* @todo missing charset & collat
*
* @var string
*/
protected $createDatabaseStr = 'CREATE DATABASE %s ';
/**
* CHECK DATABASE EXIST statement
*
* @var string
*/
protected $checkDatabaseExistStr = 'IF DB_ID( %s ) IS NOT NULL SELECT 1';
/**
* RENAME TABLE statement
*
* While the below statement would work, it returns an error.
* Also MS recommends dropping and dropping and re-creating the table.
*
* @see https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-rename-transact-sql?view=sql-server-2017
* 'EXEC sp_rename %s , %s ;'
*
* @var string
*/
protected $renameTableStr;
/**
* UNSIGNED support
*
* @var array
*/
protected $unsigned = [
'TINYINT' => 'SMALLINT',
'SMALLINT' => 'INT',
'INT' => 'BIGINT',
'REAL' => 'FLOAT',
];
/**
* Foreign Key Allowed Actions
*
* @var array
*/
protected $fkAllowActions = ['CASCADE', 'SET NULL', 'NO ACTION', 'RESTRICT', 'SET DEFAULT'];
/**
* CREATE TABLE IF statement
*
* @var string
*
* @deprecated This is no longer used.
*/
protected $createTableIfStr;
/**
* CREATE TABLE statement
*
* @var string
*/
protected $createTableStr;
public function __construct(BaseConnection $db)
{
parent::__construct($db);
$this->createTableStr = '%s ' . $this->db->escapeIdentifiers($this->db->schema) . ".%s (%s\n) ";
$this->renameTableStr = 'EXEC sp_rename [' . $this->db->escapeIdentifiers($this->db->schema) . '.%s] , %s ;';
$this->dropConstraintStr = 'ALTER TABLE ' . $this->db->escapeIdentifiers($this->db->schema) . '.%s DROP CONSTRAINT %s';
$this->dropIndexStr = 'DROP INDEX %s ON ' . $this->db->escapeIdentifiers($this->db->schema) . '.%s';
}
/**
* Create database
*
* @param bool $ifNotExists Whether to add IF NOT EXISTS condition
*
* @throws DatabaseException
*/
public function createDatabase(string $dbName, bool $ifNotExists = false): bool
{
if ($ifNotExists) {
$sql = sprintf(
$this->createDatabaseIfStr,
$dbName,
$this->db->escapeIdentifier($dbName),
);
} else {
$sql = sprintf(
$this->createDatabaseStr,
$this->db->escapeIdentifier($dbName),
);
}
try {
if (! $this->db->query($sql)) {
// @codeCoverageIgnoreStart
if ($this->db->DBDebug) {
throw new DatabaseException('Unable to create the specified database.');
}
return false;
// @codeCoverageIgnoreEnd
}
if (isset($this->db->dataCache['db_names'])) {
$this->db->dataCache['db_names'][] = $dbName;
}
return true;
} catch (Throwable $e) {
if ($this->db->DBDebug) {
throw new DatabaseException('Unable to create the specified database.', 0, $e);
}
return false; // @codeCoverageIgnore
}
}
/**
* CREATE TABLE attributes
*/
protected function _createTableAttributes(array $attributes): string
{
return '';
}
/**
* @param array|string $processedFields Processed column definitions
* or column names to DROP
*
* @return ($alterType is 'DROP' ? string : false|list<string>)
*/
protected function _alterTable(string $alterType, string $table, $processedFields)
{
// Handle DROP here
if ($alterType === 'DROP') {
$columnNamesToDrop = $processedFields;
// check if fields are part of any indexes
$indexData = $this->db->getIndexData($table);
foreach ($indexData as $index) {
if (is_string($columnNamesToDrop)) {
$columnNamesToDrop = explode(',', $columnNamesToDrop);
}
$fld = array_intersect($columnNamesToDrop, $index->fields);
// Drop index if field is part of an index
if ($fld !== []) {
$this->_dropIndex($table, $index);
}
}
$fullTable = $this->db->escapeIdentifiers($this->db->schema) . '.' . $this->db->escapeIdentifiers($table);
// Drop default constraints
$fields = implode(',', $this->db->escape((array) $columnNamesToDrop));
$sql = <<<SQL
SELECT name
FROM sys.default_constraints
WHERE parent_object_id = OBJECT_ID('{$fullTable}')
AND parent_column_id IN (
SELECT column_id FROM sys.columns WHERE name IN ({$fields}) AND object_id = OBJECT_ID(N'{$fullTable}')
)
SQL;
foreach ($this->db->query($sql)->getResultArray() as $index) {
$this->db->query('ALTER TABLE ' . $fullTable . ' DROP CONSTRAINT ' . $index['name'] . '');
}
$sql = 'ALTER TABLE ' . $fullTable . ' DROP ';
$fields = array_map(static fn ($item): string => 'COLUMN [' . trim($item) . ']', (array) $columnNamesToDrop);
return $sql . implode(',', $fields);
}
$sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($this->db->schema) . '.' . $this->db->escapeIdentifiers($table);
$sql .= ($alterType === 'ADD') ? 'ADD ' : ' ';
$sqls = [];
if ($alterType === 'ADD') {
foreach ($processedFields as $field) {
$sqls[] = $sql . ($field['_literal'] !== false ? $field['_literal'] : $this->_processColumn($field));
}
return $sqls;
}
foreach ($processedFields as $field) {
if ($field['_literal'] !== false) {
return false;
}
if (isset($field['type'])) {
$sqls[] = $sql . ' ALTER COLUMN ' . $this->db->escapeIdentifiers($field['name'])
. " {$field['type']}{$field['length']}";
}
if (! empty($field['default'])) {
$sqls[] = $sql . ' ALTER COLUMN ADD CONSTRAINT ' . $this->db->escapeIdentifiers($field['name']) . '_def'
. " DEFAULT {$field['default']} FOR " . $this->db->escapeIdentifiers($field['name']);
}
$nullable = true; // Nullable by default.
if (isset($field['null']) && ($field['null'] === false || $field['null'] === ' NOT ' . $this->null)) {
$nullable = false;
}
$sqls[] = $sql . ' ALTER COLUMN ' . $this->db->escapeIdentifiers($field['name'])
. " {$field['type']}{$field['length']} " . ($nullable ? '' : 'NOT') . ' NULL';
if (! empty($field['comment'])) {
$sqls[] = 'EXEC sys.sp_addextendedproperty '
. "@name=N'Caption', @value=N'" . $field['comment'] . "' , "
. "@level0type=N'SCHEMA',@level0name=N'" . $this->db->schema . "', "
. "@level1type=N'TABLE',@level1name=N'" . $this->db->escapeIdentifiers($table) . "', "
. "@level2type=N'COLUMN',@level2name=N'" . $this->db->escapeIdentifiers($field['name']) . "'";
}
if (! empty($field['new_name'])) {
$sqls[] = "EXEC sp_rename '[" . $this->db->schema . '].[' . $table . '].[' . $field['name'] . "]' , '" . $field['new_name'] . "', 'COLUMN';";
}
}
return $sqls;
}
/**
* Drop index for table
*
* @return mixed
*/
protected function _dropIndex(string $table, object $indexData)
{
if ($indexData->type === 'PRIMARY') {
$sql = 'ALTER TABLE [' . $this->db->schema . '].[' . $table . '] DROP [' . $indexData->name . ']';
} else {
$sql = 'DROP INDEX [' . $indexData->name . '] ON [' . $this->db->schema . '].[' . $table . ']';
}
return $this->db->simpleQuery($sql);
}
/**
* Generates SQL to add indexes
*
* @param bool $asQuery When true returns stand alone SQL, else partial SQL used with CREATE TABLE
*/
protected function _processIndexes(string $table, bool $asQuery = false): array
{
$sqls = [];
for ($i = 0, $c = count($this->keys); $i < $c; $i++) {
for ($i2 = 0, $c2 = count($this->keys[$i]['fields']); $i2 < $c2; $i2++) {
if (! isset($this->fields[$this->keys[$i]['fields'][$i2]])) {
unset($this->keys[$i]['fields'][$i2]);
}
}
if (count($this->keys[$i]['fields']) <= 0) {
continue;
}
$keyName = $this->db->escapeIdentifiers(($this->keys[$i]['keyName'] === '') ?
$table . '_' . implode('_', $this->keys[$i]['fields']) :
$this->keys[$i]['keyName']);
if (in_array($i, $this->uniqueKeys, true)) {
$sqls[] = 'ALTER TABLE '
. $this->db->escapeIdentifiers($this->db->schema) . '.' . $this->db->escapeIdentifiers($table)
. ' ADD CONSTRAINT ' . $keyName
. ' UNIQUE (' . implode(', ', $this->db->escapeIdentifiers($this->keys[$i]['fields'])) . ');';
continue;
}
$sqls[] = 'CREATE INDEX '
. $keyName
. ' ON ' . $this->db->escapeIdentifiers($this->db->schema) . '.' . $this->db->escapeIdentifiers($table)
. ' (' . implode(', ', $this->db->escapeIdentifiers($this->keys[$i]['fields'])) . ');';
}
return $sqls;
}
/**
* Process column
*/
protected function _processColumn(array $processedField): string
{
return $this->db->escapeIdentifiers($processedField['name'])
. (empty($processedField['new_name']) ? '' : ' ' . $this->db->escapeIdentifiers($processedField['new_name']))
. ' ' . $processedField['type'] . ($processedField['type'] === 'text' ? '' : $processedField['length'])
. $processedField['default']
. $processedField['null']
. $processedField['auto_increment']
. ''
. $processedField['unique'];
}
/**
* Performs a data type mapping between different databases.
*/
protected function _attributeType(array &$attributes)
{
// Reset field lengths for data types that don't support it
if (isset($attributes['CONSTRAINT']) && str_contains(strtolower($attributes['TYPE']), 'int')) {
$attributes['CONSTRAINT'] = null;
}
switch (strtoupper($attributes['TYPE'])) {
case 'MEDIUMINT':
$attributes['TYPE'] = 'INTEGER';
$attributes['UNSIGNED'] = false;
break;
case 'INTEGER':
$attributes['TYPE'] = 'INT';
break;
case 'ENUM':
// in char(n) and varchar(n), the n defines the string length in
// bytes (0 to 8,000).
// https://learn.microsoft.com/en-us/sql/t-sql/data-types/char-and-varchar-transact-sql?view=sql-server-ver16#remarks
$maxLength = max(
array_map(
static fn ($value): int => strlen($value),
$attributes['CONSTRAINT'],
),
);
$attributes['TYPE'] = 'VARCHAR';
$attributes['CONSTRAINT'] = $maxLength;
break;
case 'TIMESTAMP':
$attributes['TYPE'] = 'DATETIME';
break;
case 'BOOLEAN':
$attributes['TYPE'] = 'BIT';
break;
case 'BLOB':
$attributes['TYPE'] = 'VARBINARY';
$attributes['CONSTRAINT'] ??= 'MAX';
break;
default:
break;
}
}
/**
* Field attribute AUTO_INCREMENT
*/
protected function _attributeAutoIncrement(array &$attributes, array &$field)
{
if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true && str_contains(strtolower($field['type']), strtolower('INT'))) {
$field['auto_increment'] = ' IDENTITY(1,1)';
}
}
/**
* Generates a platform-specific DROP TABLE string
*
* @todo Support for cascade
*/
protected function _dropTable(string $table, bool $ifExists, bool $cascade): string
{
$sql = 'DROP TABLE';
if ($ifExists) {
$sql .= ' IF EXISTS ';
}
$table = ' [' . $this->db->database . '].[' . $this->db->schema . '].[' . $table . '] ';
$sql .= $table;
if ($cascade) {
$sql .= '';
}
return $sql;
}
/**
* Constructs sql to check if key is a constraint.
*/
protected function _dropKeyAsConstraint(string $table, string $constraintName): string
{
return "SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME= '" . trim($table, '"') . "'
AND CONSTRAINT_NAME = '" . trim($constraintName, '"') . "'";
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/OCI8/Connection.php | system/Database/OCI8/Connection.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\Database\OCI8;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\Query;
use CodeIgniter\Database\TableName;
use ErrorException;
use stdClass;
/**
* Connection for OCI8
*
* @extends BaseConnection<resource, resource>
*/
class Connection extends BaseConnection
{
/**
* Database driver
*
* @var string
*/
protected $DBDriver = 'OCI8';
/**
* Identifier escape character
*
* @var string
*/
public $escapeChar = '"';
/**
* List of reserved identifiers
*
* Identifiers that must NOT be escaped.
*
* @var array
*/
protected $reservedIdentifiers = [
'*',
'rownum',
];
protected $validDSNs = [
// TNS
'tns' => '/^\(DESCRIPTION=(\(.+\)){2,}\)$/',
// Easy Connect string (Oracle 10g+).
// https://docs.oracle.com/en/database/oracle/oracle-database/23/netag/configuring-naming-methods.html#GUID-36F3A17D-843C-490A-8A23-FB0FE005F8E8
// [//]host[:port][/[service_name][:server_type][/instance_name]]
'ec' => '/^
(\/\/)?
(\[)?[a-z0-9.:_-]+(\])? # Host or IP address
(:[1-9][0-9]{0,4})? # Port
(
(\/)
([a-z0-9.$_]+)? # Service name
(:[a-z]+)? # Server type
(\/[a-z0-9$_]+)? # Instance name
)?
$/ix',
// Instance name (defined in tnsnames.ora)
'in' => '/^[a-z0-9$_]+$/i',
];
/**
* Reset $stmtId flag
*
* Used by storedProcedure() to prevent execute() from
* re-setting the statement ID.
*/
protected $resetStmtId = true;
/**
* Statement ID
*
* @var resource
*/
protected $stmtId;
/**
* Commit mode flag
*
* @used-by PreparedQuery::_execute()
*
* @var int
*/
public $commitMode = OCI_COMMIT_ON_SUCCESS;
/**
* Cursor ID
*
* @var resource
*/
protected $cursorId;
/**
* Latest inserted table name.
*
* @used-by PreparedQuery::_execute()
*
* @var string|null
*/
public $lastInsertedTableName;
/**
* confirm DSN format.
*/
private function isValidDSN(): bool
{
if ($this->DSN === null || $this->DSN === '') {
return false;
}
foreach ($this->validDSNs as $regexp) {
if (preg_match($regexp, $this->DSN)) {
return true;
}
}
return false;
}
/**
* Connect to the database.
*
* @return false|resource
*/
public function connect(bool $persistent = false)
{
if (! $this->isValidDSN()) {
$this->buildDSN();
}
$func = $persistent ? 'oci_pconnect' : 'oci_connect';
return ($this->charset === '')
? $func($this->username, $this->password, $this->DSN)
: $func($this->username, $this->password, $this->DSN, $this->charset);
}
/**
* Keep or establish the connection if no queries have been sent for
* a length of time exceeding the server's idle timeout.
*
* @return void
*/
public function reconnect()
{
}
/**
* Close the database connection.
*
* @return void
*/
protected function _close()
{
if (is_resource($this->cursorId)) {
oci_free_statement($this->cursorId);
}
if (is_resource($this->stmtId)) {
oci_free_statement($this->stmtId);
}
oci_close($this->connID);
}
/**
* Select a specific database table to use.
*/
public function setDatabase(string $databaseName): bool
{
return false;
}
/**
* Returns a string containing the version of the database being used.
*/
public function getVersion(): string
{
if (isset($this->dataCache['version'])) {
return $this->dataCache['version'];
}
if ($this->connID === false) {
$this->initialize();
}
if (($versionString = oci_server_version($this->connID)) === false) {
return '';
}
if (preg_match('#Release\s(\d+(?:\.\d+)+)#', $versionString, $match)) {
return $this->dataCache['version'] = $match[1];
}
return '';
}
/**
* Executes the query against the database.
*
* @return false|resource
*/
protected function execute(string $sql)
{
try {
if ($this->resetStmtId === true) {
$this->stmtId = oci_parse($this->connID, $sql);
}
oci_set_prefetch($this->stmtId, 1000);
$result = oci_execute($this->stmtId, $this->commitMode) ? $this->stmtId : false;
$insertTableName = $this->parseInsertTableName($sql);
if ($result && $insertTableName !== '') {
$this->lastInsertedTableName = $insertTableName;
}
return $result;
} catch (ErrorException $e) {
log_message('error', (string) $e);
if ($this->DBDebug) {
throw new DatabaseException($e->getMessage(), $e->getCode(), $e);
}
}
return false;
}
/**
* Get the table name for the insert statement from sql.
*/
public function parseInsertTableName(string $sql): string
{
$commentStrippedSql = preg_replace(['/\/\*(.|\n)*?\*\//m', '/--.+/'], '', $sql);
$isInsertQuery = str_starts_with(strtoupper(ltrim($commentStrippedSql)), 'INSERT');
if (! $isInsertQuery) {
return '';
}
preg_match('/(?is)\b(?:into)\s+("?\w+"?)/', $commentStrippedSql, $match);
$tableName = $match[1] ?? '';
return str_starts_with($tableName, '"') ? trim($tableName, '"') : strtoupper($tableName);
}
/**
* Returns the total number of rows affected by this query.
*/
public function affectedRows(): int
{
return oci_num_rows($this->stmtId);
}
/**
* Generates the SQL for listing tables in a platform-dependent manner.
*
* @param string|null $tableName If $tableName is provided will return only this table if exists.
*/
protected function _listTables(bool $prefixLimit = false, ?string $tableName = null): string
{
$sql = 'SELECT "TABLE_NAME" FROM "USER_TABLES"';
if ($tableName !== null) {
return $sql . ' WHERE "TABLE_NAME" LIKE ' . $this->escape($tableName);
}
if ($prefixLimit && $this->DBPrefix !== '') {
return $sql . ' WHERE "TABLE_NAME" LIKE \'' . $this->escapeLikeString($this->DBPrefix) . "%' "
. sprintf($this->likeEscapeStr, $this->likeEscapeChar);
}
return $sql;
}
/**
* Generates a platform-specific query string so that the column names can be fetched.
*
* @param string|TableName $table
*/
protected function _listColumns($table = ''): string
{
if ($table instanceof TableName) {
$tableName = $this->escape(strtoupper($table->getActualTableName()));
$owner = $this->username;
} elseif (str_contains($table, '.')) {
sscanf($table, '%[^.].%s', $owner, $tableName);
$tableName = $this->escape(strtoupper($this->DBPrefix . $tableName));
} else {
$owner = $this->username;
$tableName = $this->escape(strtoupper($this->DBPrefix . $table));
}
return 'SELECT COLUMN_NAME FROM ALL_TAB_COLUMNS
WHERE UPPER(OWNER) = ' . $this->escape(strtoupper($owner)) . '
AND UPPER(TABLE_NAME) = ' . $tableName;
}
/**
* Returns an array of objects with field data
*
* @return list<stdClass>
*
* @throws DatabaseException
*/
protected function _fieldData(string $table): array
{
if (str_contains($table, '.')) {
sscanf($table, '%[^.].%s', $owner, $table);
} else {
$owner = $this->username;
}
$sql = 'SELECT COLUMN_NAME, DATA_TYPE, CHAR_LENGTH, DATA_PRECISION, DATA_LENGTH, DATA_DEFAULT, NULLABLE
FROM ALL_TAB_COLUMNS
WHERE UPPER(OWNER) = ' . $this->escape(strtoupper($owner)) . '
AND UPPER(TABLE_NAME) = ' . $this->escape(strtoupper($table));
if (($query = $this->query($sql)) === false) {
throw new DatabaseException(lang('Database.failGetFieldData'));
}
$query = $query->getResultObject();
$retval = [];
for ($i = 0, $c = count($query); $i < $c; $i++) {
$retval[$i] = new stdClass();
$retval[$i]->name = $query[$i]->COLUMN_NAME;
$retval[$i]->type = $query[$i]->DATA_TYPE;
$length = $query[$i]->CHAR_LENGTH > 0 ? $query[$i]->CHAR_LENGTH : $query[$i]->DATA_PRECISION;
$length ??= $query[$i]->DATA_LENGTH;
$retval[$i]->max_length = $length;
$retval[$i]->nullable = $query[$i]->NULLABLE === 'Y';
$retval[$i]->default = $query[$i]->DATA_DEFAULT;
}
return $retval;
}
/**
* Returns an array of objects with index data
*
* @return array<string, stdClass>
*
* @throws DatabaseException
*/
protected function _indexData(string $table): array
{
if (str_contains($table, '.')) {
sscanf($table, '%[^.].%s', $owner, $table);
} else {
$owner = $this->username;
}
$sql = 'SELECT AIC.INDEX_NAME, UC.CONSTRAINT_TYPE, AIC.COLUMN_NAME '
. ' FROM ALL_IND_COLUMNS AIC '
. ' LEFT JOIN USER_CONSTRAINTS UC ON AIC.INDEX_NAME = UC.CONSTRAINT_NAME AND AIC.TABLE_NAME = UC.TABLE_NAME '
. 'WHERE AIC.TABLE_NAME = ' . $this->escape(strtolower($table)) . ' '
. 'AND AIC.TABLE_OWNER = ' . $this->escape(strtoupper($owner)) . ' '
. ' ORDER BY UC.CONSTRAINT_TYPE, AIC.COLUMN_POSITION';
if (($query = $this->query($sql)) === false) {
throw new DatabaseException(lang('Database.failGetIndexData'));
}
$query = $query->getResultObject();
$retVal = [];
$constraintTypes = [
'P' => 'PRIMARY',
'U' => 'UNIQUE',
];
foreach ($query as $row) {
if (isset($retVal[$row->INDEX_NAME])) {
$retVal[$row->INDEX_NAME]->fields[] = $row->COLUMN_NAME;
continue;
}
$retVal[$row->INDEX_NAME] = new stdClass();
$retVal[$row->INDEX_NAME]->name = $row->INDEX_NAME;
$retVal[$row->INDEX_NAME]->fields = [$row->COLUMN_NAME];
$retVal[$row->INDEX_NAME]->type = $constraintTypes[$row->CONSTRAINT_TYPE] ?? 'INDEX';
}
return $retVal;
}
/**
* Returns an array of objects with Foreign key data
*
* @return array<string, stdClass>
*
* @throws DatabaseException
*/
protected function _foreignKeyData(string $table): array
{
$sql = 'SELECT
acc.constraint_name,
acc.table_name,
acc.column_name,
ccu.table_name foreign_table_name,
accu.column_name foreign_column_name,
ac.delete_rule
FROM all_cons_columns acc
JOIN all_constraints ac ON acc.owner = ac.owner
AND acc.constraint_name = ac.constraint_name
JOIN all_constraints ccu ON ac.r_owner = ccu.owner
AND ac.r_constraint_name = ccu.constraint_name
JOIN all_cons_columns accu ON accu.constraint_name = ccu.constraint_name
AND accu.position = acc.position
AND accu.table_name = ccu.table_name
WHERE ac.constraint_type = ' . $this->escape('R') . '
AND acc.table_name = ' . $this->escape($table);
$query = $this->query($sql);
if ($query === false) {
throw new DatabaseException(lang('Database.failGetForeignKeyData'));
}
$query = $query->getResultObject();
$indexes = [];
foreach ($query as $row) {
$indexes[$row->CONSTRAINT_NAME]['constraint_name'] = $row->CONSTRAINT_NAME;
$indexes[$row->CONSTRAINT_NAME]['table_name'] = $row->TABLE_NAME;
$indexes[$row->CONSTRAINT_NAME]['column_name'][] = $row->COLUMN_NAME;
$indexes[$row->CONSTRAINT_NAME]['foreign_table_name'] = $row->FOREIGN_TABLE_NAME;
$indexes[$row->CONSTRAINT_NAME]['foreign_column_name'][] = $row->FOREIGN_COLUMN_NAME;
$indexes[$row->CONSTRAINT_NAME]['on_delete'] = $row->DELETE_RULE;
$indexes[$row->CONSTRAINT_NAME]['on_update'] = null;
$indexes[$row->CONSTRAINT_NAME]['match'] = null;
}
return $this->foreignKeyDataToObjects($indexes);
}
/**
* Returns platform-specific SQL to disable foreign key checks.
*
* @return string
*/
protected function _disableForeignKeyChecks()
{
return <<<'SQL'
BEGIN
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'ENABLED'
AND c.constraint_type = 'R'
AND t.iot_type IS NULL
ORDER BY c.constraint_type DESC)
LOOP
dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" disable constraint "' || c.constraint_name || '"');
END LOOP;
END;
SQL;
}
/**
* Returns platform-specific SQL to enable foreign key checks.
*
* @return string
*/
protected function _enableForeignKeyChecks()
{
return <<<'SQL'
BEGIN
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'DISABLED'
AND c.constraint_type = 'R'
AND t.iot_type IS NULL
ORDER BY c.constraint_type DESC)
LOOP
dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" enable constraint "' || c.constraint_name || '"');
END LOOP;
END;
SQL;
}
/**
* Get cursor. Returns a cursor from the database
*
* @return resource
*/
public function getCursor()
{
return $this->cursorId = oci_new_cursor($this->connID);
}
/**
* Executes a stored procedure
*
* @param string $procedureName procedure name to execute
* @param array $params params array keys
* KEY OPTIONAL NOTES
* name no the name of the parameter should be in :<param_name> format
* value no the value of the parameter. If this is an OUT or IN OUT parameter,
* this should be a reference to a variable
* type yes the type of the parameter
* length yes the max size of the parameter
*
* @return bool|Query|Result
*/
public function storedProcedure(string $procedureName, array $params)
{
if ($procedureName === '') {
throw new DatabaseException(lang('Database.invalidArgument', [$procedureName]));
}
// Build the query string
$sql = sprintf(
'BEGIN %s (' . substr(str_repeat(',%s', count($params)), 1) . '); END;',
$procedureName,
...array_map(static fn ($row) => $row['name'], $params),
);
$this->resetStmtId = false;
$this->stmtId = oci_parse($this->connID, $sql);
$this->bindParams($params);
$result = $this->query($sql);
$this->resetStmtId = true;
return $result;
}
/**
* Bind parameters
*
* @param array $params
*
* @return void
*/
protected function bindParams($params)
{
if (! is_array($params) || ! is_resource($this->stmtId)) {
return;
}
foreach ($params as $param) {
oci_bind_by_name(
$this->stmtId,
$param['name'],
$param['value'],
$param['length'] ?? -1,
$param['type'] ?? SQLT_CHR,
);
}
}
/**
* Returns the last error code and message.
*
* Must return an array with keys 'code' and 'message':
*
* return ['code' => null, 'message' => null);
*/
public function error(): array
{
// oci_error() returns an array that already contains
// 'code' and 'message' keys, but it can return false
// if there was no error ....
$error = oci_error();
$resources = [$this->cursorId, $this->stmtId, $this->connID];
foreach ($resources as $resource) {
if (is_resource($resource)) {
$error = oci_error($resource);
break;
}
}
return is_array($error)
? $error
: [
'code' => '',
'message' => '',
];
}
public function insertID(): int
{
if (empty($this->lastInsertedTableName)) {
return 0;
}
$indexs = $this->getIndexData($this->lastInsertedTableName);
$fieldDatas = $this->getFieldData($this->lastInsertedTableName);
if ($indexs === [] || $fieldDatas === []) {
return 0;
}
$columnTypeList = array_column($fieldDatas, 'type', 'name');
$primaryColumnName = '';
foreach ($indexs as $index) {
if ($index->type !== 'PRIMARY' || count($index->fields) !== 1) {
continue;
}
$primaryColumnName = $this->protectIdentifiers($index->fields[0], false, false);
$primaryColumnType = $columnTypeList[$primaryColumnName];
if ($primaryColumnType !== 'NUMBER') {
$primaryColumnName = '';
}
}
if ($primaryColumnName === '') {
return 0;
}
$query = $this->query('SELECT DATA_DEFAULT FROM USER_TAB_COLUMNS WHERE TABLE_NAME = ? AND COLUMN_NAME = ?', [$this->lastInsertedTableName, $primaryColumnName])->getRow();
$lastInsertValue = str_replace('nextval', 'currval', $query->DATA_DEFAULT ?? '0');
$query = $this->query(sprintf('SELECT %s SEQ FROM DUAL', $lastInsertValue))->getRow();
return (int) ($query->SEQ ?? 0);
}
/**
* Build a DSN from the provided parameters
*
* @return void
*/
protected function buildDSN()
{
if ($this->DSN !== '') {
$this->DSN = '';
}
// Legacy support for TNS in the hostname configuration field
$this->hostname = str_replace(["\n", "\r", "\t", ' '], '', $this->hostname);
if (preg_match($this->validDSNs['tns'], $this->hostname)) {
$this->DSN = $this->hostname;
return;
}
$isEasyConnectableHostName = $this->hostname !== '' && ! str_contains($this->hostname, '/') && ! str_contains($this->hostname, ':');
$easyConnectablePort = ($this->port !== '') && ctype_digit((string) $this->port) ? ':' . $this->port : '';
$easyConnectableDatabase = $this->database !== '' ? '/' . ltrim($this->database, '/') : '';
if ($isEasyConnectableHostName && ($easyConnectablePort !== '' || $easyConnectableDatabase !== '')) {
/* If the hostname field isn't empty, doesn't contain
* ':' and/or '/' and if port and/or database aren't
* empty, then the hostname field is most likely indeed
* just a hostname. Therefore we'll try and build an
* Easy Connect string from these 3 settings, assuming
* that the database field is a service name.
*/
$this->DSN = $this->hostname . $easyConnectablePort . $easyConnectableDatabase;
if (preg_match($this->validDSNs['ec'], $this->DSN)) {
return;
}
}
/* At this point, we can only try and validate the hostname and
* database fields separately as DSNs.
*/
if (preg_match($this->validDSNs['ec'], $this->hostname) || preg_match($this->validDSNs['in'], $this->hostname)) {
$this->DSN = $this->hostname;
return;
}
$this->database = str_replace(["\n", "\r", "\t", ' '], '', $this->database);
foreach ($this->validDSNs as $regexp) {
if (preg_match($regexp, $this->database)) {
return;
}
}
/* Well - OK, an empty string should work as well.
* PHP will try to use environment variables to
* determine which Oracle instance to connect to.
*/
$this->DSN = '';
}
/**
* Begin Transaction
*/
protected function _transBegin(): bool
{
$this->commitMode = OCI_NO_AUTO_COMMIT;
return true;
}
/**
* Commit Transaction
*/
protected function _transCommit(): bool
{
$this->commitMode = OCI_COMMIT_ON_SUCCESS;
return oci_commit($this->connID);
}
/**
* Rollback Transaction
*/
protected function _transRollback(): bool
{
$this->commitMode = OCI_COMMIT_ON_SUCCESS;
return oci_rollback($this->connID);
}
/**
* Returns the name of the current database being used.
*/
public function getDatabase(): string
{
if (! empty($this->database)) {
return $this->database;
}
return $this->query('SELECT DEFAULT_TABLESPACE FROM USER_USERS')->getRow()->DEFAULT_TABLESPACE ?? '';
}
/**
* Get the prefix of the function to access the DB.
*/
protected function getDriverFunctionPrefix(): string
{
return 'oci_';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/OCI8/Result.php | system/Database/OCI8/Result.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\Database\OCI8;
use CodeIgniter\Database\BaseResult;
use CodeIgniter\Entity\Entity;
use stdClass;
/**
* Result for OCI8
*
* @extends BaseResult<resource, resource>
*/
class Result extends BaseResult
{
/**
* Gets the number of fields in the result set.
*/
public function getFieldCount(): int
{
return oci_num_fields($this->resultID);
}
/**
* Generates an array of column names in the result set.
*/
public function getFieldNames(): array
{
return array_map(fn ($fieldIndex): false|string => oci_field_name($this->resultID, $fieldIndex), range(1, $this->getFieldCount()));
}
/**
* Generates an array of objects representing field meta-data.
*/
public function getFieldData(): array
{
return array_map(fn ($fieldIndex) => (object) [
'name' => oci_field_name($this->resultID, $fieldIndex),
'type' => oci_field_type($this->resultID, $fieldIndex),
'max_length' => oci_field_size($this->resultID, $fieldIndex),
], range(1, $this->getFieldCount()));
}
/**
* Frees the current result.
*
* @return void
*/
public function freeResult()
{
if (is_resource($this->resultID)) {
oci_free_statement($this->resultID);
$this->resultID = false;
}
}
/**
* Moves the internal pointer to the desired offset. This is called
* internally before fetching results to make sure the result set
* starts at zero.
*
* @return false
*/
public function dataSeek(int $n = 0)
{
// We can't support data seek by oci
return false;
}
/**
* Returns the result set as an array.
*
* Overridden by driver classes.
*
* @return array|false
*/
protected function fetchAssoc()
{
return oci_fetch_assoc($this->resultID);
}
/**
* Returns the result set as an object.
*
* Overridden by child classes.
*
* @return Entity|false|object|stdClass
*/
protected function fetchObject(string $className = 'stdClass')
{
$row = oci_fetch_object($this->resultID);
if ($className === 'stdClass' || ! $row) {
return $row;
}
if (is_subclass_of($className, Entity::class)) {
return (new $className())->injectRawData((array) $row);
}
$instance = new $className();
foreach (get_object_vars($row) as $key => $value) {
$instance->{$key} = $value;
}
return $instance;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/OCI8/Builder.php | system/Database/OCI8/Builder.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\Database\OCI8;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\RawSql;
/**
* Builder for OCI8
*/
class Builder extends BaseBuilder
{
/**
* Identifier escape character
*
* @var string
*/
protected $escapeChar = '"';
/**
* ORDER BY random keyword
*
* @var array
*/
protected $randomKeyword = [
'"DBMS_RANDOM"."RANDOM"',
];
/**
* COUNT string
*
* @used-by CI_DB_driver::count_all()
* @used-by BaseBuilder::count_all_results()
*
* @var string
*/
protected $countString = 'SELECT COUNT(1) ';
/**
* A reference to the database connection.
*
* @var Connection
*/
protected $db;
/**
* Generates a platform-specific insert string from the supplied data.
*/
protected function _insertBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$insertKeys = implode(', ', $keys);
$hasPrimaryKey = in_array('PRIMARY', array_column($this->db->getIndexData($table), 'type'), true);
// ORA-00001 measures
$sql = 'INSERT' . ($hasPrimaryKey ? '' : ' ALL') . ' INTO ' . $table . ' (' . $insertKeys . ")\n{:_table_:}";
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" FROM DUAL UNION ALL\n",
array_map(
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index): string => $index . ' ' . $key,
$keys,
$value,
)),
$values,
),
) . " FROM DUAL\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Generates a platform-specific replace string from the supplied data
*/
protected function _replace(string $table, array $keys, array $values): string
{
$fieldNames = array_map(static fn ($columnName): string => trim($columnName, '"'), $keys);
$uniqueIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames): bool {
$hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields);
return ($index->type === 'PRIMARY') && $hasAllFields;
});
$replaceableFields = array_filter($keys, static function ($columnName) use ($uniqueIndexes): bool {
foreach ($uniqueIndexes as $index) {
if (in_array(trim($columnName, '"'), $index->fields, true)) {
return false;
}
}
return true;
});
$sql = 'MERGE INTO ' . $table . "\n USING (SELECT ";
$sql .= implode(', ', array_map(static fn ($columnName, $value): string => $value . ' ' . $columnName, $keys, $values));
$sql .= ' FROM DUAL) "_replace" ON ( ';
$onList = [];
$onList[] = '1 != 1';
foreach ($uniqueIndexes as $index) {
$onList[] = '(' . implode(' AND ', array_map(static fn ($columnName): string => $table . '."' . $columnName . '" = "_replace"."' . $columnName . '"', $index->fields)) . ')';
}
$sql .= implode(' OR ', $onList) . ') WHEN MATCHED THEN UPDATE SET ';
$sql .= implode(', ', array_map(static fn ($columnName): string => $columnName . ' = "_replace".' . $columnName, $replaceableFields));
$sql .= ' WHEN NOT MATCHED THEN INSERT (' . implode(', ', $replaceableFields) . ') VALUES ';
return $sql . (' (' . implode(', ', array_map(static fn ($columnName): string => '"_replace".' . $columnName, $replaceableFields)) . ')');
}
/**
* Generates a platform-specific truncate string from the supplied data
*
* If the database does not support the truncate() command,
* then this method maps to 'DELETE FROM table'
*/
protected function _truncate(string $table): string
{
return 'TRUNCATE TABLE ' . $table;
}
/**
* Compiles a delete string and runs the query
*
* @param mixed $where
*
* @return mixed
*
* @throws DatabaseException
*/
public function delete($where = '', ?int $limit = null, bool $resetData = true)
{
if ($limit !== null && $limit !== 0) {
$this->QBLimit = $limit;
}
return parent::delete($where, null, $resetData);
}
/**
* Generates a platform-specific delete string from the supplied data
*/
protected function _delete(string $table): string
{
if ($this->QBLimit) {
$this->where('rownum <= ', $this->QBLimit, false);
$this->QBLimit = false;
}
return parent::_delete($table);
}
/**
* Generates a platform-specific update string from the supplied data
*/
protected function _update(string $table, array $values): string
{
$valStr = [];
foreach ($values as $key => $val) {
$valStr[] = $key . ' = ' . $val;
}
if ($this->QBLimit) {
$this->where('rownum <= ', $this->QBLimit, false);
}
return 'UPDATE ' . $this->compileIgnore('update') . $table . ' SET ' . implode(', ', $valStr)
. $this->compileWhereHaving('QBWhere')
. $this->compileOrderBy();
}
/**
* Generates a platform-specific LIMIT clause.
*/
protected function _limit(string $sql, bool $offsetIgnore = false): string
{
$offset = (int) ($offsetIgnore === false ? $this->QBOffset : 0);
// OFFSET-FETCH can be used only with the ORDER BY clause
if (empty($this->QBOrderBy)) {
$sql .= ' ORDER BY 1';
}
return $sql . ' OFFSET ' . $offset . ' ROWS FETCH NEXT ' . $this->QBLimit . ' ROWS ONLY';
}
/**
* Generates a platform-specific batch update string from the supplied data
*/
protected function _updateBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$constraints = $this->QBOptions['constraints'] ?? [];
if ($constraints === []) {
if ($this->db->DBDebug) {
throw new DatabaseException('You must specify a constraint to match on for batch updates.');
}
return ''; // @codeCoverageIgnore
}
$updateFields = $this->QBOptions['updateFields'] ??
$this->updateFields($keys, false, $constraints)->QBOptions['updateFields'] ??
[];
$alias = $this->QBOptions['alias'] ?? '"_u"';
// Oracle doesn't support ignore on updates so we will use MERGE
$sql = 'MERGE INTO ' . $table . "\n";
$sql .= "USING (\n{:_table_:}";
$sql .= ') ' . $alias . "\n";
$sql .= 'ON (' . implode(
' AND ',
array_map(
static fn ($key, $value) => (
($value instanceof RawSql && is_string($key))
?
$table . '.' . $key . ' = ' . $value
:
(
$value instanceof RawSql
?
$value
:
$table . '.' . $value . ' = ' . $alias . '.' . $value
)
),
array_keys($constraints),
$constraints,
),
) . ")\n";
$sql .= "WHEN MATCHED THEN UPDATE\n";
$sql .= "SET\n";
$sql .= implode(
",\n",
array_map(
static fn ($key, $value): string => $table . '.' . $key . ($value instanceof RawSql ?
' = ' . $value :
' = ' . $alias . '.' . $value),
array_keys($updateFields),
$updateFields,
),
);
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" UNION ALL\n",
array_map(
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index): string => $index . ' ' . $key,
$keys,
$value,
)) . ' FROM DUAL',
$values,
),
) . "\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Generates a platform-specific upsertBatch string from the supplied data
*
* @throws DatabaseException
*/
protected function _upsertBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$constraints = $this->QBOptions['constraints'] ?? [];
if (empty($constraints)) {
$fieldNames = array_map(static fn ($columnName): string => trim($columnName, '"'), $keys);
$uniqueIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames): bool {
$hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields);
return ($index->type === 'PRIMARY' || $index->type === 'UNIQUE') && $hasAllFields;
});
// only take first index
foreach ($uniqueIndexes as $index) {
$constraints = $index->fields;
break;
}
$constraints = $this->onConstraint($constraints)->QBOptions['constraints'] ?? [];
}
if (empty($constraints)) {
if ($this->db->DBDebug) {
throw new DatabaseException('No constraint found for upsert.');
}
return ''; // @codeCoverageIgnore
}
$alias = $this->QBOptions['alias'] ?? '"_upsert"';
$updateFields = $this->QBOptions['updateFields'] ?? $this->updateFields($keys, false, $constraints)->QBOptions['updateFields'] ?? [];
$sql = 'MERGE INTO ' . $table . "\nUSING (\n{:_table_:}";
$sql .= ") {$alias}\nON (";
$sql .= implode(
' AND ',
array_map(
static fn ($key, $value) => (
($value instanceof RawSql && is_string($key))
?
$table . '.' . $key . ' = ' . $value
:
(
$value instanceof RawSql
?
$value
:
$table . '.' . $value . ' = ' . $alias . '.' . $value
)
),
array_keys($constraints),
$constraints,
),
) . ")\n";
$sql .= "WHEN MATCHED THEN UPDATE SET\n";
$sql .= implode(
",\n",
array_map(
static fn ($key, $value): string => $key . ($value instanceof RawSql ?
" = {$value}" :
" = {$alias}.{$value}"),
array_keys($updateFields),
$updateFields,
),
);
$sql .= "\nWHEN NOT MATCHED THEN INSERT (" . implode(', ', $keys) . ")\nVALUES ";
$sql .= (' ('
. implode(', ', array_map(static fn ($columnName): string => "{$alias}.{$columnName}", $keys))
. ')');
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" FROM DUAL UNION ALL\n",
array_map(
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index): string => $index . ' ' . $key,
$keys,
$value,
)),
$values,
),
) . " FROM DUAL\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Generates a platform-specific batch update string from the supplied data
*/
protected function _deleteBatch(string $table, array $keys, array $values): string
{
$sql = $this->QBOptions['sql'] ?? '';
// if this is the first iteration of batch then we need to build skeleton sql
if ($sql === '') {
$constraints = $this->QBOptions['constraints'] ?? [];
if ($constraints === []) {
if ($this->db->DBDebug) {
throw new DatabaseException('You must specify a constraint to match on for batch deletes.'); // @codeCoverageIgnore
}
return ''; // @codeCoverageIgnore
}
$alias = $this->QBOptions['alias'] ?? '_u';
$sql = 'DELETE ' . $table . "\n";
$sql .= "WHERE EXISTS (SELECT * FROM (\n{:_table_:}";
$sql .= ') ' . $alias . "\n";
$sql .= 'WHERE ' . implode(
' AND ',
array_map(
static fn ($key, $value) => (
$value instanceof RawSql ?
$value :
(
is_string($key) ?
$table . '.' . $key . ' = ' . $alias . '.' . $value :
$table . '.' . $value . ' = ' . $alias . '.' . $value
)
),
array_keys($constraints),
$constraints,
),
);
// convert binds in where
foreach ($this->QBWhere as $key => $where) {
foreach ($this->binds as $field => $bind) {
$this->QBWhere[$key]['condition'] = str_replace(':' . $field . ':', $bind[0], $where['condition']);
}
}
$sql .= ' ' . str_replace(
'WHERE ',
'AND ',
$this->compileWhereHaving('QBWhere'),
) . ')';
$this->QBOptions['sql'] = $sql;
}
if (isset($this->QBOptions['setQueryAsData'])) {
$data = $this->QBOptions['setQueryAsData'];
} else {
$data = implode(
" FROM DUAL UNION ALL\n",
array_map(
static fn ($value): string => 'SELECT ' . implode(', ', array_map(
static fn ($key, $index): string => $index . ' ' . $key,
$keys,
$value,
)),
$values,
),
) . " FROM DUAL\n";
}
return str_replace('{:_table_:}', $data, $sql);
}
/**
* Gets column names from a select query
*/
protected function fieldsFromQuery(string $sql): array
{
return $this->db->query('SELECT * FROM (' . $sql . ') "_u_" WHERE ROWNUM = 1')->getFieldNames();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/OCI8/PreparedQuery.php | system/Database/OCI8/PreparedQuery.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\Database\OCI8;
use CodeIgniter\Database\BasePreparedQuery;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Exceptions\BadMethodCallException;
use OCILob;
/**
* Prepared query for OCI8
*
* @extends BasePreparedQuery<resource, resource, resource>
*/
class PreparedQuery extends BasePreparedQuery
{
/**
* A reference to the db connection to use.
*
* @var Connection
*/
protected $db;
/**
* Latest inserted table name.
*/
private ?string $lastInsertTableName = null;
/**
* Prepares the query against the database, and saves the connection
* info necessary to execute the query later.
*
* NOTE: This version is based on SQL code. Child classes should
* override this method.
*
* @param array $options Passed to the connection's prepare statement.
* Unused in the OCI8 driver.
*/
public function _prepare(string $sql, array $options = []): PreparedQuery
{
if (! $this->statement = oci_parse($this->db->connID, $this->parameterize($sql))) {
$error = oci_error($this->db->connID);
$this->errorCode = $error['code'] ?? 0;
$this->errorString = $error['message'] ?? '';
if ($this->db->DBDebug) {
throw new DatabaseException($this->errorString . ' code: ' . $this->errorCode);
}
}
$this->lastInsertTableName = $this->db->parseInsertTableName($sql);
return $this;
}
/**
* Takes a new set of data and runs it against the currently
* prepared query. Upon success, will return a Results object.
*/
public function _execute(array $data): bool
{
if (! isset($this->statement)) {
throw new BadMethodCallException('You must call prepare before trying to execute a prepared statement.');
}
$binaryData = null;
foreach (array_keys($data) as $key) {
if (is_string($data[$key]) && $this->isBinary($data[$key])) {
$binaryData = oci_new_descriptor($this->db->connID, OCI_D_LOB);
$binaryData->writeTemporary($data[$key], OCI_TEMP_BLOB);
oci_bind_by_name($this->statement, ':' . $key, $binaryData, -1, OCI_B_BLOB);
} else {
oci_bind_by_name($this->statement, ':' . $key, $data[$key]);
}
}
$result = oci_execute($this->statement, $this->db->commitMode);
if ($binaryData instanceof OCILob) {
$binaryData->free();
}
if ($result && $this->lastInsertTableName !== '') {
$this->db->lastInsertedTableName = $this->lastInsertTableName;
}
return $result;
}
/**
* Returns the statement resource for the prepared query or false when preparing failed.
*
* @return resource|null
*/
public function _getResult()
{
return $this->statement;
}
/**
* Deallocate prepared statements.
*/
protected function _close(): bool
{
return oci_free_statement($this->statement);
}
/**
* Replaces the ? placeholders with :0, :1, etc parameters for use
* within the prepared query.
*/
public function parameterize(string $sql): string
{
// Track our current value
$count = 0;
return preg_replace_callback('/\?/', static function ($matches) use (&$count): string {
return ':' . ($count++);
}, $sql);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/OCI8/Utils.php | system/Database/OCI8/Utils.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\Database\OCI8;
use CodeIgniter\Database\BaseUtils;
use CodeIgniter\Database\Exceptions\DatabaseException;
/**
* Utils for OCI8
*/
class Utils extends BaseUtils
{
/**
* List databases statement
*
* @var string
*/
protected $listDatabases = 'SELECT TABLESPACE_NAME FROM USER_TABLESPACES';
/**
* Platform dependent version of the backup function.
*
* @return never
*/
public function _backup(?array $prefs = null)
{
throw new DatabaseException('Unsupported feature of the database platform you are using.');
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Database/OCI8/Forge.php | system/Database/OCI8/Forge.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\Database\OCI8;
use CodeIgniter\Database\Forge as BaseForge;
/**
* Forge for OCI8
*/
class Forge extends BaseForge
{
/**
* DROP INDEX statement
*
* @var string
*/
protected $dropIndexStr = 'DROP INDEX %s';
/**
* CREATE DATABASE statement
*
* @var false
*/
protected $createDatabaseStr = false;
/**
* CREATE TABLE IF statement
*
* @var false
*
* @deprecated This is no longer used.
*/
protected $createTableIfStr = false;
/**
* DROP TABLE IF EXISTS statement
*
* @var false
*/
protected $dropTableIfStr = false;
/**
* DROP DATABASE statement
*
* @var false
*/
protected $dropDatabaseStr = false;
/**
* UNSIGNED support
*
* @var array|bool
*/
protected $unsigned = false;
/**
* NULL value representation in CREATE/ALTER TABLE statements
*
* @var string
*/
protected $null = 'NULL';
/**
* RENAME TABLE statement
*
* @var string
*/
protected $renameTableStr = 'ALTER TABLE %s RENAME TO %s';
/**
* DROP CONSTRAINT statement
*
* @var string
*/
protected $dropConstraintStr = 'ALTER TABLE %s DROP CONSTRAINT %s';
/**
* Foreign Key Allowed Actions
*
* @var array
*/
protected $fkAllowActions = ['CASCADE', 'SET NULL', 'NO ACTION'];
/**
* ALTER TABLE
*
* @param string $alterType ALTER type
* @param string $table Table name
* @param array|string $processedFields Processed column definitions
* or column names to DROP
*
* @return ($alterType is 'DROP' ? string : list<string>)
*/
protected function _alterTable(string $alterType, string $table, $processedFields)
{
$sql = 'ALTER TABLE ' . $this->db->escapeIdentifiers($table);
if ($alterType === 'DROP') {
$columnNamesToDrop = $processedFields;
$fields = array_map(
fn ($field) => $this->db->escapeIdentifiers(trim($field)),
is_string($columnNamesToDrop) ? explode(',', $columnNamesToDrop) : $columnNamesToDrop,
);
return $sql . ' DROP (' . implode(',', $fields) . ') CASCADE CONSTRAINT INVALIDATE';
}
if ($alterType === 'CHANGE') {
$alterType = 'MODIFY';
}
$nullableMap = array_column($this->db->getFieldData($table), 'nullable', 'name');
$sqls = [];
for ($i = 0, $c = count($processedFields); $i < $c; $i++) {
if ($alterType === 'MODIFY') {
// If a null constraint is added to a column with a null constraint,
// ORA-01451 will occur,
// so add null constraint is used only when it is different from the current null constraint.
// If a not null constraint is added to a column with a not null constraint,
// ORA-01442 will occur.
$wantToAddNull = ! str_contains($processedFields[$i]['null'], ' NOT');
$currentNullable = $nullableMap[$processedFields[$i]['name']];
if ($wantToAddNull && $currentNullable === true) {
$processedFields[$i]['null'] = '';
} elseif ($processedFields[$i]['null'] === '' && $currentNullable === false) {
// Nullable by default
$processedFields[$i]['null'] = ' NULL';
} elseif ($wantToAddNull === false && $currentNullable === false) {
$processedFields[$i]['null'] = '';
}
}
if ($processedFields[$i]['_literal'] !== false) {
$processedFields[$i] = "\n\t" . $processedFields[$i]['_literal'];
} else {
$processedFields[$i]['_literal'] = "\n\t" . $this->_processColumn($processedFields[$i]);
if (! empty($processedFields[$i]['comment'])) {
$sqls[] = 'COMMENT ON COLUMN '
. $this->db->escapeIdentifiers($table) . '.' . $this->db->escapeIdentifiers($processedFields[$i]['name'])
. ' IS ' . $processedFields[$i]['comment'];
}
if ($alterType === 'MODIFY' && ! empty($processedFields[$i]['new_name'])) {
$sqls[] = $sql . ' RENAME COLUMN ' . $this->db->escapeIdentifiers($processedFields[$i]['name'])
. ' TO ' . $this->db->escapeIdentifiers($processedFields[$i]['new_name']);
}
$processedFields[$i] = "\n\t" . $processedFields[$i]['_literal'];
}
}
$sql .= ' ' . $alterType . ' ';
$sql .= count($processedFields) === 1
? $processedFields[0]
: '(' . implode(',', $processedFields) . ')';
// RENAME COLUMN must be executed after MODIFY
array_unshift($sqls, $sql);
return $sqls;
}
/**
* Field attribute AUTO_INCREMENT
*
* @return void
*/
protected function _attributeAutoIncrement(array &$attributes, array &$field)
{
if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true
&& str_contains(strtolower($field['type']), 'number')
&& version_compare($this->db->getVersion(), '12.1', '>=')
) {
$field['auto_increment'] = ' GENERATED BY DEFAULT ON NULL AS IDENTITY';
}
}
/**
* Process column
*/
protected function _processColumn(array $processedField): string
{
$constraint = '';
// @todo: can't cover multi pattern when set type.
if ($processedField['type'] === 'VARCHAR2' && str_starts_with($processedField['length'], "('")) {
$constraint = ' CHECK(' . $this->db->escapeIdentifiers($processedField['name'])
. ' IN ' . $processedField['length'] . ')';
$processedField['length'] = '(' . max(array_map(mb_strlen(...), explode("','", mb_substr($processedField['length'], 2, -2)))) . ')' . $constraint;
} elseif (isset($this->primaryKeys['fields']) && count($this->primaryKeys['fields']) === 1 && $processedField['name'] === $this->primaryKeys['fields'][0]) {
$processedField['unique'] = '';
}
return $this->db->escapeIdentifiers($processedField['name'])
. ' ' . $processedField['type'] . $processedField['length']
. $processedField['unsigned']
. $processedField['default']
. $processedField['auto_increment']
. $processedField['null']
. $processedField['unique'];
}
/**
* Performs a data type mapping between different databases.
*
* @return void
*/
protected function _attributeType(array &$attributes)
{
// Reset field lengths for data types that don't support it
// Usually overridden by drivers
switch (strtoupper($attributes['TYPE'])) {
case 'TINYINT':
$attributes['CONSTRAINT'] ??= 3;
// no break
case 'SMALLINT':
$attributes['CONSTRAINT'] ??= 5;
// no break
case 'MEDIUMINT':
$attributes['CONSTRAINT'] ??= 7;
// no break
case 'INT':
case 'INTEGER':
$attributes['CONSTRAINT'] ??= 11;
// no break
case 'BIGINT':
$attributes['CONSTRAINT'] ??= 19;
// no break
case 'NUMERIC':
$attributes['TYPE'] = 'NUMBER';
return;
case 'BOOLEAN':
$attributes['TYPE'] = 'NUMBER';
$attributes['CONSTRAINT'] = 1;
$attributes['UNSIGNED'] = true;
return;
case 'DOUBLE':
$attributes['TYPE'] = 'FLOAT';
$attributes['CONSTRAINT'] ??= 126;
return;
case 'DATETIME':
case 'TIME':
$attributes['TYPE'] = 'DATE';
return;
case 'SET':
case 'ENUM':
case 'VARCHAR':
$attributes['CONSTRAINT'] ??= 255;
// no break
case 'TEXT':
case 'MEDIUMTEXT':
$attributes['CONSTRAINT'] ??= 4000;
$attributes['TYPE'] = 'VARCHAR2';
}
}
/**
* Generates a platform-specific DROP TABLE string
*
* @return bool|string
*/
protected function _dropTable(string $table, bool $ifExists, bool $cascade)
{
$sql = parent::_dropTable($table, $ifExists, $cascade);
if ($sql !== true && $cascade) {
$sql .= ' CASCADE CONSTRAINTS PURGE';
} elseif ($sql !== true) {
$sql .= ' PURGE';
}
return $sql;
}
/**
* Constructs sql to check if key is a constraint.
*/
protected function _dropKeyAsConstraint(string $table, string $constraintName): string
{
return "SELECT constraint_name FROM all_constraints WHERE table_name = '"
. trim($table, '"') . "' AND index_name = '"
. trim($constraintName, '"') . "'";
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cache/ResponseCache.php | system/Cache/ResponseCache.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\Cache;
use CodeIgniter\Exceptions\RuntimeException;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\Header;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Cache as CacheConfig;
/**
* Web Page Caching
*
* @see \CodeIgniter\Cache\ResponseCacheTest
*/
final class ResponseCache
{
/**
* Whether to take the URL query string into consideration when generating
* output cache files. Valid options are:
*
* false = Disabled
* true = Enabled, take all query parameters into account.
* Please be aware that this may result in numerous cache
* files generated for the same page over and over again.
* array('q') = Enabled, but only take into account the specified list
* of query parameters.
*
* @var bool|list<string>
*/
private array|bool $cacheQueryString = false;
/**
* Cache time to live (TTL) in seconds.
*/
private int $ttl = 0;
public function __construct(CacheConfig $config, private readonly CacheInterface $cache)
{
$this->cacheQueryString = $config->cacheQueryString;
}
public function setTtl(int $ttl): self
{
$this->ttl = $ttl;
return $this;
}
/**
* Generates the cache key to use from the current request.
*
* @internal for testing purposes only
*/
public function generateCacheKey(CLIRequest|IncomingRequest $request): string
{
if ($request instanceof CLIRequest) {
return md5($request->getPath());
}
$uri = clone $request->getUri();
$query = (bool) $this->cacheQueryString
? $uri->getQuery(is_array($this->cacheQueryString) ? ['only' => $this->cacheQueryString] : [])
: '';
return md5($request->getMethod() . ':' . $uri->setFragment('')->setQuery($query));
}
/**
* Caches the response.
*/
public function make(CLIRequest|IncomingRequest $request, ResponseInterface $response): bool
{
if ($this->ttl === 0) {
return true;
}
$headers = [];
foreach ($response->headers() as $name => $value) {
if ($value instanceof Header) {
$headers[$name] = $value->getValueLine();
} else {
foreach ($value as $header) {
$headers[$name][] = $header->getValueLine();
}
}
}
return $this->cache->save(
$this->generateCacheKey($request),
serialize(['headers' => $headers, 'output' => $response->getBody()]),
$this->ttl,
);
}
/**
* Gets the cached response for the request.
*/
public function get(CLIRequest|IncomingRequest $request, ResponseInterface $response): ?ResponseInterface
{
$cachedResponse = $this->cache->get($this->generateCacheKey($request));
if (is_string($cachedResponse) && $cachedResponse !== '') {
$cachedResponse = unserialize($cachedResponse);
if (
! is_array($cachedResponse)
|| ! isset($cachedResponse['output'])
|| ! isset($cachedResponse['headers'])
) {
throw new RuntimeException('Error unserializing page cache');
}
$headers = $cachedResponse['headers'];
$output = $cachedResponse['output'];
// Clear all default headers
foreach (array_keys($response->headers()) as $key) {
$response->removeHeader($key);
}
// Set cached headers
foreach ($headers as $name => $value) {
$response->setHeader($name, $value);
}
$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/Cache/CacheInterface.php | system/Cache/CacheInterface.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\Cache;
interface CacheInterface
{
/**
* Takes care of any handler-specific setup that must be done.
*
* @return void
*/
public function initialize();
/**
* Attempts to fetch an item from the cache store.
*
* @param string $key Cache item name
*
* @return mixed
*/
public function get(string $key);
/**
* Saves an item to the cache store.
*
* @param string $key Cache item name
* @param mixed $value The data to save
* @param int $ttl Time To Live, in seconds (default 60)
*
* @return bool Success or failure
*/
public function save(string $key, $value, int $ttl = 60);
/**
* Deletes a specific item from the cache store.
*
* @param string $key Cache item name
*
* @return bool Success or failure
*/
public function delete(string $key);
/**
* Performs atomic incrementation of a raw stored value.
*
* @param string $key Cache ID
* @param int $offset Step/value to increase by
*
* @return bool|int
*/
public function increment(string $key, int $offset = 1);
/**
* Performs atomic decrementation of a raw stored value.
*
* @param string $key Cache ID
* @param int $offset Step/value to increase by
*
* @return bool|int
*/
public function decrement(string $key, int $offset = 1);
/**
* Will delete all items in the entire cache.
*
* @return bool Success or failure
*/
public function clean();
/**
* Returns information on the entire cache.
*
* The information returned and the structure of the data
* varies depending on the handler.
*
* @return array<array-key, mixed>|false|object|null
*/
public function getCacheInfo();
/**
* Returns detailed information about the specific item in the cache.
*
* @param string $key Cache item name.
*
* @return array<string, mixed>|false|null Returns null if the item does not exist, otherwise array<string, mixed>
* with at least the 'expire' key for absolute epoch expiry (or null).
* Some handlers may return false when an item does not exist, which is deprecated.
*/
public function getMetaData(string $key);
/**
* Determines if the driver is supported on this system.
*/
public function isSupported(): bool;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cache/FactoriesCache.php | system/Cache/FactoriesCache.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\Cache;
use CodeIgniter\Cache\FactoriesCache\FileVarExportHandler;
use CodeIgniter\Config\Factories;
final class FactoriesCache
{
private readonly CacheInterface|FileVarExportHandler $cache;
public function __construct(CacheInterface|FileVarExportHandler|null $cache = null)
{
$this->cache = $cache ?? new FileVarExportHandler();
}
public function save(string $component): void
{
if (! Factories::isUpdated($component)) {
return;
}
$data = Factories::getComponentInstances($component);
$this->cache->save($this->getCacheKey($component), $data, 3600 * 24);
}
private function getCacheKey(string $component): string
{
return 'FactoriesCache_' . $component;
}
public function load(string $component): bool
{
$key = $this->getCacheKey($component);
$data = $this->cache->get($key);
if (! is_array($data) || $data === []) {
return false;
}
Factories::setComponentInstances($component, $data);
return true;
}
public function delete(string $component): void
{
$this->cache->delete($this->getCacheKey($component));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cache/CacheFactory.php | system/Cache/CacheFactory.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\Cache;
use CodeIgniter\Cache\Exceptions\CacheException;
use CodeIgniter\Exceptions\CriticalError;
use CodeIgniter\Test\Mock\MockCache;
use Config\Cache;
/**
* A factory for loading the desired
*
* @see \CodeIgniter\Cache\CacheFactoryTest
*/
class CacheFactory
{
/**
* The class to use when mocking
*
* @var string
*/
public static $mockClass = MockCache::class;
/**
* The service to inject the mock as
*
* @var string
*/
public static $mockServiceName = 'cache';
/**
* Attempts to create the desired cache handler, based upon the
*
* @param non-empty-string|null $handler
* @param non-empty-string|null $backup
*
* @return CacheInterface
*/
public static function getHandler(Cache $config, ?string $handler = null, ?string $backup = null)
{
if (! isset($config->validHandlers) || $config->validHandlers === []) {
throw CacheException::forInvalidHandlers();
}
if (! isset($config->handler) || ! isset($config->backupHandler)) {
throw CacheException::forNoBackup();
}
$handler ??= $config->handler;
$backup ??= $config->backupHandler;
if (! array_key_exists($handler, $config->validHandlers) || ! array_key_exists($backup, $config->validHandlers)) {
throw CacheException::forHandlerNotFound();
}
$adapter = new $config->validHandlers[$handler]($config);
if (! $adapter->isSupported()) {
$adapter = new $config->validHandlers[$backup]($config);
if (! $adapter->isSupported()) {
// Fall back to the dummy adapter.
$adapter = new $config->validHandlers['dummy']();
}
}
// If $adapter->initialize() throws a CriticalError exception, we will attempt to
// use the $backup handler, if that also fails, we resort to the dummy handler.
try {
$adapter->initialize();
} catch (CriticalError $e) {
log_message('critical', $e . ' Resorting to using ' . $backup . ' handler.');
// get the next best cache handler (or dummy if the $backup also fails)
$adapter = self::getHandler($config, $backup, 'dummy');
}
return $adapter;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cache/Exceptions/CacheException.php | system/Cache/Exceptions/CacheException.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\Cache\Exceptions;
use CodeIgniter\Exceptions\DebugTraceableTrait;
use CodeIgniter\Exceptions\RuntimeException;
class CacheException extends RuntimeException
{
use DebugTraceableTrait;
/**
* Thrown when handler has no permission to write cache.
*
* @return static
*/
public static function forUnableToWrite(string $path)
{
return new static(lang('Cache.unableToWrite', [$path]));
}
/**
* Thrown when an unrecognized handler is used.
*
* @return static
*/
public static function forInvalidHandlers()
{
return new static(lang('Cache.invalidHandlers'));
}
/**
* Thrown when no backup handler is setup in config.
*
* @return static
*/
public static function forNoBackup()
{
return new static(lang('Cache.noBackup'));
}
/**
* Thrown when specified handler was not found.
*
* @return static
*/
public static function forHandlerNotFound()
{
return new static(lang('Cache.handlerNotFound'));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cache/FactoriesCache/FileVarExportHandler.php | system/Cache/FactoriesCache/FileVarExportHandler.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\Cache\FactoriesCache;
final class FileVarExportHandler
{
private string $path = WRITEPATH . 'cache';
public function save(string $key, mixed $val): void
{
$val = var_export($val, true);
// Write to temp file first to ensure atomicity
$tmp = $this->path . "/{$key}." . uniqid('', true) . '.tmp';
file_put_contents($tmp, '<?php return ' . $val . ';', LOCK_EX);
rename($tmp, $this->path . "/{$key}");
}
public function delete(string $key): void
{
@unlink($this->path . "/{$key}");
}
public function get(string $key): mixed
{
return @include $this->path . "/{$key}";
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cache/Handlers/PredisHandler.php | system/Cache/Handlers/PredisHandler.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\Cache\Handlers;
use CodeIgniter\Exceptions\CriticalError;
use CodeIgniter\I18n\Time;
use Config\Cache;
use Exception;
use Predis\Client;
use Predis\Collection\Iterator\Keyspace;
use Predis\Response\Status;
/**
* Predis cache handler
*
* @see \CodeIgniter\Cache\Handlers\PredisHandlerTest
*/
class PredisHandler extends BaseHandler
{
/**
* Default config
*
* @var array{
* scheme: string,
* host: string,
* password: string|null,
* port: int,
* timeout: int
* }
*/
protected $config = [
'scheme' => 'tcp',
'host' => '127.0.0.1',
'password' => null,
'port' => 6379,
'timeout' => 0,
];
/**
* Predis connection
*
* @var Client
*/
protected $redis;
/**
* Note: Use `CacheFactory::getHandler()` to instantiate.
*/
public function __construct(Cache $config)
{
$this->prefix = $config->prefix;
if (isset($config->redis)) {
$this->config = array_merge($this->config, $config->redis);
}
}
/**
* {@inheritDoc}
*/
public function initialize()
{
try {
$this->redis = new Client($this->config, ['prefix' => $this->prefix]);
$this->redis->time();
} catch (Exception $e) {
throw new CriticalError('Cache: Predis connection refused (' . $e->getMessage() . ').');
}
}
/**
* {@inheritDoc}
*/
public function get(string $key)
{
$key = static::validateKey($key);
$data = array_combine(
['__ci_type', '__ci_value'],
$this->redis->hmget($key, ['__ci_type', '__ci_value']),
);
if (! isset($data['__ci_type'], $data['__ci_value']) || $data['__ci_value'] === false) {
return null;
}
return match ($data['__ci_type']) {
'array', 'object' => unserialize($data['__ci_value']),
// Yes, 'double' is returned and NOT 'float'
'boolean', 'integer', 'double', 'string', 'NULL' => settype($data['__ci_value'], $data['__ci_type']) ? $data['__ci_value'] : null,
default => null,
};
}
/**
* {@inheritDoc}
*/
public function save(string $key, $value, int $ttl = 60)
{
$key = static::validateKey($key);
switch ($dataType = gettype($value)) {
case 'array':
case 'object':
$value = serialize($value);
break;
case 'boolean':
case 'integer':
case 'double': // Yes, 'double' is returned and NOT 'float'
case 'string':
case 'NULL':
break;
case 'resource':
default:
return false;
}
if (! $this->redis->hmset($key, ['__ci_type' => $dataType, '__ci_value' => $value]) instanceof Status) {
return false;
}
if ($ttl !== 0) {
$this->redis->expireat($key, Time::now()->getTimestamp() + $ttl);
}
return true;
}
/**
* {@inheritDoc}
*/
public function delete(string $key)
{
$key = static::validateKey($key);
return $this->redis->del($key) === 1;
}
/**
* {@inheritDoc}
*
* @return int
*/
public function deleteMatching(string $pattern)
{
$matchedKeys = [];
foreach (new Keyspace($this->redis, $pattern) as $key) {
$matchedKeys[] = $key;
}
return $this->redis->del($matchedKeys);
}
/**
* {@inheritDoc}
*/
public function increment(string $key, int $offset = 1)
{
$key = static::validateKey($key);
return $this->redis->hincrby($key, 'data', $offset);
}
/**
* {@inheritDoc}
*/
public function decrement(string $key, int $offset = 1)
{
$key = static::validateKey($key);
return $this->redis->hincrby($key, 'data', -$offset);
}
/**
* {@inheritDoc}
*/
public function clean()
{
return $this->redis->flushdb()->getPayload() === 'OK';
}
/**
* {@inheritDoc}
*/
public function getCacheInfo()
{
return $this->redis->info();
}
/**
* {@inheritDoc}
*/
public function getMetaData(string $key)
{
$key = static::validateKey($key);
$data = array_combine(['__ci_value'], $this->redis->hmget($key, ['__ci_value']));
if (isset($data['__ci_value']) && $data['__ci_value'] !== false) {
$time = Time::now()->getTimestamp();
$ttl = $this->redis->ttl($key);
return [
'expire' => $ttl > 0 ? $time + $ttl : null,
'mtime' => $time,
'data' => $data['__ci_value'],
];
}
return null;
}
/**
* {@inheritDoc}
*/
public function isSupported(): bool
{
return class_exists(Client::class);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cache/Handlers/DummyHandler.php | system/Cache/Handlers/DummyHandler.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\Cache\Handlers;
use Closure;
/**
* Dummy cache handler
*
* @see \CodeIgniter\Cache\Handlers\DummyHandlerTest
*/
class DummyHandler extends BaseHandler
{
/**
* {@inheritDoc}
*/
public function initialize()
{
}
/**
* {@inheritDoc}
*/
public function get(string $key)
{
return null;
}
/**
* {@inheritDoc}
*/
public function remember(string $key, int $ttl, Closure $callback)
{
return null;
}
/**
* {@inheritDoc}
*/
public function save(string $key, $value, int $ttl = 60)
{
return true;
}
/**
* {@inheritDoc}
*/
public function delete(string $key)
{
return true;
}
/**
* {@inheritDoc}
*
* @return int
*/
public function deleteMatching(string $pattern)
{
return 0;
}
/**
* {@inheritDoc}
*/
public function increment(string $key, int $offset = 1)
{
return true;
}
/**
* {@inheritDoc}
*/
public function decrement(string $key, int $offset = 1)
{
return true;
}
/**
* {@inheritDoc}
*/
public function clean()
{
return true;
}
/**
* {@inheritDoc}
*/
public function getCacheInfo()
{
return null;
}
/**
* {@inheritDoc}
*/
public function getMetaData(string $key)
{
return null;
}
/**
* {@inheritDoc}
*/
public function isSupported(): bool
{
return true;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cache/Handlers/RedisHandler.php | system/Cache/Handlers/RedisHandler.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\Cache\Handlers;
use CodeIgniter\Exceptions\CriticalError;
use CodeIgniter\I18n\Time;
use Config\Cache;
use Redis;
use RedisException;
/**
* Redis cache handler
*
* @see \CodeIgniter\Cache\Handlers\RedisHandlerTest
*/
class RedisHandler extends BaseHandler
{
/**
* Default config
*
* @var array{
* host: string,
* password: string|null,
* port: int,
* timeout: int,
* database: int,
* }
*/
protected $config = [
'host' => '127.0.0.1',
'password' => null,
'port' => 6379,
'timeout' => 0,
'database' => 0,
];
/**
* Redis connection
*
* @var Redis|null
*/
protected $redis;
/**
* Note: Use `CacheFactory::getHandler()` to instantiate.
*/
public function __construct(Cache $config)
{
$this->prefix = $config->prefix;
$this->config = array_merge($this->config, $config->redis);
}
/**
* Closes the connection to Redis if present.
*/
public function __destruct()
{
if (isset($this->redis)) {
$this->redis->close();
}
}
/**
* {@inheritDoc}
*/
public function initialize()
{
$config = $this->config;
$this->redis = new Redis();
try {
// Note:: If Redis is your primary cache choice, and it is "offline", every page load will end up been delayed by the timeout duration.
// I feel like some sort of temporary flag should be set, to indicate that we think Redis is "offline", allowing us to bypass the timeout for a set period of time.
if (! $this->redis->connect($config['host'], ($config['host'][0] === '/' ? 0 : $config['port']), $config['timeout'])) {
// Note:: I'm unsure if log_message() is necessary, however I'm not 100% comfortable removing it.
log_message('error', 'Cache: Redis connection failed. Check your configuration.');
throw new CriticalError('Cache: Redis connection failed. Check your configuration.');
}
if (isset($config['password']) && ! $this->redis->auth($config['password'])) {
log_message('error', 'Cache: Redis authentication failed.');
throw new CriticalError('Cache: Redis authentication failed.');
}
if (isset($config['database']) && ! $this->redis->select($config['database'])) {
log_message('error', 'Cache: Redis select database failed.');
throw new CriticalError('Cache: Redis select database failed.');
}
} catch (RedisException $e) {
throw new CriticalError('Cache: RedisException occurred with message (' . $e->getMessage() . ').');
}
}
/**
* {@inheritDoc}
*/
public function get(string $key)
{
$key = static::validateKey($key, $this->prefix);
$data = $this->redis->hMget($key, ['__ci_type', '__ci_value']);
if (! isset($data['__ci_type'], $data['__ci_value']) || $data['__ci_value'] === false) {
return null;
}
return match ($data['__ci_type']) {
'array', 'object' => unserialize($data['__ci_value']),
// Yes, 'double' is returned and NOT 'float'
'boolean', 'integer', 'double', 'string', 'NULL' => settype($data['__ci_value'], $data['__ci_type']) ? $data['__ci_value'] : null,
default => null,
};
}
/**
* {@inheritDoc}
*/
public function save(string $key, $value, int $ttl = 60)
{
$key = static::validateKey($key, $this->prefix);
switch ($dataType = gettype($value)) {
case 'array':
case 'object':
$value = serialize($value);
break;
case 'boolean':
case 'integer':
case 'double': // Yes, 'double' is returned and NOT 'float'
case 'string':
case 'NULL':
break;
case 'resource':
default:
return false;
}
if (! $this->redis->hMset($key, ['__ci_type' => $dataType, '__ci_value' => $value])) {
return false;
}
if ($ttl !== 0) {
$this->redis->expireAt($key, Time::now()->getTimestamp() + $ttl);
}
return true;
}
/**
* {@inheritDoc}
*/
public function delete(string $key)
{
$key = static::validateKey($key, $this->prefix);
return $this->redis->del($key) === 1;
}
/**
* {@inheritDoc}
*
* @return int
*/
public function deleteMatching(string $pattern)
{
/** @var list<string> $matchedKeys */
$matchedKeys = [];
$pattern = static::validateKey($pattern, $this->prefix);
$iterator = null;
do {
/** @var false|list<string> $keys */
$keys = $this->redis->scan($iterator, $pattern);
if (is_array($keys)) {
$matchedKeys = [...$matchedKeys, ...$keys];
}
} while ($iterator > 0);
return $this->redis->del($matchedKeys);
}
/**
* {@inheritDoc}
*/
public function increment(string $key, int $offset = 1)
{
$key = static::validateKey($key, $this->prefix);
return $this->redis->hIncrBy($key, '__ci_value', $offset);
}
/**
* {@inheritDoc}
*/
public function decrement(string $key, int $offset = 1)
{
return $this->increment($key, -$offset);
}
/**
* {@inheritDoc}
*/
public function clean()
{
return $this->redis->flushDB();
}
/**
* {@inheritDoc}
*/
public function getCacheInfo()
{
return $this->redis->info();
}
/**
* {@inheritDoc}
*/
public function getMetaData(string $key)
{
$value = $this->get($key);
if ($value !== null) {
$time = Time::now()->getTimestamp();
$ttl = $this->redis->ttl(static::validateKey($key, $this->prefix));
assert(is_int($ttl));
return [
'expire' => $ttl > 0 ? $time + $ttl : null,
'mtime' => $time,
'data' => $value,
];
}
return null;
}
/**
* {@inheritDoc}
*/
public function isSupported(): bool
{
return extension_loaded('redis');
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cache/Handlers/FileHandler.php | system/Cache/Handlers/FileHandler.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\Cache\Handlers;
use CodeIgniter\Cache\Exceptions\CacheException;
use CodeIgniter\I18n\Time;
use Config\Cache;
use Throwable;
/**
* File system cache handler
*
* @see \CodeIgniter\Cache\Handlers\FileHandlerTest
*/
class FileHandler extends BaseHandler
{
/**
* Maximum key length.
*/
public const MAX_KEY_LENGTH = 255;
/**
* Where to store cached files on the disk.
*
* @var string
*/
protected $path;
/**
* Mode for the stored files.
* Must be chmod-safe (octal).
*
* @var int
*
* @see https://www.php.net/manual/en/function.chmod.php
*/
protected $mode;
/**
* Note: Use `CacheFactory::getHandler()` to instantiate.
*
* @throws CacheException
*/
public function __construct(Cache $config)
{
$options = [
...['storePath' => WRITEPATH . 'cache', 'mode' => 0640],
...$config->file,
];
$this->path = $options['storePath'] !== '' ? $options['storePath'] : WRITEPATH . 'cache';
$this->path = rtrim($this->path, '\\/') . '/';
if (! is_really_writable($this->path)) {
throw CacheException::forUnableToWrite($this->path);
}
$this->mode = $options['mode'];
$this->prefix = $config->prefix;
helper('filesystem');
}
/**
* {@inheritDoc}
*/
public function initialize()
{
}
/**
* {@inheritDoc}
*/
public function get(string $key)
{
$key = static::validateKey($key, $this->prefix);
$data = $this->getItem($key);
return is_array($data) ? $data['data'] : null;
}
/**
* {@inheritDoc}
*/
public function save(string $key, $value, int $ttl = 60)
{
$key = static::validateKey($key, $this->prefix);
$contents = [
'time' => Time::now()->getTimestamp(),
'ttl' => $ttl,
'data' => $value,
];
if (write_file($this->path . $key, serialize($contents))) {
try {
chmod($this->path . $key, $this->mode);
// @codeCoverageIgnoreStart
} catch (Throwable $e) {
log_message('debug', 'Failed to set mode on cache file: ' . $e);
// @codeCoverageIgnoreEnd
}
return true;
}
return false;
}
/**
* {@inheritDoc}
*/
public function delete(string $key)
{
$key = static::validateKey($key, $this->prefix);
return is_file($this->path . $key) && unlink($this->path . $key);
}
/**
* {@inheritDoc}
*
* @return int
*/
public function deleteMatching(string $pattern)
{
$deleted = 0;
foreach (glob($this->path . $pattern, GLOB_NOSORT) as $filename) {
if (is_file($filename) && @unlink($filename)) {
$deleted++;
}
}
return $deleted;
}
/**
* {@inheritDoc}
*/
public function increment(string $key, int $offset = 1)
{
$prefixedKey = static::validateKey($key, $this->prefix);
$tmp = $this->getItem($prefixedKey);
if ($tmp === false) {
$tmp = ['data' => 0, 'ttl' => 60];
}
['data' => $value, 'ttl' => $ttl] = $tmp;
if (! is_int($value)) {
return false;
}
$value += $offset;
return $this->save($key, $value, $ttl) ? $value : false;
}
/**
* {@inheritDoc}
*/
public function decrement(string $key, int $offset = 1)
{
return $this->increment($key, -$offset);
}
/**
* {@inheritDoc}
*/
public function clean()
{
return delete_files($this->path, false, true);
}
/**
* {@inheritDoc}
*/
public function getCacheInfo()
{
return get_dir_file_info($this->path);
}
/**
* {@inheritDoc}
*/
public function getMetaData(string $key)
{
$key = static::validateKey($key, $this->prefix);
if (false === $data = $this->getItem($key)) {
return false; // @TODO This will return null in a future release
}
return [
'expire' => $data['ttl'] > 0 ? $data['time'] + $data['ttl'] : null,
'mtime' => filemtime($this->path . $key),
'data' => $data['data'],
];
}
/**
* {@inheritDoc}
*/
public function isSupported(): bool
{
return is_writable($this->path);
}
/**
* Does the heavy lifting of actually retrieving the file and
* verifying its age.
*
* @return array{data: mixed, ttl: int, time: int}|false
*/
protected function getItem(string $filename)
{
if (! is_file($this->path . $filename)) {
return false;
}
$content = @file_get_contents($this->path . $filename);
if ($content === false) {
return false;
}
try {
$data = unserialize($content);
} catch (Throwable) {
return false;
}
if (! is_array($data)) {
return false;
}
if (! isset($data['ttl']) || ! is_int($data['ttl'])) {
return false;
}
if (! isset($data['time']) || ! is_int($data['time'])) {
return false;
}
if ($data['ttl'] > 0 && Time::now()->getTimestamp() > $data['time'] + $data['ttl']) {
@unlink($this->path . $filename);
return false;
}
return $data;
}
/**
* Writes a file to disk, or returns false if not successful.
*
* @deprecated 4.6.1 Use `write_file()` instead.
*
* @param string $path
* @param string $data
* @param string $mode
*
* @return bool
*/
protected function writeFile($path, $data, $mode = 'wb')
{
if (($fp = @fopen($path, $mode)) === false) {
return false;
}
flock($fp, LOCK_EX);
$result = 0;
for ($written = 0, $length = strlen($data); $written < $length; $written += $result) {
if (($result = fwrite($fp, substr($data, $written))) === false) {
break;
}
}
flock($fp, LOCK_UN);
fclose($fp);
return is_int($result);
}
/**
* Deletes all files contained in the supplied directory path.
* Files must be writable or owned by the system in order to be deleted.
* If the second parameter is set to TRUE, any directories contained
* within the supplied base directory will be nuked as well.
*
* @deprecated 4.6.1 Use `delete_files()` instead.
*
* @param string $path File path
* @param bool $delDir Whether to delete any directories found in the path
* @param bool $htdocs Whether to skip deleting .htaccess and index page files
* @param int $_level Current directory depth level (default: 0; internal use only)
*/
protected function deleteFiles(string $path, bool $delDir = false, bool $htdocs = false, int $_level = 0): bool
{
// Trim the trailing slash
$path = rtrim($path, '/\\');
if (! $currentDir = @opendir($path)) {
return false;
}
while (false !== ($filename = @readdir($currentDir))) {
if ($filename !== '.' && $filename !== '..') {
if (is_dir($path . DIRECTORY_SEPARATOR . $filename) && $filename[0] !== '.') {
$this->deleteFiles($path . DIRECTORY_SEPARATOR . $filename, $delDir, $htdocs, $_level + 1);
} elseif (! $htdocs || preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename) !== 1) {
@unlink($path . DIRECTORY_SEPARATOR . $filename);
}
}
}
closedir($currentDir);
return ($delDir && $_level > 0) ? @rmdir($path) : true;
}
/**
* Reads the specified directory and builds an array containing the filenames,
* filesize, dates, and permissions
*
* Any sub-folders contained within the specified path are read as well.
*
* @deprecated 4.6.1 Use `get_dir_file_info()` instead.
*
* @param string $sourceDir Path to source
* @param bool $topLevelOnly Look only at the top level directory specified?
* @param bool $_recursion Internal variable to determine recursion status - do not use in calls
*
* @return array<string, array{
* name: string,
* server_path: string,
* size: int,
* date: int,
* relative_path: string,
* }>|false
*/
protected function getDirFileInfo(string $sourceDir, bool $topLevelOnly = true, bool $_recursion = false)
{
static $filedata = [];
$relativePath = $sourceDir;
$filePointer = @opendir($sourceDir);
if (! is_bool($filePointer)) {
// reset the array and make sure $sourceDir has a trailing slash on the initial call
if ($_recursion === false) {
$filedata = [];
$resolvedSrc = realpath($sourceDir);
$resolvedSrc = $resolvedSrc === false ? $sourceDir : $resolvedSrc;
$sourceDir = rtrim($resolvedSrc, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
}
// Used to be foreach (scandir($sourceDir, 1) as $file), but scandir() is simply not as fast
while (false !== $file = readdir($filePointer)) {
if (is_dir($sourceDir . $file) && $file[0] !== '.' && $topLevelOnly === false) {
$this->getDirFileInfo($sourceDir . $file . DIRECTORY_SEPARATOR, $topLevelOnly, true);
} elseif (! is_dir($sourceDir . $file) && $file[0] !== '.') {
$filedata[$file] = $this->getFileInfo($sourceDir . $file);
$filedata[$file]['relative_path'] = $relativePath;
}
}
closedir($filePointer);
return $filedata;
}
return false;
}
/**
* Given a file and path, returns the name, path, size, date modified
* Second parameter allows you to explicitly declare what information you want returned
* Options are: name, server_path, size, date, readable, writable, executable, fileperms
* Returns FALSE if the file cannot be found.
*
* @deprecated 4.6.1 Use `get_file_info()` instead.
*
* @param string $file Path to file
* @param list<string>|string $returnedValues Array or comma separated string of information returned
*
* @return array{
* name?: string,
* server_path?: string,
* size?: int,
* date?: int,
* readable?: bool,
* writable?: bool,
* executable?: bool,
* fileperms?: int
* }|false
*/
protected function getFileInfo(string $file, $returnedValues = ['name', 'server_path', 'size', 'date'])
{
if (! is_file($file)) {
return false;
}
if (is_string($returnedValues)) {
$returnedValues = explode(',', $returnedValues);
}
$fileInfo = [];
foreach ($returnedValues as $key) {
switch ($key) {
case 'name':
$fileInfo['name'] = basename($file);
break;
case 'server_path':
$fileInfo['server_path'] = $file;
break;
case 'size':
$fileInfo['size'] = filesize($file);
break;
case 'date':
$fileInfo['date'] = filemtime($file);
break;
case 'readable':
$fileInfo['readable'] = is_readable($file);
break;
case 'writable':
$fileInfo['writable'] = is_writable($file);
break;
case 'executable':
$fileInfo['executable'] = is_executable($file);
break;
case 'fileperms':
$fileInfo['fileperms'] = fileperms($file);
break;
}
}
return $fileInfo;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cache/Handlers/WincacheHandler.php | system/Cache/Handlers/WincacheHandler.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\Cache\Handlers;
use CodeIgniter\Exceptions\BadMethodCallException;
use CodeIgniter\I18n\Time;
use Config\Cache;
/**
* Cache handler for WinCache from Microsoft & IIS.
*
* @codeCoverageIgnore
*/
class WincacheHandler extends BaseHandler
{
/**
* Note: Use `CacheFactory::getHandler()` to instantiate.
*/
public function __construct(Cache $config)
{
$this->prefix = $config->prefix;
}
/**
* {@inheritDoc}
*/
public function initialize()
{
}
/**
* {@inheritDoc}
*/
public function get(string $key)
{
$key = static::validateKey($key, $this->prefix);
$success = false;
$data = wincache_ucache_get($key, $success);
// Success returned by reference from wincache_ucache_get()
return $success ? $data : null;
}
/**
* {@inheritDoc}
*/
public function save(string $key, $value, int $ttl = 60)
{
$key = static::validateKey($key, $this->prefix);
return wincache_ucache_set($key, $value, $ttl);
}
/**
* {@inheritDoc}
*/
public function delete(string $key)
{
$key = static::validateKey($key, $this->prefix);
return wincache_ucache_delete($key);
}
/**
* {@inheritDoc}
*
* @return never
*/
public function deleteMatching(string $pattern)
{
throw new BadMethodCallException('The deleteMatching method is not implemented for Wincache. You must select File, Redis or Predis handlers to use it.');
}
/**
* {@inheritDoc}
*/
public function increment(string $key, int $offset = 1)
{
$key = static::validateKey($key, $this->prefix);
return wincache_ucache_inc($key, $offset);
}
/**
* {@inheritDoc}
*/
public function decrement(string $key, int $offset = 1)
{
$key = static::validateKey($key, $this->prefix);
return wincache_ucache_dec($key, $offset);
}
/**
* {@inheritDoc}
*/
public function clean()
{
return wincache_ucache_clear();
}
/**
* {@inheritDoc}
*/
public function getCacheInfo()
{
return wincache_ucache_info(true);
}
/**
* {@inheritDoc}
*/
public function getMetaData(string $key)
{
$key = static::validateKey($key, $this->prefix);
if ($stored = wincache_ucache_info(false, $key)) {
$age = $stored['ucache_entries'][1]['age_seconds'];
$ttl = $stored['ucache_entries'][1]['ttl_seconds'];
$hitcount = $stored['ucache_entries'][1]['hitcount'];
return [
'expire' => $ttl > 0 ? Time::now()->getTimestamp() + $ttl : null,
'hitcount' => $hitcount,
'age' => $age,
'ttl' => $ttl,
];
}
return false; // @TODO This will return null in a future release
}
/**
* {@inheritDoc}
*/
public function isSupported(): bool
{
return extension_loaded('wincache') && ini_get('wincache.ucenabled');
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cache/Handlers/BaseHandler.php | system/Cache/Handlers/BaseHandler.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\Cache\Handlers;
use Closure;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\Exceptions\BadMethodCallException;
use CodeIgniter\Exceptions\InvalidArgumentException;
use Config\Cache;
use Exception;
/**
* Base class for cache handling
*
* @see \CodeIgniter\Cache\Handlers\BaseHandlerTest
*/
abstract class BaseHandler implements CacheInterface
{
/**
* Reserved characters that cannot be used in a key or tag. May be overridden by the config.
* From https://github.com/symfony/cache-contracts/blob/c0446463729b89dd4fa62e9aeecc80287323615d/ItemInterface.php#L43
*
* @deprecated in favor of the Cache config
*/
public const RESERVED_CHARACTERS = '{}()/\@:';
/**
* Maximum key length.
*/
public const MAX_KEY_LENGTH = PHP_INT_MAX;
/**
* Prefix to apply to cache keys.
* May not be used by all handlers.
*
* @var string
*/
protected $prefix;
/**
* Validates a cache key according to PSR-6.
* Keys that exceed MAX_KEY_LENGTH are hashed.
* From https://github.com/symfony/cache/blob/7b024c6726af21fd4984ac8d1eae2b9f3d90de88/CacheItem.php#L158
*
* @param mixed $key The key to validate
* @param string $prefix Optional prefix to include in length calculations
*
* @throws InvalidArgumentException When $key is not valid
*/
public static function validateKey($key, $prefix = ''): string
{
if (! is_string($key)) {
throw new InvalidArgumentException('Cache key must be a string');
}
if ($key === '') {
throw new InvalidArgumentException('Cache key cannot be empty.');
}
$reserved = config(Cache::class)->reservedCharacters;
if ($reserved !== '' && strpbrk($key, $reserved) !== false) {
throw new InvalidArgumentException('Cache key contains reserved characters ' . $reserved);
}
// If the key with prefix exceeds the length then return the hashed version
return strlen($prefix . $key) > static::MAX_KEY_LENGTH ? $prefix . md5($key) : $prefix . $key;
}
/**
* Get an item from the cache, or execute the given Closure and store the result.
*
* @param string $key Cache item name
* @param int $ttl Time to live
* @param Closure(): mixed $callback Callback return value
*
* @return mixed
*/
public function remember(string $key, int $ttl, Closure $callback)
{
$value = $this->get($key);
if ($value !== null) {
return $value;
}
$this->save($key, $value = $callback(), $ttl);
return $value;
}
/**
* Deletes items from the cache store matching a given pattern.
*
* @param string $pattern Cache items glob-style pattern
*
* @return int
*
* @throws Exception
*/
public function deleteMatching(string $pattern)
{
throw new BadMethodCallException('The deleteMatching method is not implemented.');
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cache/Handlers/MemcachedHandler.php | system/Cache/Handlers/MemcachedHandler.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\Cache\Handlers;
use CodeIgniter\Exceptions\BadMethodCallException;
use CodeIgniter\Exceptions\CriticalError;
use CodeIgniter\I18n\Time;
use Config\Cache;
use Exception;
use Memcache;
use Memcached;
/**
* Mamcached cache handler
*
* @see \CodeIgniter\Cache\Handlers\MemcachedHandlerTest
*/
class MemcachedHandler extends BaseHandler
{
/**
* The memcached object
*
* @var Memcache|Memcached
*/
protected $memcached;
/**
* Memcached Configuration
*
* @var array{host: string, port: int, weight: int, raw: bool}
*/
protected $config = [
'host' => '127.0.0.1',
'port' => 11211,
'weight' => 1,
'raw' => false,
];
/**
* Note: Use `CacheFactory::getHandler()` to instantiate.
*/
public function __construct(Cache $config)
{
$this->prefix = $config->prefix;
$this->config = array_merge($this->config, $config->memcached);
}
/**
* Closes the connection to Memcache(d) if present.
*/
public function __destruct()
{
if ($this->memcached instanceof Memcached) {
$this->memcached->quit();
} elseif ($this->memcached instanceof Memcache) {
$this->memcached->close();
}
}
/**
* {@inheritDoc}
*/
public function initialize()
{
try {
if (class_exists(Memcached::class)) {
$this->memcached = new Memcached();
if ($this->config['raw']) {
$this->memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
}
$this->memcached->addServer(
$this->config['host'],
$this->config['port'],
$this->config['weight'],
);
$stats = $this->memcached->getStats();
// $stats should be an associate array with a key in the format of host:port.
// If it doesn't have the key, we know the server is not working as expected.
if (! is_array($stats) || ! isset($stats[$this->config['host'] . ':' . $this->config['port']])) {
throw new CriticalError('Cache: Memcached connection failed.');
}
} elseif (class_exists(Memcache::class)) {
$this->memcached = new Memcache();
if (! $this->memcached->connect($this->config['host'], $this->config['port'])) {
throw new CriticalError('Cache: Memcache connection failed.');
}
$this->memcached->addServer(
$this->config['host'],
$this->config['port'],
true,
$this->config['weight'],
);
} else {
throw new CriticalError('Cache: Not support Memcache(d) extension.');
}
} catch (Exception $e) {
throw new CriticalError('Cache: Memcache(d) connection refused (' . $e->getMessage() . ').');
}
}
/**
* {@inheritDoc}
*/
public function get(string $key)
{
$data = [];
$key = static::validateKey($key, $this->prefix);
if ($this->memcached instanceof Memcached) {
$data = $this->memcached->get($key);
// check for unmatched key
if ($this->memcached->getResultCode() === Memcached::RES_NOTFOUND) {
return null;
}
} elseif ($this->memcached instanceof Memcache) {
$flags = false;
$data = $this->memcached->get($key, $flags);
// check for unmatched key (i.e. $flags is untouched)
if ($flags === false) {
return null;
}
}
return is_array($data) ? $data[0] : $data;
}
/**
* {@inheritDoc}
*/
public function save(string $key, $value, int $ttl = 60)
{
$key = static::validateKey($key, $this->prefix);
if (! $this->config['raw']) {
$value = [
$value,
Time::now()->getTimestamp(),
$ttl,
];
}
if ($this->memcached instanceof Memcached) {
return $this->memcached->set($key, $value, $ttl);
}
if ($this->memcached instanceof Memcache) {
return $this->memcached->set($key, $value, 0, $ttl);
}
return false;
}
/**
* {@inheritDoc}
*/
public function delete(string $key)
{
$key = static::validateKey($key, $this->prefix);
return $this->memcached->delete($key);
}
/**
* {@inheritDoc}
*
* @return never
*/
public function deleteMatching(string $pattern)
{
throw new BadMethodCallException('The deleteMatching method is not implemented for Memcached. You must select File, Redis or Predis handlers to use it.');
}
/**
* {@inheritDoc}
*/
public function increment(string $key, int $offset = 1)
{
if (! $this->config['raw']) {
return false;
}
$key = static::validateKey($key, $this->prefix);
return $this->memcached->increment($key, $offset, $offset, 60);
}
/**
* {@inheritDoc}
*/
public function decrement(string $key, int $offset = 1)
{
if (! $this->config['raw']) {
return false;
}
$key = static::validateKey($key, $this->prefix);
// FIXME: third parameter isn't other handler actions.
return $this->memcached->decrement($key, $offset, $offset, 60);
}
/**
* {@inheritDoc}
*/
public function clean()
{
return $this->memcached->flush();
}
/**
* {@inheritDoc}
*/
public function getCacheInfo()
{
return $this->memcached->getStats();
}
/**
* {@inheritDoc}
*/
public function getMetaData(string $key)
{
$key = static::validateKey($key, $this->prefix);
$stored = $this->memcached->get($key);
// if not an array, don't try to count for PHP7.2
if (! is_array($stored) || count($stored) !== 3) {
return false; // @TODO This will return null in a future release
}
[$data, $time, $limit] = $stored;
return [
'expire' => $limit > 0 ? $time + $limit : null,
'mtime' => $time,
'data' => $data,
];
}
/**
* {@inheritDoc}
*/
public function isSupported(): bool
{
return extension_loaded('memcached') || extension_loaded('memcache');
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Config/Routing.php | system/Config/Routing.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\Config;
/**
* Routing configuration
*/
class Routing extends BaseConfig
{
/**
* For Defined Routes.
* An array of files that contain route definitions.
* Route files are read in order, with the first match
* found taking precedence.
*
* Default: APPPATH . 'Config/Routes.php'
*
* @var list<string>
*/
public array $routeFiles = [
APPPATH . 'Config/Routes.php',
];
/**
* For Defined Routes and Auto Routing.
* The default namespace to use for Controllers when no other
* namespace has been specified.
*
* Default: 'App\Controllers'
*/
public string $defaultNamespace = 'App\Controllers';
/**
* For Auto Routing.
* The default controller to use when no other controller has been
* specified.
*
* Default: 'Home'
*/
public string $defaultController = 'Home';
/**
* For Defined Routes and Auto Routing.
* The default method to call on the controller when no other
* method has been set in the route.
*
* Default: 'index'
*/
public string $defaultMethod = 'index';
/**
* For Auto Routing.
* Whether to translate dashes in URIs for controller/method to underscores.
* Primarily useful when using the auto-routing.
*
* Default: false
*/
public bool $translateURIDashes = false;
/**
* Sets the class/method that should be called if routing doesn't
* find a match. It can be the controller/method name like: Users::index
*
* This setting is passed to the Router class and handled there.
*
* If you want to use a closure, you will have to set it in the
* routes file by calling:
*
* $routes->set404Override(function() {
* // Do something here
* });
*
* Example:
* public $override404 = 'App\Errors::show404';
*/
public ?string $override404 = null;
/**
* If TRUE, the system will attempt to match the URI against
* Controllers by matching each segment against folders/files
* in APPPATH/Controllers, when a match wasn't found against
* defined routes.
*
* If FALSE, will stop searching and do NO automatic routing.
*/
public bool $autoRoute = false;
/**
* For Defined Routes.
* If TRUE, will enable the use of the 'prioritize' option
* when defining routes.
*
* Default: false
*/
public bool $prioritize = false;
/**
* For Defined Routes.
* If TRUE, matched multiple URI segments will be passed as one parameter.
*
* Default: false
*/
public bool $multipleSegmentsOneParam = false;
/**
* For Auto Routing (Improved).
* Map of URI segments and namespaces.
*
* The key is the first URI segment. The value is the controller namespace.
* E.g.,
* [
* 'blog' => 'Acme\Blog\Controllers',
* ]
*
* @var array<string, string>
*/
public array $moduleRoutes = [];
/**
* For Auto Routing (Improved).
* Whether to translate dashes in URIs for controller/method to CamelCase.
* E.g., blog-controller -> BlogController
*
* If you enable this, $translateURIDashes is ignored.
*
* Default: false
*/
public bool $translateUriToCamelCase = false;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Config/ForeignCharacters.php | system/Config/ForeignCharacters.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\Config;
/**
* Describes foreign characters for transliteration with the text helper.
*/
class ForeignCharacters
{
/**
* The list of foreign characters.
*
* @var array<string, string>
*/
public $characterList = [
'/ä|æ|ǽ/' => 'ae',
'/ö|œ/' => 'oe',
'/ü/' => 'ue',
'/Ä/' => 'Ae',
'/Ü/' => 'Ue',
'/Ö/' => 'Oe',
'/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ|Α|Ά|Ả|Ạ|Ầ|Ẫ|Ẩ|Ậ|Ằ|Ắ|Ẵ|Ẳ|Ặ|А/' => 'A',
'/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª|α|ά|ả|ạ|ầ|ấ|ẫ|ẩ|ậ|ằ|ắ|ẵ|ẳ|ặ|а/' => 'a',
'/Б/' => 'B',
'/б/' => 'b',
'/Ç|Ć|Ĉ|Ċ|Č/' => 'C',
'/ç|ć|ĉ|ċ|č/' => 'c',
'/Д/' => 'D',
'/д/' => 'd',
'/Ð|Ď|Đ|Δ/' => 'Dj',
'/ð|ď|đ|δ/' => 'dj',
'/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě|Ε|Έ|Ẽ|Ẻ|Ẹ|Ề|Ế|Ễ|Ể|Ệ|Е|Э/' => 'E',
'/è|é|ê|ë|ē|ĕ|ė|ę|ě|έ|ε|ẽ|ẻ|ẹ|ề|ế|ễ|ể|ệ|е|э/' => 'e',
'/Ф/' => 'F',
'/ф/' => 'f',
'/Ĝ|Ğ|Ġ|Ģ|Γ|Г|Ґ/' => 'G',
'/ĝ|ğ|ġ|ģ|γ|г|ґ/' => 'g',
'/Ĥ|Ħ/' => 'H',
'/ĥ|ħ/' => 'h',
'/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ|Η|Ή|Ί|Ι|Ϊ|Ỉ|Ị|И|Ы/' => 'I',
'/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı|η|ή|ί|ι|ϊ|ỉ|ị|и|ы|ї/' => 'i',
'/Ĵ/' => 'J',
'/ĵ/' => 'j',
'/Ķ|Κ|К/' => 'K',
'/ķ|κ|к/' => 'k',
'/Ĺ|Ļ|Ľ|Ŀ|Ł|Λ|Л/' => 'L',
'/ĺ|ļ|ľ|ŀ|ł|λ|л/' => 'l',
'/М/' => 'M',
'/м/' => 'm',
'/Ñ|Ń|Ņ|Ň|Ν|Н/' => 'N',
'/ñ|ń|ņ|ň|ʼn|ν|н/' => 'n',
'/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ|Ο|Ό|Ω|Ώ|Ỏ|Ọ|Ồ|Ố|Ỗ|Ổ|Ộ|Ờ|Ớ|Ỡ|Ở|Ợ|О/' => 'O',
'/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º|ο|ό|ω|ώ|ỏ|ọ|ồ|ố|ỗ|ổ|ộ|ờ|ớ|ỡ|ở|ợ|о/' => 'o',
'/П/' => 'P',
'/п/' => 'p',
'/Ŕ|Ŗ|Ř|Ρ|Р/' => 'R',
'/ŕ|ŗ|ř|ρ|р/' => 'r',
'/Ś|Ŝ|Ş|Ș|Š|Σ|С/' => 'S',
'/ś|ŝ|ş|ș|š|ſ|σ|ς|с/' => 's',
'/Ț|Ţ|Ť|Ŧ|τ|Т/' => 'T',
'/ț|ţ|ť|ŧ|т/' => 't',
'/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ|Ũ|Ủ|Ụ|Ừ|Ứ|Ữ|Ử|Ự|У/' => 'U',
'/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ|υ|ύ|ϋ|ủ|ụ|ừ|ứ|ữ|ử|ự|у/' => 'u',
'/Ƴ|Ɏ|Ỵ|Ẏ|Ӳ|Ӯ|Ў|Ý|Ÿ|Ŷ|Υ|Ύ|Ϋ|Ỳ|Ỹ|Ỷ|Ỵ|Й/' => 'Y',
'/ẙ|ʏ|ƴ|ɏ|ỵ|ẏ|ӳ|ӯ|ў|ý|ÿ|ŷ|ỳ|ỹ|ỷ|ỵ|й/' => 'y',
'/В/' => 'V',
'/в/' => 'v',
'/Ŵ/' => 'W',
'/ŵ/' => 'w',
'/Ź|Ż|Ž|Ζ|З/' => 'Z',
'/ź|ż|ž|ζ|з/' => 'z',
'/Æ|Ǽ/' => 'AE',
'/ß/' => 'ss',
'/IJ/' => 'IJ',
'/ij/' => 'ij',
'/Œ/' => 'OE',
'/ƒ/' => 'f',
'/ξ/' => 'ks',
'/π/' => 'p',
'/β/' => 'v',
'/μ/' => 'm',
'/ψ/' => 'ps',
'/Ё/' => 'Yo',
'/ё/' => 'yo',
'/Є/' => 'Ye',
'/є/' => 'ye',
'/Ї/' => 'Yi',
'/Ж/' => 'Zh',
'/ж/' => 'zh',
'/Х/' => 'Kh',
'/х/' => 'kh',
'/Ц/' => 'Ts',
'/ц/' => 'ts',
'/Ч/' => 'Ch',
'/ч/' => 'ch',
'/Ш/' => 'Sh',
'/ш/' => 'sh',
'/Щ/' => 'Shch',
'/щ/' => 'shch',
'/Ъ|ъ|Ь|ь/' => '',
'/Ю/' => 'Yu',
'/ю/' => 'yu',
'/Я/' => 'Ya',
'/я/' => 'ya',
];
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Config/AutoloadConfig.php | system/Config/AutoloadConfig.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\Config;
use Laminas\Escaper\Escaper;
use Laminas\Escaper\EscaperInterface;
use Laminas\Escaper\Exception\ExceptionInterface;
use Laminas\Escaper\Exception\InvalidArgumentException as EscaperInvalidArgumentException;
use Laminas\Escaper\Exception\RuntimeException;
use Psr\Log\AbstractLogger;
use Psr\Log\InvalidArgumentException;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Psr\Log\LoggerTrait;
use Psr\Log\LogLevel;
use Psr\Log\NullLogger;
/**
* AUTOLOADER CONFIGURATION
*
* This file defines the namespaces and class maps so the Autoloader
* can find the files as needed.
*/
class AutoloadConfig
{
/**
* -------------------------------------------------------------------
* Namespaces
* -------------------------------------------------------------------
* This maps the locations of any namespaces in your application to
* their location on the file system. These are used by the autoloader
* to locate files the first time they have been instantiated.
*
* The '/app' and '/system' directories are already mapped for you.
* you may change the name of the 'App' namespace if you wish,
* but this should be done prior to creating any namespaced classes,
* else you will need to modify all of those classes for this to work.
*
* @var array<string, list<string>|string>
*/
public $psr4 = [];
/**
* -------------------------------------------------------------------
* Class Map
* -------------------------------------------------------------------
* The class map provides a map of class names and their exact
* location on the drive. Classes loaded in this manner will have
* slightly faster performance because they will not have to be
* searched for within one or more directories as they would if they
* were being autoloaded through a namespace.
*
* @var array<string, string>
*/
public $classmap = [];
/**
* -------------------------------------------------------------------
* Files
* -------------------------------------------------------------------
* The files array provides a list of paths to __non-class__ files
* that will be autoloaded. This can be useful for bootstrap operations
* or for loading functions.
*
* @var list<string>
*/
public $files = [];
/**
* -------------------------------------------------------------------
* Namespaces
* -------------------------------------------------------------------
* This maps the locations of any namespaces in your application to
* their location on the file system. These are used by the autoloader
* to locate files the first time they have been instantiated.
*
* Do not change the name of the CodeIgniter namespace or your application
* will break.
*
* @var array<string, string>
*/
protected $corePsr4 = [
'CodeIgniter' => SYSTEMPATH,
'Config' => APPPATH . 'Config',
];
/**
* -------------------------------------------------------------------
* Class Map
* -------------------------------------------------------------------
* The class map provides a map of class names and their exact
* location on the drive. Classes loaded in this manner will have
* slightly faster performance because they will not have to be
* searched for within one or more directories as they would if they
* were being autoloaded through a namespace.
*
* @var array<class-string, string>
*/
protected $coreClassmap = [
AbstractLogger::class => SYSTEMPATH . 'ThirdParty/PSR/Log/AbstractLogger.php',
InvalidArgumentException::class => SYSTEMPATH . 'ThirdParty/PSR/Log/InvalidArgumentException.php',
LoggerAwareInterface::class => SYSTEMPATH . 'ThirdParty/PSR/Log/LoggerAwareInterface.php',
LoggerAwareTrait::class => SYSTEMPATH . 'ThirdParty/PSR/Log/LoggerAwareTrait.php',
LoggerInterface::class => SYSTEMPATH . 'ThirdParty/PSR/Log/LoggerInterface.php',
LoggerTrait::class => SYSTEMPATH . 'ThirdParty/PSR/Log/LoggerTrait.php',
LogLevel::class => SYSTEMPATH . 'ThirdParty/PSR/Log/LogLevel.php',
NullLogger::class => SYSTEMPATH . 'ThirdParty/PSR/Log/NullLogger.php',
ExceptionInterface::class => SYSTEMPATH . 'ThirdParty/Escaper/Exception/ExceptionInterface.php',
EscaperInvalidArgumentException::class => SYSTEMPATH . 'ThirdParty/Escaper/Exception/InvalidArgumentException.php',
RuntimeException::class => SYSTEMPATH . 'ThirdParty/Escaper/Exception/RuntimeException.php',
EscaperInterface::class => SYSTEMPATH . 'ThirdParty/Escaper/EscaperInterface.php',
Escaper::class => SYSTEMPATH . 'ThirdParty/Escaper/Escaper.php',
];
/**
* -------------------------------------------------------------------
* Core Files
* -------------------------------------------------------------------
* List of files from the framework to be autoloaded early.
*
* @var array<int, string>
*/
protected $coreFiles = [];
/**
* Constructor.
*
* Merge the built-in and developer-configured psr4 and classmap,
* with preference to the developer ones.
*/
public function __construct()
{
if (isset($_SERVER['CI_ENVIRONMENT']) && $_SERVER['CI_ENVIRONMENT'] === 'testing') {
$this->psr4['Tests\Support'] = SUPPORTPATH;
$this->classmap['CodeIgniter\Log\TestLogger'] = SYSTEMPATH . 'Test/TestLogger.php';
$this->classmap['CIDatabaseTestCase'] = SYSTEMPATH . 'Test/CIDatabaseTestCase.php';
}
$this->psr4 = array_merge($this->corePsr4, $this->psr4);
$this->classmap = array_merge($this->coreClassmap, $this->classmap);
$this->files = [...$this->coreFiles, ...$this->files];
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Config/Filters.php | system/Config/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\Config;
use CodeIgniter\Filters\Cors;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\ForceHTTPS;
use CodeIgniter\Filters\Honeypot;
use CodeIgniter\Filters\InvalidChars;
use CodeIgniter\Filters\PageCache;
use CodeIgniter\Filters\PerformanceMetrics;
use CodeIgniter\Filters\SecureHeaders;
/**
* Filters configuration
*/
class Filters extends BaseConfig
{
/**
* Configures aliases for Filter classes to
* make reading things nicer and simpler.
*
* @var array<string, class-string|list<class-string>>
*
* [filter_name => classname]
* or [filter_name => [classname1, classname2, ...]]
*/
public array $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'cors' => Cors::class,
'forcehttps' => ForceHTTPS::class,
'pagecache' => PageCache::class,
'performance' => PerformanceMetrics::class,
];
/**
* List of special required filters.
*
* The filters listed here are special. They are applied before and after
* other kinds of filters, and always applied even if a route does not exist.
*
* Filters set by default provide framework functionality. If removed,
* those functions will no longer work.
*
* @see https://codeigniter.com/user_guide/incoming/filters.html#provided-filters
*
* @var array{before: list<string>, after: list<string>}
*/
public array $required = [
'before' => [
'forcehttps', // Force Global Secure Requests
'pagecache', // Web Page Caching
],
'after' => [
'pagecache', // Web Page Caching
'performance', // Performance Metrics
'toolbar', // Debug Toolbar
],
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* @var array{
* before: array<string, array{except: list<string>|string}>|list<string>,
* after: array<string, array{except: list<string>|string}>|list<string>
* }
*/
public array $globals = [
'before' => [
// 'honeypot',
// 'csrf',
// 'invalidchars',
],
'after' => [
// 'honeypot',
// 'secureheaders',
],
];
/**
* List of filter aliases that works on a
* particular HTTP method (GET, POST, etc.).
*
* Example:
* 'POST' => ['foo', 'bar']
*
* If you use this, you should disable auto-routing because auto-routing
* permits any HTTP method to access a controller. Accessing the controller
* with a method you don't expect could bypass the filter.
*
* @var array<string, list<string>>
*/
public array $methods = [];
/**
* List of filter aliases that should run on any
* before or after URI patterns.
*
* Example:
* 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
*
* @var array<string, array<string, list<string>>>
*/
public array $filters = [];
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Config/Factories.php | system/Config/Factories.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\Config;
use CodeIgniter\Autoloader\FileLocatorInterface;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Model;
/**
* Factories for creating instances.
*
* Factories allow dynamic loading of components by their path
* and name. The "shared instance" implementation provides a
* large performance boost and helps keep code clean of lengthy
* instantiation checks.
*
* @method static BaseConfig|null config(...$arguments)
* @method static Model|null models(string $alias, array $options = [], ?ConnectionInterface &$conn = null)
* @see \CodeIgniter\Config\FactoriesTest
*/
final class Factories
{
/**
* Store of component-specific options, usually
* from CodeIgniter\Config\Factory.
*
* @var array<string, array<string, bool|string|null>>
*/
private static array $options = [];
/**
* Explicit options for the Config
* component to prevent logic loops.
*
* @var array<string, bool|string|null>
*/
private static array $configOptions = [
'component' => 'config',
'path' => 'Config',
'instanceOf' => null,
'getShared' => true,
'preferApp' => true,
];
/**
* Mapping of class aliases to their true Fully Qualified Class Name (FQCN).
*
* Class aliases can be:
* - FQCN. E.g., 'App\Lib\SomeLib'
* - short classname. E.g., 'SomeLib'
* - short classname with sub-directories. E.g., 'Sub/SomeLib'
*
* [component => [alias => FQCN]]
*
* @var array<string, array<string, class-string>>
*/
private static array $aliases = [];
/**
* Store for instances of any component that
* has been requested as "shared".
*
* A multi-dimensional array with components as
* keys to the array of name-indexed instances.
*
* [component => [FQCN => instance]]
*
* @var array<string, array<class-string, object>>
*/
private static array $instances = [];
/**
* Whether the component instances are updated?
*
* @var array<string, true> [component => true]
*
* @internal For caching only
*/
private static array $updated = [];
/**
* Define the class to load. You can *override* the concrete class.
*
* @param string $component Lowercase, plural component name
* @param string $alias Class alias. See the $aliases property.
* @param class-string $classname FQCN to be loaded
*/
public static function define(string $component, string $alias, string $classname): void
{
$component = strtolower($component);
if (isset(self::$aliases[$component][$alias])) {
if (self::$aliases[$component][$alias] === $classname) {
return;
}
throw new InvalidArgumentException(
'Already defined in Factories: ' . $component . ' ' . $alias . ' -> ' . self::$aliases[$component][$alias],
);
}
if (! class_exists($classname)) {
throw new InvalidArgumentException('No such class: ' . $classname);
}
// Force a configuration to exist for this component.
// Otherwise, getOptions() will reset the component.
self::getOptions($component);
self::$aliases[$component][$alias] = $classname;
self::$updated[$component] = true;
}
/**
* Loads instances based on the method component name. Either
* creates a new instance or returns an existing shared instance.
*
* @return object|null
*/
public static function __callStatic(string $component, array $arguments)
{
$component = strtolower($component);
// First argument is the class alias, second is options
$alias = trim(array_shift($arguments), '\\ ');
$options = array_shift($arguments) ?? [];
// Determine the component-specific options
$options = array_merge(self::getOptions($component), $options);
if (! $options['getShared']) {
if (isset(self::$aliases[$options['component']][$alias])) {
$class = self::$aliases[$options['component']][$alias];
return new $class(...$arguments);
}
// Try to locate the class
$class = self::locateClass($options, $alias);
if ($class !== null) {
return new $class(...$arguments);
}
return null;
}
// Check for an existing definition
$instance = self::getDefinedInstance($options, $alias, $arguments);
if ($instance !== null) {
return $instance;
}
// Try to locate the class
if (($class = self::locateClass($options, $alias)) === null) {
return null;
}
self::createInstance($options['component'], $class, $arguments);
self::setAlias($options['component'], $alias, $class);
return self::$instances[$options['component']][$class];
}
/**
* Simple method to get the shared instance fast.
*/
public static function get(string $component, string $alias): ?object
{
if (isset(self::$aliases[$component][$alias])) {
$class = self::$aliases[$component][$alias];
if (isset(self::$instances[$component][$class])) {
return self::$instances[$component][$class];
}
}
return self::__callStatic($component, [$alias]);
}
/**
* Gets the defined instance. If not exists, creates new one.
*
* @return object|null
*/
private static function getDefinedInstance(array $options, string $alias, array $arguments)
{
// The alias is already defined.
if (isset(self::$aliases[$options['component']][$alias])) {
$class = self::$aliases[$options['component']][$alias];
// Need to verify if the shared instance matches the request
if (self::verifyInstanceOf($options, $class)) {
// Check for an existing instance
if (isset(self::$instances[$options['component']][$class])) {
return self::$instances[$options['component']][$class];
}
self::createInstance($options['component'], $class, $arguments);
return self::$instances[$options['component']][$class];
}
}
// Try to locate the class
if (($class = self::locateClass($options, $alias)) === null) {
return null;
}
// Check for an existing instance for the class
if (isset(self::$instances[$options['component']][$class])) {
self::setAlias($options['component'], $alias, $class);
return self::$instances[$options['component']][$class];
}
return null;
}
/**
* Creates the shared instance.
*/
private static function createInstance(string $component, string $class, array $arguments): void
{
self::$instances[$component][$class] = new $class(...$arguments);
self::$updated[$component] = true;
}
/**
* Sets alias
*/
private static function setAlias(string $component, string $alias, string $class): void
{
self::$aliases[$component][$alias] = $class;
self::$updated[$component] = true;
// If a short classname is specified, also register FQCN to share the instance.
if (! isset(self::$aliases[$component][$class]) && ! self::isNamespaced($alias)) {
self::$aliases[$component][$class] = $class;
}
}
/**
* Is the component Config?
*
* @param string $component Lowercase, plural component name
*/
private static function isConfig(string $component): bool
{
return $component === 'config';
}
/**
* Finds a component class
*
* @param array $options The array of component-specific directives
* @param string $alias Class alias. See the $aliases property.
*/
private static function locateClass(array $options, string $alias): ?string
{
// Check for low-hanging fruit
if (
class_exists($alias, false)
&& self::verifyPreferApp($options, $alias)
&& self::verifyInstanceOf($options, $alias)
) {
return $alias;
}
// Determine the relative class names we need
$basename = self::getBasename($alias);
$appname = self::isConfig($options['component'])
? 'Config\\' . $basename
: rtrim(APP_NAMESPACE, '\\') . '\\' . $options['path'] . '\\' . $basename;
// If an App version was requested then see if it verifies
if (
// preferApp is used only for no namespaced class.
! self::isNamespaced($alias)
&& $options['preferApp'] && class_exists($appname)
&& self::verifyInstanceOf($options, $alias)
) {
return $appname;
}
// If we have ruled out an App version and the class exists then try it
if (class_exists($alias) && self::verifyInstanceOf($options, $alias)) {
return $alias;
}
// Have to do this the hard way...
/** @var FileLocatorInterface */
$locator = service('locator');
// Check if the class alias was namespaced
if (self::isNamespaced($alias)) {
if (! $file = $locator->locateFile($alias, $options['path'])) {
return null;
}
$files = [$file];
}
// No namespace? Search for it
// Check all namespaces, prioritizing App and modules
elseif (($files = $locator->search($options['path'] . DIRECTORY_SEPARATOR . $alias)) === []) {
return null;
}
// Check all files for a valid class
foreach ($files as $file) {
$class = $locator->findQualifiedNameFromPath($file);
if ($class !== false && self::verifyInstanceOf($options, $class)) {
return $class;
}
}
return null;
}
/**
* Is the class alias namespaced or not?
*
* @param string $alias Class alias. See the $aliases property.
*/
private static function isNamespaced(string $alias): bool
{
return str_contains($alias, '\\');
}
/**
* Verifies that a class & config satisfy the "preferApp" option
*
* @param array $options The array of component-specific directives
* @param string $alias Class alias. See the $aliases property.
*/
private static function verifyPreferApp(array $options, string $alias): bool
{
// Anything without that restriction passes
if (! $options['preferApp']) {
return true;
}
// Special case for Config since its App namespace is actually \Config
if (self::isConfig($options['component'])) {
return str_starts_with($alias, 'Config');
}
return str_starts_with($alias, APP_NAMESPACE);
}
/**
* Verifies that a class & config satisfy the "instanceOf" option
*
* @param array $options The array of component-specific directives
* @param string $alias Class alias. See the $aliases property.
*/
private static function verifyInstanceOf(array $options, string $alias): bool
{
// Anything without that restriction passes
if (! $options['instanceOf']) {
return true;
}
return is_a($alias, $options['instanceOf'], true);
}
/**
* Returns the component-specific configuration
*
* @param string $component Lowercase, plural component name
*
* @return array<string, bool|string|null>
*
* @internal For testing only
* @testTag
*/
public static function getOptions(string $component): array
{
$component = strtolower($component);
// Check for a stored version
if (isset(self::$options[$component])) {
return self::$options[$component];
}
$values = self::isConfig($component)
// Handle Config as a special case to prevent logic loops
? self::$configOptions
// Load values from the best Factory configuration (will include Registrars)
: config('Factory')->{$component} ?? [];
// The setOptions() reset the component. So getOptions() may reset
// the component.
return self::setOptions($component, $values);
}
/**
* Normalizes, stores, and returns the configuration for a specific component
*
* @param string $component Lowercase, plural component name
* @param array $values option values
*
* @return array<string, bool|string|null> The result after applying defaults and normalization
*/
public static function setOptions(string $component, array $values): array
{
$component = strtolower($component);
// Allow the config to replace the component name, to support "aliases"
$values['component'] = strtolower($values['component'] ?? $component);
// Reset this component so instances can be rediscovered with the updated config
self::reset($values['component']);
// If no path was available then use the component
$values['path'] = trim($values['path'] ?? ucfirst($values['component']), '\\ ');
// Add defaults for any missing values
$values = array_merge(Factory::$default, $values);
// Store the result to the supplied name and potential alias
self::$options[$component] = $values;
self::$options[$values['component']] = $values;
return $values;
}
/**
* Resets the static arrays, optionally just for one component
*
* @param string|null $component Lowercase, plural component name
*
* @return void
*/
public static function reset(?string $component = null)
{
if ($component !== null) {
unset(
self::$options[$component],
self::$aliases[$component],
self::$instances[$component],
self::$updated[$component],
);
return;
}
self::$options = [];
self::$aliases = [];
self::$instances = [];
self::$updated = [];
}
/**
* Helper method for injecting mock instances
*
* @param string $component Lowercase, plural component name
* @param string $alias Class alias. See the $aliases property.
*
* @return void
*
* @internal For testing only
* @testTag
*/
public static function injectMock(string $component, string $alias, object $instance)
{
$component = strtolower($component);
// Force a configuration to exist for this component
self::getOptions($component);
$class = $instance::class;
self::$instances[$component][$class] = $instance;
self::$aliases[$component][$alias] = $class;
if (self::isConfig($component)) {
if (self::isNamespaced($alias)) {
self::$aliases[$component][self::getBasename($alias)] = $class;
} else {
self::$aliases[$component]['Config\\' . $alias] = $class;
}
}
}
/**
* Gets a basename from a class alias, namespaced or not.
*
* @internal For testing only
* @testTag
*/
public static function getBasename(string $alias): string
{
// Determine the basename
if ($basename = strrchr($alias, '\\')) {
return substr($basename, 1);
}
return $alias;
}
/**
* Gets component data for caching.
*
* @return array{
* options: array<string, bool|string|null>,
* aliases: array<string, class-string>,
* instances: array<class-string, object>,
* }
*
* @internal For caching only
*/
public static function getComponentInstances(string $component): array
{
if (! isset(self::$aliases[$component])) {
return [
'options' => [],
'aliases' => [],
'instances' => [],
];
}
return [
'options' => self::$options[$component],
'aliases' => self::$aliases[$component],
'instances' => self::$instances[$component],
];
}
/**
* Sets component data
*
* @internal For caching only
*/
public static function setComponentInstances(string $component, array $data): void
{
self::$options[$component] = $data['options'];
self::$aliases[$component] = $data['aliases'];
self::$instances[$component] = $data['instances'];
unset(self::$updated[$component]);
}
/**
* Whether the component instances are updated?
*
* @internal For caching only
*/
public static function isUpdated(string $component): bool
{
return isset(self::$updated[$component]);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Config/DotEnv.php | system/Config/DotEnv.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\Config;
use CodeIgniter\Exceptions\InvalidArgumentException;
/**
* Environment-specific configuration
*
* @see \CodeIgniter\Config\DotEnvTest
*/
class DotEnv
{
/**
* The directory where the .env file can be located.
*
* @var string
*/
protected $path;
/**
* Builds the path to our file.
*/
public function __construct(string $path, string $file = '.env')
{
$this->path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $file;
}
/**
* The main entry point, will load the .env file and process it
* so that we end up with all settings in the PHP environment vars
* (i.e. getenv(), $_ENV, and $_SERVER)
*/
public function load(): bool
{
$vars = $this->parse();
return $vars !== null;
}
/**
* Parse the .env file into an array of key => value
*/
public function parse(): ?array
{
// We don't want to enforce the presence of a .env file, they should be optional.
if (! is_file($this->path)) {
return null;
}
// Ensure the file is readable
if (! is_readable($this->path)) {
throw new InvalidArgumentException("The .env file is not readable: {$this->path}");
}
$vars = [];
$lines = file($this->path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
// Is it a comment?
if (str_starts_with(trim($line), '#')) {
continue;
}
// If there is an equal sign, then we know we are assigning a variable.
if (str_contains($line, '=')) {
[$name, $value] = $this->normaliseVariable($line);
$vars[$name] = $value;
$this->setVariable($name, $value);
}
}
return $vars;
}
/**
* Sets the variable into the environment. Will parse the string
* first to look for {name}={value} pattern, ensure that nested
* variables are handled, and strip it of single and double quotes.
*
* @return void
*/
protected function setVariable(string $name, string $value = '')
{
if (getenv($name, true) === false) {
putenv("{$name}={$value}");
}
if (empty($_ENV[$name])) {
$_ENV[$name] = $value;
}
if (empty($_SERVER[$name])) {
$_SERVER[$name] = $value;
}
}
/**
* Parses for assignment, cleans the $name and $value, and ensures
* that nested variables are handled.
*/
public function normaliseVariable(string $name, string $value = ''): array
{
// Split our compound string into its parts.
if (str_contains($name, '=')) {
[$name, $value] = explode('=', $name, 2);
}
$name = trim($name);
$value = trim($value);
// Sanitize the name
$name = preg_replace('/^export[ \t]++(\S+)/', '$1', $name);
$name = str_replace(['\'', '"'], '', $name);
// Sanitize the value
$value = $this->sanitizeValue($value);
$value = $this->resolveNestedVariables($value);
return [$name, $value];
}
/**
* Strips quotes from the environment variable value.
*
* This was borrowed from the excellent phpdotenv with very few changes.
* https://github.com/vlucas/phpdotenv
*
* @throws InvalidArgumentException
*/
protected function sanitizeValue(string $value): string
{
if ($value === '') {
return $value;
}
// Does it begin with a quote?
if (strpbrk($value[0], '"\'') !== false) {
// value starts with a quote
$quote = $value[0];
$regexPattern = sprintf(
'/^
%1$s # match a quote at the start of the value
( # capturing sub-pattern used
(?: # we do not need to capture this
[^%1$s\\\\] # any character other than a quote or backslash
|\\\\\\\\ # or two backslashes together
|\\\\%1$s # or an escaped quote e.g \"
)* # as many characters that match the previous rules
) # end of the capturing sub-pattern
%1$s # and the closing quote
.*$ # and discard any string after the closing quote
/mx',
$quote,
);
$value = preg_replace($regexPattern, '$1', $value);
$value = str_replace("\\{$quote}", $quote, $value);
$value = str_replace('\\\\', '\\', $value);
} else {
$parts = explode(' #', $value, 2);
$value = trim($parts[0]);
// Unquoted values cannot contain whitespace
if (preg_match('/\s+/', $value) > 0) {
throw new InvalidArgumentException('.env values containing spaces must be surrounded by quotes.');
}
}
return $value;
}
/**
* Resolve the nested variables.
*
* Look for ${varname} patterns in the variable value and replace with an existing
* environment variable.
*
* This was borrowed from the excellent phpdotenv with very few changes.
* https://github.com/vlucas/phpdotenv
*/
protected function resolveNestedVariables(string $value): string
{
if (str_contains($value, '$')) {
$value = preg_replace_callback(
'/\${([a-zA-Z0-9_\.]+)}/',
function ($matchedPatterns) {
$nestedVariable = $this->getVariable($matchedPatterns[1]);
if ($nestedVariable === null) {
return $matchedPatterns[0];
}
return $nestedVariable;
},
$value,
);
}
return $value;
}
/**
* Search the different places for environment variables and return first value found.
*
* This was borrowed from the excellent phpdotenv with very few changes.
* https://github.com/vlucas/phpdotenv
*
* @return string|null
*/
protected function getVariable(string $name)
{
switch (true) {
case array_key_exists($name, $_ENV):
return $_ENV[$name];
case array_key_exists($name, $_SERVER):
return $_SERVER[$name];
default:
$value = getenv($name);
// switch getenv default to null
return $value === false ? null : $value;
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Config/BaseService.php | system/Config/BaseService.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\Config;
use CodeIgniter\Autoloader\Autoloader;
use CodeIgniter\Autoloader\FileLocator;
use CodeIgniter\Autoloader\FileLocatorCached;
use CodeIgniter\Autoloader\FileLocatorInterface;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\Cache\ResponseCache;
use CodeIgniter\CLI\Commands;
use CodeIgniter\CodeIgniter;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Database\MigrationRunner;
use CodeIgniter\Debug\Exceptions;
use CodeIgniter\Debug\Iterator;
use CodeIgniter\Debug\Timer;
use CodeIgniter\Debug\Toolbar;
use CodeIgniter\Email\Email;
use CodeIgniter\Encryption\EncrypterInterface;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Filters\Filters;
use CodeIgniter\Format\Format;
use CodeIgniter\Honeypot\Honeypot;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\ContentSecurityPolicy;
use CodeIgniter\HTTP\CURLRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Negotiate;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\Request;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\SiteURIFactory;
use CodeIgniter\HTTP\URI;
use CodeIgniter\Images\Handlers\BaseHandler;
use CodeIgniter\Language\Language;
use CodeIgniter\Log\Logger;
use CodeIgniter\Pager\Pager;
use CodeIgniter\Router\RouteCollection;
use CodeIgniter\Router\RouteCollectionInterface;
use CodeIgniter\Router\Router;
use CodeIgniter\Security\Security;
use CodeIgniter\Session\Session;
use CodeIgniter\Superglobals;
use CodeIgniter\Throttle\Throttler;
use CodeIgniter\Typography\Typography;
use CodeIgniter\Validation\ValidationInterface;
use CodeIgniter\View\Cell;
use CodeIgniter\View\Parser;
use CodeIgniter\View\RendererInterface;
use CodeIgniter\View\View;
use Config\App;
use Config\Autoload;
use Config\Cache;
use Config\ContentSecurityPolicy as CSPConfig;
use Config\Encryption;
use Config\Exceptions as ConfigExceptions;
use Config\Filters as ConfigFilters;
use Config\Format as ConfigFormat;
use Config\Honeypot as ConfigHoneyPot;
use Config\Images;
use Config\Migrations;
use Config\Modules;
use Config\Optimize;
use Config\Pager as ConfigPager;
use Config\Services as AppServices;
use Config\Session as ConfigSession;
use Config\Toolbar as ConfigToolbar;
use Config\Validation as ConfigValidation;
use Config\View as ConfigView;
/**
* Services Configuration file.
*
* Services are simply other classes/libraries that the system uses
* to do its job. This is used by CodeIgniter to allow the core of the
* framework to be swapped out easily without affecting the usage within
* the rest of your application.
*
* This is used in place of a Dependency Injection container primarily
* due to its simplicity, which allows a better long-term maintenance
* of the applications built on top of CodeIgniter. A bonus side-effect
* is that IDEs are able to determine what class you are calling
* whereas with DI Containers there usually isn't a way for them to do this.
*
* Warning: To allow overrides by service providers do not use static calls,
* instead call out to \Config\Services (imported as AppServices).
*
* @see http://blog.ircmaxell.com/2015/11/simple-easy-risk-and-change.html
* @see http://www.infoq.com/presentations/Simple-Made-Easy
*
* @method static CacheInterface cache(Cache $config = null, $getShared = true)
* @method static CLIRequest clirequest(App $config = null, $getShared = true)
* @method static CodeIgniter codeigniter(App $config = null, $getShared = true)
* @method static Commands commands($getShared = true)
* @method static void createRequest(App $config, bool $isCli = false)
* @method static ContentSecurityPolicy csp(CSPConfig $config = null, $getShared = true)
* @method static CURLRequest curlrequest($options = [], ResponseInterface $response = null, App $config = null, $getShared = true)
* @method static Email email($config = null, $getShared = true)
* @method static EncrypterInterface encrypter(Encryption $config = null, $getShared = false)
* @method static Exceptions exceptions(ConfigExceptions $config = null, $getShared = true)
* @method static Filters filters(ConfigFilters $config = null, $getShared = true)
* @method static Format format(ConfigFormat $config = null, $getShared = true)
* @method static Honeypot honeypot(ConfigHoneyPot $config = null, $getShared = true)
* @method static BaseHandler image($handler = null, Images $config = null, $getShared = true)
* @method static IncomingRequest incomingrequest(?App $config = null, bool $getShared = true)
* @method static Iterator iterator($getShared = true)
* @method static Language language($locale = null, $getShared = true)
* @method static Logger logger($getShared = true)
* @method static MigrationRunner migrations(Migrations $config = null, ConnectionInterface $db = null, $getShared = true)
* @method static Negotiate negotiator(RequestInterface $request = null, $getShared = true)
* @method static Pager pager(ConfigPager $config = null, RendererInterface $view = null, $getShared = true)
* @method static Parser parser($viewPath = null, ConfigView $config = null, $getShared = true)
* @method static RedirectResponse redirectresponse(App $config = null, $getShared = true)
* @method static View renderer($viewPath = null, ConfigView $config = null, $getShared = true)
* @method static IncomingRequest|CLIRequest request(App $config = null, $getShared = true)
* @method static ResponseInterface response(App $config = null, $getShared = true)
* @method static ResponseCache responsecache(?Cache $config = null, ?CacheInterface $cache = null, bool $getShared = true)
* @method static Router router(RouteCollectionInterface $routes = null, Request $request = null, $getShared = true)
* @method static RouteCollection routes($getShared = true)
* @method static Security security(App $config = null, $getShared = true)
* @method static Session session(ConfigSession $config = null, $getShared = true)
* @method static SiteURIFactory siteurifactory(App $config = null, Superglobals $superglobals = null, $getShared = true)
* @method static Superglobals superglobals(array $server = null, array $get = null, bool $getShared = true)
* @method static Throttler throttler($getShared = true)
* @method static Timer timer($getShared = true)
* @method static Toolbar toolbar(ConfigToolbar $config = null, $getShared = true)
* @method static Typography typography($getShared = true)
* @method static URI uri($uri = null, $getShared = true)
* @method static ValidationInterface validation(ConfigValidation $config = null, $getShared = true)
* @method static Cell viewcell($getShared = true)
*/
class BaseService
{
/**
* Cache for instance of any services that
* have been requested as a "shared" instance.
* Keys should be lowercase service names.
*
* @var array<string, object> [key => instance]
*/
protected static $instances = [];
/**
* Factory method list.
*
* @var array<string, (callable(mixed ...$params): object)> [key => callable]
*/
protected static array $factories = [];
/**
* Mock objects for testing which are returned if exist.
*
* @var array<string, object> [key => instance]
*/
protected static $mocks = [];
/**
* Have we already discovered other Services?
*
* @var bool
*/
protected static $discovered = false;
/**
* A cache of other service classes we've found.
*
* @var array
*
* @deprecated 4.5.0 No longer used.
*/
protected static $services = [];
/**
* A cache of the names of services classes found.
*
* @var list<string>
*/
private static array $serviceNames = [];
/**
* Simple method to get an entry fast.
*
* @param string $key Identifier of the entry to look for.
*
* @return object|null Entry.
*/
public static function get(string $key): ?object
{
return static::$instances[$key] ?? static::__callStatic($key, []);
}
/**
* Sets an entry.
*
* @param string $key Identifier of the entry.
*/
public static function set(string $key, object $value): void
{
if (isset(static::$instances[$key])) {
throw new InvalidArgumentException('The entry for "' . $key . '" is already set.');
}
static::$instances[$key] = $value;
}
/**
* Overrides an existing entry.
*
* @param string $key Identifier of the entry.
*/
public static function override(string $key, object $value): void
{
static::$instances[$key] = $value;
}
/**
* Returns a shared instance of any of the class' services.
*
* $key must be a name matching a service.
*
* @param array|bool|float|int|object|string|null ...$params
*
* @return object
*/
protected static function getSharedInstance(string $key, ...$params)
{
$key = strtolower($key);
// Returns mock if exists
if (isset(static::$mocks[$key])) {
return static::$mocks[$key];
}
if (! isset(static::$instances[$key])) {
// Make sure $getShared is false
$params[] = false;
static::$instances[$key] = AppServices::$key(...$params);
}
return static::$instances[$key];
}
/**
* The Autoloader class is the central class that handles our
* spl_autoload_register method, and helper methods.
*
* @return Autoloader
*/
public static function autoloader(bool $getShared = true)
{
if ($getShared) {
if (empty(static::$instances['autoloader'])) {
static::$instances['autoloader'] = new Autoloader();
}
return static::$instances['autoloader'];
}
return new Autoloader();
}
/**
* The file locator provides utility methods for looking for non-classes
* within namespaced folders, as well as convenience methods for
* loading 'helpers', and 'libraries'.
*
* @return FileLocatorInterface
*/
public static function locator(bool $getShared = true)
{
if ($getShared) {
if (empty(static::$instances['locator'])) {
$cacheEnabled = class_exists(Optimize::class)
&& (new Optimize())->locatorCacheEnabled;
if ($cacheEnabled) {
static::$instances['locator'] = new FileLocatorCached(new FileLocator(static::autoloader()));
} else {
static::$instances['locator'] = new FileLocator(static::autoloader());
}
}
return static::$mocks['locator'] ?? static::$instances['locator'];
}
return new FileLocator(static::autoloader());
}
/**
* Provides the ability to perform case-insensitive calling of service
* names.
*
* @return object|null
*/
public static function __callStatic(string $name, array $arguments)
{
if (isset(static::$factories[$name])) {
return static::$factories[$name](...$arguments);
}
$service = static::serviceExists($name);
if ($service === null) {
return null;
}
return $service::$name(...$arguments);
}
/**
* Check if the requested service is defined and return the declaring
* class. Return null if not found.
*/
public static function serviceExists(string $name): ?string
{
static::buildServicesCache();
$services = array_merge(self::$serviceNames, [Services::class]);
$name = strtolower($name);
foreach ($services as $service) {
if (method_exists($service, $name)) {
static::$factories[$name] = [$service, $name];
return $service;
}
}
return null;
}
/**
* Reset shared instances and mocks for testing.
*
* @return void
*
* @testTag only available to test code
*/
public static function reset(bool $initAutoloader = true)
{
static::$mocks = [];
static::$instances = [];
static::$factories = [];
if ($initAutoloader) {
static::autoloader()->initialize(new Autoload(), new Modules());
}
}
/**
* Resets any mock and shared instances for a single service.
*
* @return void
*
* @testTag only available to test code
*/
public static function resetSingle(string $name)
{
$name = strtolower($name);
unset(static::$mocks[$name], static::$instances[$name]);
}
/**
* Inject mock object for testing.
*
* @param object $mock
*
* @return void
*
* @testTag only available to test code
*/
public static function injectMock(string $name, $mock)
{
static::$instances[$name] = $mock;
static::$mocks[strtolower($name)] = $mock;
}
/**
* Resets the service cache.
*/
public static function resetServicesCache(): void
{
self::$serviceNames = [];
static::$discovered = false;
}
protected static function buildServicesCache(): void
{
if (! static::$discovered) {
if ((new Modules())->shouldDiscover('services')) {
$locator = static::locator();
$files = $locator->search('Config/Services');
$systemPath = static::autoloader()->getNamespace('CodeIgniter')[0];
// Get instances of all service classes and cache them locally.
foreach ($files as $file) {
// Does not search `CodeIgniter` namespace to prevent from loading twice.
if (str_starts_with($file, $systemPath)) {
continue;
}
$classname = $locator->findQualifiedNameFromPath($file);
if ($classname === false) {
continue;
}
if ($classname !== Services::class) {
self::$serviceNames[] = $classname;
}
}
}
static::$discovered = true;
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Config/Publisher.php | system/Config/Publisher.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\Config;
/**
* Publisher Configuration
*
* Defines basic security restrictions for the Publisher class
* to prevent abuse by injecting malicious files into a project.
*/
class Publisher extends BaseConfig
{
/**
* A list of allowed destinations with a (pseudo-)regex
* of allowed files for each destination.
* Attempts to publish to directories not in this list will
* result in a PublisherException. Files that do no fit the
* pattern will cause copy/merge to fail.
*
* @var array<string, string>
*/
public $restrictions = [
ROOTPATH => '*',
FCPATH => '#\.(?css|js|map|htm?|xml|json|webmanifest|tff|eot|woff?|gif|jpe?g|tiff?|png|webp|bmp|ico|svg)$#i',
];
/**
* Disables Registrars to prevent modules from altering the restrictions.
*/
final protected function registerProperties(): void
{
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Config/Services.php | system/Config/Services.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\Config;
use CodeIgniter\Cache\CacheFactory;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\Cache\ResponseCache;
use CodeIgniter\CLI\Commands;
use CodeIgniter\CodeIgniter;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Database\MigrationRunner;
use CodeIgniter\Debug\Exceptions;
use CodeIgniter\Debug\Iterator;
use CodeIgniter\Debug\Timer;
use CodeIgniter\Debug\Toolbar;
use CodeIgniter\Email\Email;
use CodeIgniter\Encryption\EncrypterInterface;
use CodeIgniter\Encryption\Encryption;
use CodeIgniter\Filters\Filters;
use CodeIgniter\Format\Format;
use CodeIgniter\Honeypot\Honeypot;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\ContentSecurityPolicy;
use CodeIgniter\HTTP\CURLRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Negotiate;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\Request;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\SiteURIFactory;
use CodeIgniter\HTTP\URI;
use CodeIgniter\HTTP\UserAgent;
use CodeIgniter\Images\Handlers\BaseHandler;
use CodeIgniter\Language\Language;
use CodeIgniter\Log\Logger;
use CodeIgniter\Pager\Pager;
use CodeIgniter\Router\RouteCollection;
use CodeIgniter\Router\RouteCollectionInterface;
use CodeIgniter\Router\Router;
use CodeIgniter\Security\Security;
use CodeIgniter\Session\Handlers\BaseHandler as SessionBaseHandler;
use CodeIgniter\Session\Handlers\Database\MySQLiHandler;
use CodeIgniter\Session\Handlers\Database\PostgreHandler;
use CodeIgniter\Session\Handlers\DatabaseHandler;
use CodeIgniter\Session\Session;
use CodeIgniter\Superglobals;
use CodeIgniter\Throttle\Throttler;
use CodeIgniter\Typography\Typography;
use CodeIgniter\Validation\Validation;
use CodeIgniter\Validation\ValidationInterface;
use CodeIgniter\View\Cell;
use CodeIgniter\View\Parser;
use CodeIgniter\View\RendererInterface;
use CodeIgniter\View\View;
use Config\App;
use Config\Cache;
use Config\ContentSecurityPolicy as ContentSecurityPolicyConfig;
use Config\ContentSecurityPolicy as CSPConfig;
use Config\Database;
use Config\Email as EmailConfig;
use Config\Encryption as EncryptionConfig;
use Config\Exceptions as ExceptionsConfig;
use Config\Filters as FiltersConfig;
use Config\Format as FormatConfig;
use Config\Honeypot as HoneypotConfig;
use Config\Images;
use Config\Logger as LoggerConfig;
use Config\Migrations;
use Config\Modules;
use Config\Pager as PagerConfig;
use Config\Paths;
use Config\Routing;
use Config\Security as SecurityConfig;
use Config\Services as AppServices;
use Config\Session as SessionConfig;
use Config\Toolbar as ToolbarConfig;
use Config\Validation as ValidationConfig;
use Config\View as ViewConfig;
use InvalidArgumentException;
use Locale;
/**
* Services Configuration file.
*
* Services are simply other classes/libraries that the system uses
* to do its job. This is used by CodeIgniter to allow the core of the
* framework to be swapped out easily without affecting the usage within
* the rest of your application.
*
* This is used in place of a Dependency Injection container primarily
* due to its simplicity, which allows a better long-term maintenance
* of the applications built on top of CodeIgniter. A bonus side-effect
* is that IDEs are able to determine what class you are calling
* whereas with DI Containers there usually isn't a way for them to do this.
*
* @see http://blog.ircmaxell.com/2015/11/simple-easy-risk-and-change.html
* @see http://www.infoq.com/presentations/Simple-Made-Easy
* @see \CodeIgniter\Config\ServicesTest
*/
class Services extends BaseService
{
/**
* The cache class provides a simple way to store and retrieve
* complex data for later.
*
* @return CacheInterface
*/
public static function cache(?Cache $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('cache', $config);
}
$config ??= config(Cache::class);
return CacheFactory::getHandler($config);
}
/**
* The CLI Request class provides for ways to interact with
* a command line request.
*
* @return CLIRequest
*
* @internal
*/
public static function clirequest(?App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('clirequest', $config);
}
$config ??= config(App::class);
return new CLIRequest($config);
}
/**
* CodeIgniter, the core of the framework.
*
* @return CodeIgniter
*/
public static function codeigniter(?App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('codeigniter', $config);
}
$config ??= config(App::class);
return new CodeIgniter($config);
}
/**
* The commands utility for running and working with CLI commands.
*
* @return Commands
*/
public static function commands(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('commands');
}
return new Commands();
}
/**
* Content Security Policy
*
* @return ContentSecurityPolicy
*/
public static function csp(?CSPConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('csp', $config);
}
$config ??= config(ContentSecurityPolicyConfig::class);
return new ContentSecurityPolicy($config);
}
/**
* The CURL Request class acts as a simple HTTP client for interacting
* with other servers, typically through APIs.
*
* @return CURLRequest
*/
public static function curlrequest(array $options = [], ?ResponseInterface $response = null, ?App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('curlrequest', $options, $response, $config);
}
$config ??= config(App::class);
$response ??= new Response($config);
return new CURLRequest(
$config,
new URI($options['baseURI'] ?? null),
$response,
$options,
);
}
/**
* The Email class allows you to send email via mail, sendmail, SMTP.
*
* @param array|EmailConfig|null $config
*
* @return Email
*/
public static function email($config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('email', $config);
}
if (empty($config) || (! is_array($config) && ! $config instanceof EmailConfig)) {
$config = config(EmailConfig::class);
}
return new Email($config);
}
/**
* The Encryption class provides two-way encryption.
*
* @param bool $getShared
*
* @return EncrypterInterface Encryption handler
*/
public static function encrypter(?EncryptionConfig $config = null, $getShared = false)
{
if ($getShared === true) {
return static::getSharedInstance('encrypter', $config);
}
$config ??= config(EncryptionConfig::class);
$encryption = new Encryption($config);
return $encryption->initialize($config);
}
/**
* The Exceptions class holds the methods that handle:
*
* - set_exception_handler
* - set_error_handler
* - register_shutdown_function
*
* @return Exceptions
*/
public static function exceptions(
?ExceptionsConfig $config = null,
bool $getShared = true,
) {
if ($getShared) {
return static::getSharedInstance('exceptions', $config);
}
$config ??= config(ExceptionsConfig::class);
return new Exceptions($config);
}
/**
* Filters allow you to run tasks before and/or after a controller
* is executed. During before filters, the request can be modified,
* and actions taken based on the request, while after filters can
* act on or modify the response itself before it is sent to the client.
*
* @return Filters
*/
public static function filters(?FiltersConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('filters', $config);
}
$config ??= config(FiltersConfig::class);
return new Filters($config, AppServices::get('request'), AppServices::get('response'));
}
/**
* The Format class is a convenient place to create Formatters.
*
* @return Format
*/
public static function format(?FormatConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('format', $config);
}
$config ??= config(FormatConfig::class);
return new Format($config);
}
/**
* The Honeypot provides a secret input on forms that bots should NOT
* fill in, providing an additional safeguard when accepting user input.
*
* @return Honeypot
*/
public static function honeypot(?HoneypotConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('honeypot', $config);
}
$config ??= config(HoneypotConfig::class);
return new Honeypot($config);
}
/**
* Acts as a factory for ImageHandler classes and returns an instance
* of the handler. Used like service('image')->withFile($path)->rotate(90)->save();
*
* @return BaseHandler
*/
public static function image(?string $handler = null, ?Images $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('image', $handler, $config);
}
$config ??= config(Images::class);
assert($config instanceof Images);
$handler = $handler !== null && $handler !== '' && $handler !== '0' ? $handler : $config->defaultHandler;
$class = $config->handlers[$handler];
return new $class($config);
}
/**
* The Iterator class provides a simple way of looping over a function
* and timing the results and memory usage. Used when debugging and
* optimizing applications.
*
* @return Iterator
*/
public static function iterator(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('iterator');
}
return new Iterator();
}
/**
* Responsible for loading the language string translations.
*
* @return Language
*/
public static function language(?string $locale = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('language', $locale)->setLocale($locale);
}
if (AppServices::get('request') instanceof IncomingRequest) {
$requestLocale = AppServices::get('request')->getLocale();
} else {
$requestLocale = Locale::getDefault();
}
// Use '?:' for empty string check
$locale = $locale !== null && $locale !== '' && $locale !== '0' ? $locale : $requestLocale;
return new Language($locale);
}
/**
* The Logger class is a PSR-3 compatible Logging class that supports
* multiple handlers that process the actual logging.
*
* @return Logger
*/
public static function logger(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('logger');
}
return new Logger(config(LoggerConfig::class));
}
/**
* Return the appropriate Migration runner.
*
* @return MigrationRunner
*/
public static function migrations(?Migrations $config = null, ?ConnectionInterface $db = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('migrations', $config, $db);
}
$config ??= config(Migrations::class);
return new MigrationRunner($config, $db);
}
/**
* The Negotiate class provides the content negotiation features for
* working the request to determine correct language, encoding, charset,
* and more.
*
* @return Negotiate
*/
public static function negotiator(?RequestInterface $request = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('negotiator', $request);
}
$request ??= AppServices::get('request');
return new Negotiate($request);
}
/**
* Return the ResponseCache.
*
* @return ResponseCache
*/
public static function responsecache(?Cache $config = null, ?CacheInterface $cache = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('responsecache', $config, $cache);
}
$config ??= config(Cache::class);
$cache ??= AppServices::get('cache');
return new ResponseCache($config, $cache);
}
/**
* Return the appropriate pagination handler.
*
* @return Pager
*/
public static function pager(?PagerConfig $config = null, ?RendererInterface $view = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('pager', $config, $view);
}
$config ??= config(PagerConfig::class);
$view ??= AppServices::renderer(null, null, false);
return new Pager($config, $view);
}
/**
* The Parser is a simple template parser.
*
* @return Parser
*/
public static function parser(?string $viewPath = null, ?ViewConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('parser', $viewPath, $config);
}
$viewPath = $viewPath !== null && $viewPath !== '' && $viewPath !== '0' ? $viewPath : (new Paths())->viewDirectory;
$config ??= config(ViewConfig::class);
return new Parser($config, $viewPath, AppServices::get('locator'), CI_DEBUG, AppServices::get('logger'));
}
/**
* The Renderer class is the class that actually displays a file to the user.
* The default View class within CodeIgniter is intentionally simple, but this
* service could easily be replaced by a template engine if the user needed to.
*
* @return View
*/
public static function renderer(?string $viewPath = null, ?ViewConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('renderer', $viewPath, $config);
}
$viewPath = $viewPath !== null && $viewPath !== '' && $viewPath !== '0' ? $viewPath : (new Paths())->viewDirectory;
$config ??= config(ViewConfig::class);
return new View($config, $viewPath, AppServices::get('locator'), CI_DEBUG, AppServices::get('logger'));
}
/**
* Returns the current Request object.
*
* createRequest() injects IncomingRequest or CLIRequest.
*
* @return CLIRequest|IncomingRequest
*
* @deprecated The parameter $config and $getShared are deprecated.
*/
public static function request(?App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('request', $config);
}
// @TODO remove the following code for backward compatibility
return AppServices::incomingrequest($config, $getShared);
}
/**
* Create the current Request object, either IncomingRequest or CLIRequest.
*
* This method is called from CodeIgniter::getRequestObject().
*
* @internal
*/
public static function createRequest(App $config, bool $isCli = false): void
{
if ($isCli) {
$request = AppServices::clirequest($config);
} else {
$request = AppServices::incomingrequest($config);
// guess at protocol if needed
$request->setProtocolVersion($_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1');
}
// Inject the request object into Services.
static::$instances['request'] = $request;
}
/**
* The IncomingRequest class models an HTTP request.
*
* @return IncomingRequest
*
* @internal
*/
public static function incomingrequest(?App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('request', $config);
}
$config ??= config(App::class);
return new IncomingRequest(
$config,
AppServices::get('uri'),
'php://input',
new UserAgent(),
);
}
/**
* The Response class models an HTTP response.
*
* @return ResponseInterface
*/
public static function response(?App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('response', $config);
}
$config ??= config(App::class);
return new Response($config);
}
/**
* The Redirect class provides nice way of working with redirects.
*
* @return RedirectResponse
*/
public static function redirectresponse(?App $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('redirectresponse', $config);
}
$config ??= config(App::class);
$response = new RedirectResponse($config);
$response->setProtocolVersion(AppServices::get('request')->getProtocolVersion());
return $response;
}
/**
* The Routes service is a class that allows for easily building
* a collection of routes.
*
* @return RouteCollection
*/
public static function routes(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('routes');
}
return new RouteCollection(AppServices::get('locator'), new Modules(), config(Routing::class));
}
/**
* The Router class uses a RouteCollection's array of routes, and determines
* the correct Controller and Method to execute.
*
* @return Router
*/
public static function router(?RouteCollectionInterface $routes = null, ?Request $request = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('router', $routes, $request);
}
$routes ??= AppServices::get('routes');
$request ??= AppServices::get('request');
return new Router($routes, $request);
}
/**
* The Security class provides a few handy tools for keeping the site
* secure, most notably the CSRF protection tools.
*
* @return Security
*/
public static function security(?SecurityConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('security', $config);
}
$config ??= config(SecurityConfig::class);
return new Security($config);
}
/**
* Return the session manager.
*
* @return Session
*/
public static function session(?SessionConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('session', $config);
}
$config ??= config(SessionConfig::class);
$logger = AppServices::get('logger');
$driverName = $config->driver;
if ($driverName === DatabaseHandler::class) {
$DBGroup = $config->DBGroup ?? config(Database::class)->defaultGroup;
$driverPlatform = Database::connect($DBGroup)->getPlatform();
if ($driverPlatform === 'MySQLi') {
$driverName = MySQLiHandler::class;
} elseif ($driverPlatform === 'Postgre') {
$driverName = PostgreHandler::class;
} else {
throw new InvalidArgumentException(sprintf(
'Invalid session database handler "%s" provided. Only "MySQLi" and "Postgre" are supported.',
$driverPlatform,
));
}
}
if (! class_exists($driverName) || ! is_a($driverName, SessionBaseHandler::class, true)) {
throw new InvalidArgumentException(sprintf(
'Invalid session handler "%s" provided.',
$driverName,
));
}
/** @var SessionBaseHandler $driver */
$driver = new $driverName($config, AppServices::get('request')->getIPAddress());
$driver->setLogger($logger);
$session = new Session($driver, $config);
$session->setLogger($logger);
if (session_status() === PHP_SESSION_NONE) {
// PHP Session emits the headers according to `session.cache_limiter`.
// See https://www.php.net/manual/en/function.session-cache-limiter.php.
// The headers are not managed by CI's Response class.
// So, we remove CI's default Cache-Control header.
AppServices::get('response')->removeHeader('Cache-Control');
$session->start();
}
return $session;
}
/**
* The Factory for SiteURI.
*
* @return SiteURIFactory
*/
public static function siteurifactory(
?App $config = null,
?Superglobals $superglobals = null,
bool $getShared = true,
) {
if ($getShared) {
return static::getSharedInstance('siteurifactory', $config, $superglobals);
}
$config ??= config('App');
$superglobals ??= AppServices::get('superglobals');
return new SiteURIFactory($config, $superglobals);
}
/**
* Superglobals.
*
* @return Superglobals
*/
public static function superglobals(
?array $server = null,
?array $get = null,
bool $getShared = true,
) {
if ($getShared) {
return static::getSharedInstance('superglobals', $server, $get);
}
return new Superglobals($server, $get);
}
/**
* The Throttler class provides a simple method for implementing
* rate limiting in your applications.
*
* @return Throttler
*/
public static function throttler(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('throttler');
}
return new Throttler(AppServices::get('cache'));
}
/**
* The Timer class provides a simple way to Benchmark portions of your
* application.
*
* @return Timer
*/
public static function timer(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('timer');
}
return new Timer();
}
/**
* Return the debug toolbar.
*
* @return Toolbar
*/
public static function toolbar(?ToolbarConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('toolbar', $config);
}
$config ??= config(ToolbarConfig::class);
return new Toolbar($config);
}
/**
* The URI class provides a way to model and manipulate URIs.
*
* @param string|null $uri The URI string
*
* @return URI The current URI if $uri is null.
*/
public static function uri(?string $uri = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('uri', $uri);
}
if ($uri === null) {
$appConfig = config(App::class);
$factory = AppServices::siteurifactory($appConfig, AppServices::get('superglobals'));
return $factory->createFromGlobals();
}
return new URI($uri);
}
/**
* The Validation class provides tools for validating input data.
*
* @return ValidationInterface
*/
public static function validation(?ValidationConfig $config = null, bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('validation', $config);
}
$config ??= config(ValidationConfig::class);
return new Validation($config, AppServices::get('renderer'));
}
/**
* View cells are intended to let you insert HTML into view
* that has been generated by any callable in the system.
*
* @return Cell
*/
public static function viewcell(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('viewcell');
}
return new Cell(AppServices::get('cache'));
}
/**
* The Typography class provides a way to format text in semantically relevant ways.
*
* @return Typography
*/
public static function typography(bool $getShared = true)
{
if ($getShared) {
return static::getSharedInstance('typography');
}
return new Typography();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Config/Factory.php | system/Config/Factory.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\Config;
/**
* Factories Configuration file.
*
* Provides overriding directives for how
* Factories should handle discovery and
* instantiation of specific components.
* Each property should correspond to the
* lowercase, plural component name.
*/
class Factory extends BaseConfig
{
/**
* Supplies a default set of options to merge for
* all unspecified factory components.
*
* @var array
*/
public static $default = [
'component' => null,
'path' => null,
'instanceOf' => null,
'getShared' => true,
'preferApp' => true,
];
/**
* Specifies that Models should always favor child
* classes to allow easy extension of module Models.
*
* @var array
*/
public $models = [
'preferApp' => true,
];
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Config/BaseConfig.php | system/Config/BaseConfig.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.
*/
namespace CodeIgniter\Config;
use CodeIgniter\Autoloader\FileLocatorInterface;
use CodeIgniter\Exceptions\ConfigException;
use CodeIgniter\Exceptions\RuntimeException;
use Config\Encryption;
use Config\Modules;
use ReflectionClass;
use ReflectionException;
/**
* Class BaseConfig
*
* Not intended to be used on its own, this class will attempt to
* automatically populate the child class' properties with values
* from the environment.
*
* These can be set within the .env file.
*
* @phpstan-consistent-constructor
* @see \CodeIgniter\Config\BaseConfigTest
*/
class BaseConfig
{
/**
* An optional array of classes that will act as Registrars
* for rapidly setting config class properties.
*
* @var array
*/
public static $registrars = [];
/**
* Whether to override properties by Env vars and Registrars.
*/
public static bool $override = true;
/**
* Has module discovery completed?
*
* @var bool
*/
protected static $didDiscovery = false;
/**
* Is module discovery running or not?
*/
protected static bool $discovering = false;
/**
* The processing Registrar file for error message.
*/
protected static string $registrarFile = '';
/**
* The modules configuration.
*
* @var Modules|null
*/
protected static $moduleConfig;
public static function __set_state(array $array)
{
static::$override = false;
$obj = new static();
static::$override = true;
$properties = array_keys(get_object_vars($obj));
foreach ($properties as $property) {
$obj->{$property} = $array[$property];
}
return $obj;
}
/**
* @internal For testing purposes only.
* @testTag
*/
public static function setModules(Modules $modules): void
{
static::$moduleConfig = $modules;
}
/**
* @internal For testing purposes only.
* @testTag
*/
public static function reset(): void
{
static::$registrars = [];
static::$override = true;
static::$didDiscovery = false;
static::$moduleConfig = null;
}
/**
* Will attempt to get environment variables with names
* that match the properties of the child class.
*
* The "shortPrefix" is the lowercase-only config class name.
*/
public function __construct()
{
static::$moduleConfig ??= new Modules();
if (! static::$override) {
return;
}
$this->registerProperties();
$properties = array_keys(get_object_vars($this));
$prefix = static::class;
$slashAt = strrpos($prefix, '\\');
$shortPrefix = strtolower(substr($prefix, $slashAt === false ? 0 : $slashAt + 1));
foreach ($properties as $property) {
$this->initEnvValue($this->{$property}, $property, $prefix, $shortPrefix);
if ($this instanceof Encryption && $property === 'key') {
if (str_starts_with($this->{$property}, 'hex2bin:')) {
// Handle hex2bin prefix
$this->{$property} = hex2bin(substr($this->{$property}, 8));
} elseif (str_starts_with($this->{$property}, 'base64:')) {
// Handle base64 prefix
$this->{$property} = base64_decode(substr($this->{$property}, 7), true);
}
}
}
}
/**
* Initialization an environment-specific configuration setting
*
* @param array|bool|float|int|string|null $property
*
* @return void
*/
protected function initEnvValue(&$property, string $name, string $prefix, string $shortPrefix)
{
if (is_array($property)) {
foreach (array_keys($property) as $key) {
$this->initEnvValue($property[$key], "{$name}.{$key}", $prefix, $shortPrefix);
}
} elseif (($value = $this->getEnvValue($name, $prefix, $shortPrefix)) !== false && $value !== null) {
if ($value === 'false') {
$value = false;
} elseif ($value === 'true') {
$value = true;
}
if (is_bool($value)) {
$property = $value;
return;
}
$value = trim($value, '\'"');
if (is_int($property)) {
$value = (int) $value;
} elseif (is_float($property)) {
$value = (float) $value;
}
// If the default value of the property is `null` and the type is not
// `string`, TypeError will happen.
// So cannot set `declare(strict_types=1)` in this file.
$property = $value;
}
}
/**
* Retrieve an environment-specific configuration setting
*
* @return string|null
*/
protected function getEnvValue(string $property, string $prefix, string $shortPrefix)
{
$shortPrefix = ltrim($shortPrefix, '\\');
$underscoreProperty = str_replace('.', '_', $property);
switch (true) {
case array_key_exists("{$shortPrefix}.{$property}", $_ENV):
return $_ENV["{$shortPrefix}.{$property}"];
case array_key_exists("{$shortPrefix}_{$underscoreProperty}", $_ENV):
return $_ENV["{$shortPrefix}_{$underscoreProperty}"];
case array_key_exists("{$shortPrefix}.{$property}", $_SERVER):
return $_SERVER["{$shortPrefix}.{$property}"];
case array_key_exists("{$shortPrefix}_{$underscoreProperty}", $_SERVER):
return $_SERVER["{$shortPrefix}_{$underscoreProperty}"];
case array_key_exists("{$prefix}.{$property}", $_ENV):
return $_ENV["{$prefix}.{$property}"];
case array_key_exists("{$prefix}_{$underscoreProperty}", $_ENV):
return $_ENV["{$prefix}_{$underscoreProperty}"];
case array_key_exists("{$prefix}.{$property}", $_SERVER):
return $_SERVER["{$prefix}.{$property}"];
case array_key_exists("{$prefix}_{$underscoreProperty}", $_SERVER):
return $_SERVER["{$prefix}_{$underscoreProperty}"];
default:
$value = getenv("{$shortPrefix}.{$property}");
$value = $value === false ? getenv("{$shortPrefix}_{$underscoreProperty}") : $value;
$value = $value === false ? getenv("{$prefix}.{$property}") : $value;
$value = $value === false ? getenv("{$prefix}_{$underscoreProperty}") : $value;
return $value === false ? null : $value;
}
}
/**
* Provides external libraries a simple way to register one or more
* options into a config file.
*
* @return void
*
* @throws ReflectionException
*/
protected function registerProperties()
{
if (! static::$moduleConfig->shouldDiscover('registrars')) {
return;
}
if (! static::$didDiscovery) {
// Discovery must be completed before the first instantiation of any Config class.
if (static::$discovering) {
throw new ConfigException(
'During Auto-Discovery of Registrars,'
. ' "' . static::class . '" executes Auto-Discovery again.'
. ' "' . clean_path(static::$registrarFile) . '" seems to have bad code.',
);
}
static::$discovering = true;
/** @var FileLocatorInterface */
$locator = service('locator');
$registrarsFiles = $locator->search('Config/Registrar.php');
foreach ($registrarsFiles as $file) {
// Saves the file for error message.
static::$registrarFile = $file;
$className = $locator->findQualifiedNameFromPath($file);
if ($className === false) {
continue;
}
static::$registrars[] = new $className();
}
static::$didDiscovery = true;
static::$discovering = false;
}
$shortName = (new ReflectionClass($this))->getShortName();
// Check the registrar class for a method named after this class' shortName
foreach (static::$registrars as $callable) {
// ignore non-applicable registrars
if (! method_exists($callable, $shortName)) {
continue; // @codeCoverageIgnore
}
$properties = $callable::$shortName();
if (! is_array($properties)) {
throw new RuntimeException('Registrars must return an array of properties and their values.');
}
foreach ($properties as $property => $value) {
if (isset($this->{$property}) && is_array($this->{$property}) && is_array($value)) {
$this->{$property} = array_merge($this->{$property}, $value);
} else {
$this->{$property} = $value;
}
}
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Config/View.php | system/Config/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.
*/
namespace CodeIgniter\Config;
use CodeIgniter\View\ViewDecoratorInterface;
/**
* View configuration
*
* @phpstan-type parser_callable (callable(mixed): mixed)
* @phpstan-type parser_callable_string (callable(mixed): mixed)&string
*/
class View extends BaseConfig
{
/**
* When false, the view method will clear the data between each
* call.
*
* @var bool
*/
public $saveData = true;
/**
* Parser Filters map a filter name with any PHP callable. When the
* Parser prepares a variable for display, it will chain it
* through the filters in the order defined, inserting any parameters.
*
* To prevent potential abuse, all filters MUST be defined here
* in order for them to be available for use within the Parser.
*
* @psalm-suppress UndefinedDocblockClass
*
* @var array<string, string>
* @phpstan-var array<string, parser_callable_string>
*/
public $filters = [];
/**
* Parser Plugins provide a way to extend the functionality provided
* by the core Parser by creating aliases that will be replaced with
* any callable. Can be single or tag pair.
*
* @psalm-suppress UndefinedDocblockClass
*
* @var array<string, callable|list<string>|string>
* @phpstan-var array<string, list<parser_callable_string>|parser_callable_string|parser_callable>
*/
public $plugins = [];
/**
* Built-in View filters.
*
* @psalm-suppress UndefinedDocblockClass
*
* @var array<string, string>
* @phpstan-var array<string, parser_callable_string>
*/
protected $coreFilters = [
'abs' => '\abs',
'capitalize' => '\CodeIgniter\View\Filters::capitalize',
'date' => '\CodeIgniter\View\Filters::date',
'date_modify' => '\CodeIgniter\View\Filters::date_modify',
'default' => '\CodeIgniter\View\Filters::default',
'esc' => '\CodeIgniter\View\Filters::esc',
'excerpt' => '\CodeIgniter\View\Filters::excerpt',
'highlight' => '\CodeIgniter\View\Filters::highlight',
'highlight_code' => '\CodeIgniter\View\Filters::highlight_code',
'limit_words' => '\CodeIgniter\View\Filters::limit_words',
'limit_chars' => '\CodeIgniter\View\Filters::limit_chars',
'local_currency' => '\CodeIgniter\View\Filters::local_currency',
'local_number' => '\CodeIgniter\View\Filters::local_number',
'lower' => '\strtolower',
'nl2br' => '\CodeIgniter\View\Filters::nl2br',
'number_format' => '\number_format',
'prose' => '\CodeIgniter\View\Filters::prose',
'round' => '\CodeIgniter\View\Filters::round',
'strip_tags' => '\strip_tags',
'title' => '\CodeIgniter\View\Filters::title',
'upper' => '\strtoupper',
];
/**
* Built-in View plugins.
*
* @psalm-suppress UndefinedDocblockClass
*
* @var array<string, callable|list<string>|string>
* @phpstan-var array<string, array<parser_callable_string>|parser_callable_string|parser_callable>
*/
protected $corePlugins = [
'csp_script_nonce' => '\CodeIgniter\View\Plugins::cspScriptNonce',
'csp_style_nonce' => '\CodeIgniter\View\Plugins::cspStyleNonce',
'current_url' => '\CodeIgniter\View\Plugins::currentURL',
'previous_url' => '\CodeIgniter\View\Plugins::previousURL',
'mailto' => '\CodeIgniter\View\Plugins::mailto',
'safe_mailto' => '\CodeIgniter\View\Plugins::safeMailto',
'lang' => '\CodeIgniter\View\Plugins::lang',
'validation_errors' => '\CodeIgniter\View\Plugins::validationErrors',
'route' => '\CodeIgniter\View\Plugins::route',
'siteURL' => '\CodeIgniter\View\Plugins::siteURL',
];
/**
* View Decorators are class methods that will be run in sequence to
* have a chance to alter the generated output just prior to caching
* the results.
*
* All classes must implement CodeIgniter\View\ViewDecoratorInterface
*
* @var list<class-string<ViewDecoratorInterface>>
*/
public array $decorators = [];
/**
* Merge the built-in and developer-configured filters and plugins,
* with preference to the developer ones.
*/
public function __construct()
{
$this->filters = array_merge($this->coreFilters, $this->filters);
$this->plugins = array_merge($this->corePlugins, $this->plugins);
parent::__construct();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/RESTful/ResourcePresenter.php | system/RESTful/ResourcePresenter.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\RESTful;
use CodeIgniter\HTTP\ResponseInterface;
/**
* An extendable controller to help provide a UI for a resource.
*
* @see \CodeIgniter\RESTful\ResourcePresenterTest
*/
class ResourcePresenter extends BaseResource
{
/**
* Present a view of resource objects
*
* @return ResponseInterface|string|void
*/
public function index()
{
return lang('RESTful.notImplemented', ['index']);
}
/**
* Present a view to present a specific resource object
*
* @param int|string|null $id
*
* @return ResponseInterface|string|void
*/
public function show($id = null)
{
return lang('RESTful.notImplemented', ['show']);
}
/**
* Present a view to present a new single resource object
*
* @return ResponseInterface|string|void
*/
public function new()
{
return lang('RESTful.notImplemented', ['new']);
}
/**
* Process the creation/insertion of a new resource object.
* This should be a POST.
*
* @return ResponseInterface|string|void
*/
public function create()
{
return lang('RESTful.notImplemented', ['create']);
}
/**
* Present a view to edit the properties of a specific resource object
*
* @param int|string|null $id
*
* @return ResponseInterface|string|void
*/
public function edit($id = null)
{
return lang('RESTful.notImplemented', ['edit']);
}
/**
* Process the updating, full or partial, of a specific resource object.
* This should be a POST.
*
* @param int|string|null $id
*
* @return ResponseInterface|string|void
*/
public function update($id = null)
{
return lang('RESTful.notImplemented', ['update']);
}
/**
* Present a view to confirm the deletion of a specific resource object
*
* @param int|string|null $id
*
* @return ResponseInterface|string|void
*/
public function remove($id = null)
{
return lang('RESTful.notImplemented', ['remove']);
}
/**
* Process the deletion of a specific resource object
*
* @param int|string|null $id
*
* @return ResponseInterface|string|void
*/
public function delete($id = null)
{
return lang('RESTful.notImplemented', ['delete']);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/RESTful/ResourceController.php | system/RESTful/ResourceController.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\RESTful;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\HTTP\ResponseInterface;
/**
* An extendable controller to provide a RESTful API for a resource.
*
* @see \CodeIgniter\RESTful\ResourceControllerTest
*/
class ResourceController extends BaseResource
{
use ResponseTrait;
/**
* Return an array of resource objects, themselves in array format
*
* @return ResponseInterface|string|void
*/
public function index()
{
return $this->fail(lang('RESTful.notImplemented', ['index']), 501);
}
/**
* Return the properties of a resource object
*
* @param int|string|null $id
*
* @return ResponseInterface|string|void
*/
public function show($id = null)
{
return $this->fail(lang('RESTful.notImplemented', ['show']), 501);
}
/**
* Return a new resource object, with default properties
*
* @return ResponseInterface|string|void
*/
public function new()
{
return $this->fail(lang('RESTful.notImplemented', ['new']), 501);
}
/**
* Create a new resource object, from "posted" parameters
*
* @return ResponseInterface|string|void
*/
public function create()
{
return $this->fail(lang('RESTful.notImplemented', ['create']), 501);
}
/**
* Return the editable properties of a resource object
*
* @param int|string|null $id
*
* @return ResponseInterface|string|void
*/
public function edit($id = null)
{
return $this->fail(lang('RESTful.notImplemented', ['edit']), 501);
}
/**
* Add or update a model resource, from "posted" properties
*
* @param int|string|null $id
*
* @return ResponseInterface|string|void
*/
public function update($id = null)
{
return $this->fail(lang('RESTful.notImplemented', ['update']), 501);
}
/**
* Delete the designated resource object from the model
*
* @param int|string|null $id
*
* @return ResponseInterface|string|void
*/
public function delete($id = null)
{
return $this->fail(lang('RESTful.notImplemented', ['delete']), 501);
}
/**
* Set/change the expected response representation for returned objects
*
* @param 'json'|'xml' $format Response format
*
* @return void
*/
public function setFormat(string $format = 'json')
{
if (in_array($format, ['json', 'xml'], true)) {
$this->format = $format;
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/RESTful/BaseResource.php | system/RESTful/BaseResource.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\RESTful;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
abstract class BaseResource extends Controller
{
/**
* Instance of the main Request object.
*
* @var CLIRequest|IncomingRequest
*/
protected $request;
/**
* @var string|null The model that holding this resource's data
*/
protected $modelName;
/**
* @var object|null The model that holding this resource's data
*/
protected $model;
/**
* Constructor.
*
* @return void
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
$this->setModel($this->modelName);
}
/**
* Set or change the model this controller is bound to.
* Given either the name or the object, determine the other.
*
* @param object|string|null $which
*
* @return void
*/
public function setModel($which = null)
{
if ($which !== null) {
$this->model = is_object($which) ? $which : null;
$this->modelName = is_object($which) ? null : $which;
}
if (empty($this->model) && ! empty($this->modelName) && class_exists($this->modelName)) {
$this->model = model($this->modelName);
}
if (! empty($this->model) && empty($this->modelName)) {
$this->modelName = $this->model::class;
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Autoloader/FileLocatorInterface.php | system/Autoloader/FileLocatorInterface.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\Autoloader;
/**
* Allows loading non-class files in a namespaced manner.
* Works with Helpers, Views, etc.
*/
interface FileLocatorInterface
{
/**
* Attempts to locate a file by examining the name for a namespace
* and looking through the PSR-4 namespaced files that we know about.
*
* @param non-empty-string $file The relative file path or namespaced file to
* locate. If not namespaced, search in the app
* folder.
* @param non-empty-string|null $folder The folder within the namespace that we should
* look for the file. If $file does not contain
* this value, it will be appended to the namespace
* folder.
* @param string $ext The file extension the file should have.
*
* @return false|non-empty-string The path to the file, or false if not found.
*/
public function locateFile(string $file, ?string $folder = null, string $ext = 'php');
/**
* Examines a file and returns the fully qualified class name.
*
* @param non-empty-string $file
*/
public function getClassname(string $file): string;
/**
* Searches through all of the defined namespaces looking for a file.
* Returns an array of all found locations for the defined file.
*
* Example:
*
* $locator->search('Config/Routes.php');
* // Assuming PSR4 namespaces include foo and bar, might return:
* [
* 'app/Modules/foo/Config/Routes.php',
* 'app/Modules/bar/Config/Routes.php',
* ]
*
* @return list<non-empty-string>
*/
public function search(string $path, string $ext = 'php', bool $prioritizeApp = true): array;
/**
* Find the qualified name of a file according to
* the namespace of the first matched namespace path.
*
* @return class-string|false The qualified name or false if the path is not found
*/
public function findQualifiedNameFromPath(string $path);
/**
* Scans the defined namespaces, returning a list of all files
* that are contained within the subpath specified by $path.
*
* @return list<string> List of file paths
*/
public function listFiles(string $path): array;
/**
* Scans the provided namespace, returning a list of all files
* that are contained within the sub path specified by $path.
*
* @return list<string> List of file paths
*/
public function listNamespaceFiles(string $prefix, string $path): array;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Autoloader/FileLocatorCached.php | system/Autoloader/FileLocatorCached.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\Autoloader;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\Cache\FactoriesCache\FileVarExportHandler;
/**
* FileLocator with Cache
*
* @see \CodeIgniter\Autoloader\FileLocatorCachedTest
*/
final class FileLocatorCached implements FileLocatorInterface
{
/**
* @var CacheInterface|FileVarExportHandler
*/
private $cacheHandler;
/**
* Cache data
*
* [method => data]
* E.g.,
* [
* 'search' => [$path => $foundPaths],
* ]
*
* @var array<string, array<string, mixed>>
*/
private array $cache = [];
/**
* Is the cache updated?
*/
private bool $cacheUpdated = false;
private string $cacheKey = 'FileLocatorCache';
/**
* @param CacheInterface|FileVarExportHandler|null $cache
*/
public function __construct(private readonly FileLocator $locator, $cache = null)
{
$this->cacheHandler = $cache ?? new FileVarExportHandler();
$this->loadCache();
}
private function loadCache(): void
{
$data = $this->cacheHandler->get($this->cacheKey);
if (is_array($data)) {
$this->cache = $data;
}
}
public function __destruct()
{
$this->saveCache();
}
private function saveCache(): void
{
if ($this->cacheUpdated) {
$this->cacheHandler->save($this->cacheKey, $this->cache, 3600 * 24);
}
}
/**
* Delete cache data
*/
public function deleteCache(): void
{
$this->cacheUpdated = false;
$this->cacheHandler->delete($this->cacheKey);
}
public function findQualifiedNameFromPath(string $path): false|string
{
if (isset($this->cache['findQualifiedNameFromPath'][$path])) {
return $this->cache['findQualifiedNameFromPath'][$path];
}
$classname = $this->locator->findQualifiedNameFromPath($path);
$this->cache['findQualifiedNameFromPath'][$path] = $classname;
$this->cacheUpdated = true;
return $classname;
}
public function getClassname(string $file): string
{
if (isset($this->cache['getClassname'][$file])) {
return $this->cache['getClassname'][$file];
}
$classname = $this->locator->getClassname($file);
$this->cache['getClassname'][$file] = $classname;
$this->cacheUpdated = true;
return $classname;
}
/**
* @return list<non-empty-string>
*/
public function search(string $path, string $ext = 'php', bool $prioritizeApp = true): array
{
if (isset($this->cache['search'][$path][$ext][$prioritizeApp])) {
return $this->cache['search'][$path][$ext][$prioritizeApp];
}
$foundPaths = $this->locator->search($path, $ext, $prioritizeApp);
$this->cache['search'][$path][$ext][$prioritizeApp] = $foundPaths;
$this->cacheUpdated = true;
return $foundPaths;
}
public function listFiles(string $path): array
{
if (isset($this->cache['listFiles'][$path])) {
return $this->cache['listFiles'][$path];
}
$files = $this->locator->listFiles($path);
$this->cache['listFiles'][$path] = $files;
$this->cacheUpdated = true;
return $files;
}
public function listNamespaceFiles(string $prefix, string $path): array
{
if (isset($this->cache['listNamespaceFiles'][$prefix][$path])) {
return $this->cache['listNamespaceFiles'][$prefix][$path];
}
$files = $this->locator->listNamespaceFiles($prefix, $path);
$this->cache['listNamespaceFiles'][$prefix][$path] = $files;
$this->cacheUpdated = true;
return $files;
}
public function locateFile(string $file, ?string $folder = null, string $ext = 'php'): false|string
{
if (isset($this->cache['locateFile'][$file][$folder][$ext])) {
return $this->cache['locateFile'][$file][$folder][$ext];
}
$files = $this->locator->locateFile($file, $folder, $ext);
$this->cache['locateFile'][$file][$folder][$ext] = $files;
$this->cacheUpdated = true;
return $files;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Autoloader/Autoloader.php | system/Autoloader/Autoloader.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\Autoloader;
use CodeIgniter\Exceptions\ConfigException;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Exceptions\RuntimeException;
use Composer\Autoload\ClassLoader;
use Composer\InstalledVersions;
use Config\Autoload;
use Config\Kint as KintConfig;
use Config\Modules;
use Kint\Kint;
use Kint\Renderer\CliRenderer;
use Kint\Renderer\RichRenderer;
/**
* An autoloader that uses both PSR4 autoloading, and traditional classmaps.
*
* Given a foo-bar package of classes in the file system at the following paths:
* ```
* /path/to/packages/foo-bar/
* /src
* Baz.php # Foo\Bar\Baz
* Qux/
* Quux.php # Foo\Bar\Qux\Quux
* ```
* you can add the path to the configuration array that is passed in the constructor.
* The Config array consists of 2 primary keys, both of which are associative arrays:
* 'psr4', and 'classmap'.
* ```
* $Config = [
* 'psr4' => [
* 'Foo\Bar' => '/path/to/packages/foo-bar'
* ],
* 'classmap' => [
* 'MyClass' => '/path/to/class/file.php'
* ]
* ];
* ```
* Example:
* ```
* <?php
* // our configuration array
* $Config = [ ... ];
* $loader = new \CodeIgniter\Autoloader\Autoloader($Config);
*
* // register the autoloader
* $loader->register();
* ```
*
* @see \CodeIgniter\Autoloader\AutoloaderTest
*/
class Autoloader
{
/**
* Stores namespaces as key, and path as values.
*
* @var array<non-empty-string, list<non-empty-string>>
*/
protected $prefixes = [];
/**
* Stores class name as key, and path as values.
*
* @var array<class-string, non-empty-string>
*/
protected $classmap = [];
/**
* Stores files as a list.
*
* @var list<non-empty-string>
*/
protected $files = [];
/**
* Stores helper list.
* Always load the URL helper, it should be used in most apps.
*
* @var list<non-empty-string>
*/
protected $helpers = ['url'];
/**
* Reads in the configuration array (described above) and stores
* the valid parts that we'll need.
*
* @return $this
*/
public function initialize(Autoload $config, Modules $modules)
{
$this->prefixes = [];
$this->classmap = [];
$this->files = [];
// We have to have one or the other, though we don't enforce the need
// to have both present in order to work.
if ($config->psr4 === [] && $config->classmap === []) {
throw new InvalidArgumentException('Config array must contain either the \'psr4\' key or the \'classmap\' key.');
}
if ($config->psr4 !== []) {
$this->addNamespace($config->psr4);
}
if ($config->classmap !== []) {
$this->classmap = $config->classmap;
}
if ($config->files !== []) {
$this->files = $config->files;
}
if ($config->helpers !== []) {
$this->helpers = [...$this->helpers, ...$config->helpers];
}
if (is_file(COMPOSER_PATH)) {
$this->loadComposerAutoloader($modules);
}
return $this;
}
private function loadComposerAutoloader(Modules $modules): void
{
// The path to the vendor directory.
// We do not want to enforce this, so set the constant if Composer was used.
if (! defined('VENDORPATH')) {
define('VENDORPATH', dirname(COMPOSER_PATH) . DIRECTORY_SEPARATOR);
}
/** @var ClassLoader $composer */
$composer = include COMPOSER_PATH;
// Should we load through Composer's namespaces, also?
if ($modules->discoverInComposer) {
$composerPackages = $modules->composerPackages;
$this->loadComposerNamespaces($composer, $composerPackages ?? []);
}
unset($composer);
}
/**
* Register the loader with the SPL autoloader stack
* in the following order:
*
* 1. Classmap loader
* 2. PSR-4 autoloader
* 3. Non-class files
*
* @return void
*/
public function register()
{
spl_autoload_register($this->loadClassmap(...), true);
spl_autoload_register($this->loadClass(...), true);
foreach ($this->files as $file) {
$this->includeFile($file);
}
}
/**
* Unregisters the autoloader from the SPL autoload stack.
*/
public function unregister(): void
{
spl_autoload_unregister($this->loadClass(...));
spl_autoload_unregister($this->loadClassmap(...));
}
/**
* Registers namespaces with the autoloader.
*
* @param array<non-empty-string, list<non-empty-string>|non-empty-string>|non-empty-string $namespace
*
* @return $this
*/
public function addNamespace($namespace, ?string $path = null)
{
if (is_array($namespace)) {
foreach ($namespace as $prefix => $namespacedPath) {
$prefix = trim($prefix, '\\');
if (is_array($namespacedPath)) {
foreach ($namespacedPath as $dir) {
$this->prefixes[$prefix][] = rtrim($dir, '\\/') . DIRECTORY_SEPARATOR;
}
continue;
}
$this->prefixes[$prefix][] = rtrim($namespacedPath, '\\/') . DIRECTORY_SEPARATOR;
}
} else {
$this->prefixes[trim($namespace, '\\')][] = rtrim($path, '\\/') . DIRECTORY_SEPARATOR;
}
return $this;
}
/**
* Get namespaces with prefixes as keys and paths as values.
*
* If a prefix param is set, returns only paths to the given prefix.
*
* @return ($prefix is null ? array<non-empty-string, list<non-empty-string>> : list<non-empty-string>)
*/
public function getNamespace(?string $prefix = null)
{
if ($prefix === null) {
return $this->prefixes;
}
return $this->prefixes[trim($prefix, '\\')] ?? [];
}
/**
* Removes a single namespace from the psr4 settings.
*
* @return $this
*/
public function removeNamespace(string $namespace)
{
if (isset($this->prefixes[trim($namespace, '\\')])) {
unset($this->prefixes[trim($namespace, '\\')]);
}
return $this;
}
/**
* Load a class using available class mapping.
*
* @param class-string $class The fully qualified class name.
*
* @internal For `spl_autoload_register` use.
*/
public function loadClassmap(string $class): void
{
$file = $this->classmap[$class] ?? '';
if (is_string($file) && $file !== '') {
$this->includeFile($file);
}
}
/**
* Loads the class file for a given class name.
*
* @param class-string $class The fully qualified class name.
*
* @internal For `spl_autoload_register` use.
*/
public function loadClass(string $class): void
{
$this->loadInNamespace($class);
}
/**
* Loads the class file for a given class name.
*
* @param class-string $class The fully qualified class name.
*
* @return false|non-empty-string The mapped file name on success, or boolean false on fail
*/
protected function loadInNamespace(string $class)
{
if (! str_contains($class, '\\')) {
return false;
}
foreach ($this->prefixes as $namespace => $directories) {
if (str_starts_with($class, $namespace)) {
$relativeClassPath = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, strlen($namespace)));
foreach ($directories as $directory) {
$directory = rtrim($directory, '\\/');
$filePath = $directory . $relativeClassPath . '.php';
$filename = $this->includeFile($filePath);
if ($filename !== false) {
return $filename;
}
}
}
}
return false;
}
/**
* A central way to include a file. Split out primarily for testing purposes.
*
* @return false|non-empty-string The filename on success, false if the file is not loaded
*/
protected function includeFile(string $file)
{
if (is_file($file)) {
include_once $file;
return $file;
}
return false;
}
/**
* Check file path.
*
* Checks special characters that are illegal in filenames on certain
* operating systems and special characters requiring special escaping
* to manipulate at the command line. Replaces spaces and consecutive
* dashes with a single dash. Trim period, dash and underscore from beginning
* and end of filename.
*
* @return string The sanitized filename
*
* @deprecated No longer used. See https://github.com/codeigniter4/CodeIgniter4/issues/7055
*/
public function sanitizeFilename(string $filename): string
{
// Only allow characters deemed safe for POSIX portable filenames.
// Plus the forward slash for directory separators since this might be a path.
// http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_278
// Modified to allow backslash and colons for on Windows machines.
$result = preg_match_all('/[^0-9\p{L}\s\/\-_.:\\\\]/u', $filename, $matches);
if ($result > 0) {
$chars = implode('', $matches[0]);
throw new InvalidArgumentException(
'The file path contains special characters "' . $chars
. '" that are not allowed: "' . $filename . '"',
);
}
if ($result === false) {
$message = preg_last_error_msg();
throw new RuntimeException($message . '. filename: "' . $filename . '"');
}
// Clean up our filename edges.
$cleanFilename = trim($filename, '.-_');
if ($filename !== $cleanFilename) {
throw new InvalidArgumentException('The characters ".-_" are not allowed in filename edges: "' . $filename . '"');
}
return $cleanFilename;
}
/**
* @param array{only?: list<string>, exclude?: list<string>} $composerPackages
*/
private function loadComposerNamespaces(ClassLoader $composer, array $composerPackages): void
{
$namespacePaths = $composer->getPrefixesPsr4();
// Get rid of duplicated namespaces.
$duplicatedNamespaces = ['CodeIgniter', APP_NAMESPACE, 'Config'];
foreach ($duplicatedNamespaces as $ns) {
if (isset($namespacePaths[$ns . '\\'])) {
unset($namespacePaths[$ns . '\\']);
}
}
if (! method_exists(InstalledVersions::class, 'getAllRawData')) { // @phpstan-ignore function.alreadyNarrowedType
throw new RuntimeException(
'Your Composer version is too old.'
. ' Please update Composer (run `composer self-update`) to v2.0.14 or later'
. ' and remove your vendor/ directory, and run `composer update`.',
);
}
// This method requires Composer 2.0.14 or later.
$allData = InstalledVersions::getAllRawData();
$packageList = [];
foreach ($allData as $list) {
$packageList = array_merge($packageList, $list['versions']);
}
// Check config for $composerPackages.
$only = $composerPackages['only'] ?? [];
$exclude = $composerPackages['exclude'] ?? [];
if ($only !== [] && $exclude !== []) {
throw new ConfigException('Cannot use "only" and "exclude" at the same time in "Config\Modules::$composerPackages".');
}
// Get install paths of packages to add namespace for auto-discovery.
$installPaths = [];
if ($only !== []) {
foreach ($packageList as $packageName => $data) {
if (in_array($packageName, $only, true) && isset($data['install_path'])) {
$installPaths[] = $data['install_path'];
}
}
} else {
foreach ($packageList as $packageName => $data) {
if (! in_array($packageName, $exclude, true) && isset($data['install_path'])) {
$installPaths[] = $data['install_path'];
}
}
}
$newPaths = [];
foreach ($namespacePaths as $namespace => $srcPaths) {
$add = false;
foreach ($srcPaths as $path) {
foreach ($installPaths as $installPath) {
if (str_starts_with($path, $installPath)) {
$add = true;
break 2;
}
}
}
if ($add) {
// Composer stores namespaces with trailing slash. We don't.
$newPaths[rtrim($namespace, '\\ ')] = $srcPaths;
}
}
$this->addNamespace($newPaths);
}
/**
* Locates autoload information from Composer, if available.
*
* @deprecated No longer used.
*
* @return void
*/
protected function discoverComposerNamespaces()
{
if (! is_file(COMPOSER_PATH)) {
return;
}
/**
* @var ClassLoader $composer
*/
$composer = include COMPOSER_PATH;
$paths = $composer->getPrefixesPsr4();
$classes = $composer->getClassMap();
unset($composer);
// Get rid of CodeIgniter so we don't have duplicates
if (isset($paths['CodeIgniter\\'])) {
unset($paths['CodeIgniter\\']);
}
$newPaths = [];
foreach ($paths as $key => $value) {
// Composer stores namespaces with trailing slash. We don't.
$newPaths[rtrim($key, '\\ ')] = $value;
}
$this->prefixes = array_merge($this->prefixes, $newPaths);
$this->classmap = array_merge($this->classmap, $classes);
}
/**
* Loads helpers
*/
public function loadHelpers(): void
{
helper($this->helpers);
}
/**
* Initializes Kint
*/
public function initializeKint(bool $debug = false): void
{
if ($debug) {
$this->autoloadKint();
$this->configureKint();
} elseif (class_exists(Kint::class)) {
// In case that Kint is already loaded via Composer.
Kint::$enabled_mode = false;
}
helper('kint');
}
private function autoloadKint(): void
{
// If we have KINT_DIR it means it's already loaded via composer
if (! defined('KINT_DIR')) {
spl_autoload_register(function ($class): void {
$class = explode('\\', $class);
if (array_shift($class) !== 'Kint') {
return;
}
$file = SYSTEMPATH . 'ThirdParty/Kint/' . implode('/', $class) . '.php';
if (is_file($file)) {
require_once $file;
}
});
require_once SYSTEMPATH . 'ThirdParty/Kint/init.php';
}
}
private function configureKint(): void
{
$config = new KintConfig();
Kint::$depth_limit = $config->maxDepth;
Kint::$display_called_from = $config->displayCalledFrom;
Kint::$expanded = $config->expanded;
if (isset($config->plugins) && is_array($config->plugins)) {
Kint::$plugins = $config->plugins;
}
$csp = service('csp');
if ($csp->enabled()) {
RichRenderer::$js_nonce = $csp->getScriptNonce();
RichRenderer::$css_nonce = $csp->getStyleNonce();
}
RichRenderer::$theme = $config->richTheme;
RichRenderer::$folder = $config->richFolder;
if (isset($config->richObjectPlugins) && is_array($config->richObjectPlugins)) {
RichRenderer::$value_plugins = $config->richObjectPlugins;
}
if (isset($config->richTabPlugins) && is_array($config->richTabPlugins)) {
RichRenderer::$tab_plugins = $config->richTabPlugins;
}
CliRenderer::$cli_colors = $config->cliColors;
CliRenderer::$force_utf8 = $config->cliForceUTF8;
CliRenderer::$detect_width = $config->cliDetectWidth;
CliRenderer::$min_terminal_width = $config->cliMinWidth;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Autoloader/FileLocator.php | system/Autoloader/FileLocator.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\Autoloader;
/**
* Allows loading non-class files in a namespaced manner.
* Works with Helpers, Views, etc.
*
* @see \CodeIgniter\Autoloader\FileLocatorTest
*/
class FileLocator implements FileLocatorInterface
{
/**
* The Autoloader to use.
*
* @var Autoloader
*/
protected $autoloader;
/**
* List of classnames that did not exist.
*
* @var list<class-string>
*/
private array $invalidClassnames = [];
public function __construct(Autoloader $autoloader)
{
$this->autoloader = $autoloader;
}
/**
* Attempts to locate a file by examining the name for a namespace
* and looking through the PSR-4 namespaced files that we know about.
*
* @param non-empty-string $file The relative file path or namespaced file to
* locate. If not namespaced, search in the app
* folder.
* @param non-empty-string|null $folder The folder within the namespace that we should
* look for the file. If $file does not contain
* this value, it will be appended to the namespace
* folder.
* @param string $ext The file extension the file should have.
*
* @return false|non-empty-string The path to the file, or false if not found.
*/
public function locateFile(string $file, ?string $folder = null, string $ext = 'php')
{
$file = $this->ensureExt($file, $ext);
// Clears the folder name if it is at the beginning of the filename
if ($folder !== null && str_starts_with($file, $folder)) {
$file = substr($file, strlen($folder . '/'));
}
// Is not namespaced? Try the application folder.
if (! str_contains($file, '\\')) {
return $this->legacyLocate($file, $folder);
}
// Standardize slashes to handle nested directories.
$file = strtr($file, '/', '\\');
$file = ltrim($file, '\\');
$segments = explode('\\', $file);
// The first segment will be empty if a slash started the filename.
if ($segments[0] === '') {
unset($segments[0]);
}
$paths = [];
$filename = '';
// Namespaces always comes with arrays of paths
$namespaces = $this->autoloader->getNamespace();
foreach (array_keys($namespaces) as $namespace) {
if (substr($file, 0, strlen($namespace) + 1) === $namespace . '\\') {
$fileWithoutNamespace = substr($file, strlen($namespace));
// There may be sub-namespaces of the same vendor,
// so overwrite them with namespaces found later.
$paths = $namespaces[$namespace];
$filename = ltrim(str_replace('\\', '/', $fileWithoutNamespace), '/');
}
}
// if no namespaces matched then quit
if ($paths === []) {
return false;
}
// Check each path in the namespace
foreach ($paths as $path) {
// Ensure trailing slash
$path = rtrim($path, '/') . '/';
// If we have a folder name, then the calling function
// expects this file to be within that folder, like 'Views',
// or 'libraries'.
if ($folder !== null && ! str_contains($path . $filename, '/' . $folder . '/')) {
$path .= trim($folder, '/') . '/';
}
$path .= $filename;
if (is_file($path)) {
return $path;
}
}
return false;
}
/**
* Examines a file and returns the fully qualified class name.
*/
public function getClassname(string $file): string
{
if (is_dir($file)) {
return '';
}
$php = file_get_contents($file);
$tokens = token_get_all($php);
$dlm = false;
$namespace = '';
$className = '';
foreach ($tokens as $i => $token) {
if ($i < 2) {
continue;
}
if ((isset($tokens[$i - 2][1]) && ($tokens[$i - 2][1] === 'phpnamespace' || $tokens[$i - 2][1] === 'namespace')) || ($dlm && $tokens[$i - 1][0] === T_NS_SEPARATOR && $token[0] === T_STRING)) {
if (! $dlm) {
$namespace = '';
}
if (isset($token[1])) {
$namespace = $namespace !== '' ? $namespace . '\\' . $token[1] : $token[1];
$dlm = true;
}
} elseif ($dlm && ($token[0] !== T_NS_SEPARATOR) && ($token[0] !== T_STRING)) {
$dlm = false;
}
if (
($tokens[$i - 2][0] === T_CLASS || (isset($tokens[$i - 2][1]) && $tokens[$i - 2][1] === 'phpclass'))
&& $tokens[$i - 1][0] === T_WHITESPACE
&& $token[0] === T_STRING
) {
$className = $token[1];
break;
}
}
if ($className === '') {
return '';
}
return $namespace . '\\' . $className;
}
/**
* Searches through all of the defined namespaces looking for a file.
* Returns an array of all found locations for the defined file.
*
* Example:
*
* $locator->search('Config/Routes.php');
* // Assuming PSR4 namespaces include foo and bar, might return:
* [
* 'app/Modules/foo/Config/Routes.php',
* 'app/Modules/bar/Config/Routes.php',
* ]
*
* @return list<non-empty-string>
*/
public function search(string $path, string $ext = 'php', bool $prioritizeApp = true): array
{
$path = $this->ensureExt($path, $ext);
$foundPaths = [];
$appPaths = [];
foreach ($this->getNamespaces() as $namespace) {
if (isset($namespace['path']) && is_file($namespace['path'] . $path)) {
$fullPath = $namespace['path'] . $path;
$resolvedPath = realpath($fullPath);
$fullPath = $resolvedPath !== false ? $resolvedPath : $fullPath;
if ($prioritizeApp) {
$foundPaths[] = $fullPath;
} elseif (str_starts_with($fullPath, APPPATH)) {
$appPaths[] = $fullPath;
} else {
$foundPaths[] = $fullPath;
}
}
}
if (! $prioritizeApp && $appPaths !== []) {
$foundPaths = [...$foundPaths, ...$appPaths];
}
return array_values(array_unique($foundPaths));
}
/**
* Ensures a extension is at the end of a filename
*/
protected function ensureExt(string $path, string $ext): string
{
if ($ext !== '') {
$ext = '.' . $ext;
if (! str_ends_with($path, $ext)) {
$path .= $ext;
}
}
return $path;
}
/**
* Return the namespace mappings we know about.
*
* @return list<array{prefix: non-empty-string, path: non-empty-string}>
*/
protected function getNamespaces()
{
$namespaces = [];
$system = [];
foreach ($this->autoloader->getNamespace() as $prefix => $paths) {
foreach ($paths as $path) {
if ($prefix === 'CodeIgniter') {
$system[] = [
'prefix' => $prefix,
'path' => rtrim($path, '\\/') . DIRECTORY_SEPARATOR,
];
continue;
}
$namespaces[] = [
'prefix' => $prefix,
'path' => rtrim($path, '\\/') . DIRECTORY_SEPARATOR,
];
}
}
// Save system for last
return array_merge($namespaces, $system);
}
public function findQualifiedNameFromPath(string $path)
{
$resolvedPath = realpath($path);
$path = $resolvedPath !== false ? $resolvedPath : $path;
if (! is_file($path)) {
return false;
}
foreach ($this->getNamespaces() as $namespace) {
$resolvedNamespacePath = realpath($namespace['path']);
$namespace['path'] = $resolvedNamespacePath !== false ? $resolvedNamespacePath : $namespace['path'];
if ($namespace['path'] === '') {
continue;
}
if (mb_strpos($path, $namespace['path']) === 0) {
$className = $namespace['prefix'] . '\\' .
ltrim(
str_replace(
'/',
'\\',
mb_substr($path, mb_strlen($namespace['path'])),
),
'\\',
);
// Remove the file extension (.php)
/** @var class-string $className */
$className = mb_substr($className, 0, -4);
if (in_array($className, $this->invalidClassnames, true)) {
continue;
}
if (class_exists($className)) {
return $className;
}
$this->invalidClassnames[] = $className;
}
}
return false;
}
/**
* Scans the defined namespaces, returning a list of all files
* that are contained within the subpath specified by $path.
*
* @return list<string> List of file paths
*/
public function listFiles(string $path): array
{
if ($path === '') {
return [];
}
$files = [];
helper('filesystem');
foreach ($this->getNamespaces() as $namespace) {
$fullPath = $namespace['path'] . $path;
$resolvedPath = realpath($fullPath);
$fullPath = $resolvedPath !== false ? $resolvedPath : $fullPath;
if (! is_dir($fullPath)) {
continue;
}
$tempFiles = get_filenames($fullPath, true, false, false);
if ($tempFiles !== []) {
$files = array_merge($files, $tempFiles);
}
}
return $files;
}
/**
* Scans the provided namespace, returning a list of all files
* that are contained within the sub path specified by $path.
*
* @return list<non-empty-string> List of file paths
*/
public function listNamespaceFiles(string $prefix, string $path): array
{
if ($path === '' || $prefix === '') {
return [];
}
$files = [];
helper('filesystem');
// autoloader->getNamespace($prefix) returns an array of paths for that namespace
foreach ($this->autoloader->getNamespace($prefix) as $namespacePath) {
$fullPath = rtrim($namespacePath, '/') . '/' . $path;
$resolvedPath = realpath($fullPath);
$fullPath = $resolvedPath !== false ? $resolvedPath : $fullPath;
if (! is_dir($fullPath)) {
continue;
}
$tempFiles = get_filenames($fullPath, true, false, false);
if ($tempFiles !== []) {
$files = array_merge($files, $tempFiles);
}
}
return $files;
}
/**
* Checks the app folder to see if the file can be found.
* Only for use with filenames that DO NOT include namespacing.
*
* @param non-empty-string|null $folder
*
* @return false|string The path to the file, or false if not found.
*/
protected function legacyLocate(string $file, ?string $folder = null)
{
$path = APPPATH . ($folder === null ? $file : $folder . '/' . $file);
$resolvedPath = realpath($path);
$path = $resolvedPath !== false ? $resolvedPath : $path;
if (is_file($path)) {
return $path;
}
return false;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/Language.php | system/Language/Language.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\Language;
use IntlException;
use MessageFormatter;
/**
* Handle system messages and localization.
*
* Locale-based, built on top of PHP internationalization.
*
* @see \CodeIgniter\Language\LanguageTest
*/
class Language
{
/**
* Stores the retrieved language lines
* from files for faster retrieval on
* second use.
*
* @var array
*/
protected $language = [];
/**
* The current language/locale to work with.
*
* @var string
*/
protected $locale;
/**
* Boolean value whether the intl
* libraries exist on the system.
*
* @var bool
*/
protected $intlSupport = false;
/**
* Stores filenames that have been
* loaded so that we don't load them again.
*
* @var array
*/
protected $loadedFiles = [];
public function __construct(string $locale)
{
$this->locale = $locale;
if (class_exists(MessageFormatter::class)) {
$this->intlSupport = true;
}
}
/**
* Sets the current locale to use when performing string lookups.
*
* @return $this
*/
public function setLocale(?string $locale = null)
{
if ($locale !== null) {
$this->locale = $locale;
}
return $this;
}
public function getLocale(): string
{
return $this->locale;
}
/**
* Parses the language string for a file, loads the file, if necessary,
* getting the line.
*
* @return list<string>|string
*/
public function getLine(string $line, array $args = [])
{
// if no file is given, just parse the line
if (! str_contains($line, '.')) {
return $this->formatMessage($line, $args);
}
// Parse out the file name and the actual alias.
// Will load the language file and strings.
[$file, $parsedLine] = $this->parseLine($line, $this->locale);
$output = $this->getTranslationOutput($this->locale, $file, $parsedLine);
if ($output === null && strpos($this->locale, '-')) {
[$locale] = explode('-', $this->locale, 2);
[$file, $parsedLine] = $this->parseLine($line, $locale);
$output = $this->getTranslationOutput($locale, $file, $parsedLine);
}
// if still not found, try English
if ($output === null) {
[$file, $parsedLine] = $this->parseLine($line, 'en');
$output = $this->getTranslationOutput('en', $file, $parsedLine);
}
$output ??= $line;
return $this->formatMessage($output, $args);
}
/**
* @return array|string|null
*/
protected function getTranslationOutput(string $locale, string $file, string $parsedLine)
{
$output = $this->language[$locale][$file][$parsedLine] ?? null;
if ($output !== null) {
return $output;
}
foreach (explode('.', $parsedLine) as $row) {
if (! isset($current)) {
$current = $this->language[$locale][$file] ?? null;
}
$output = $current[$row] ?? null;
if (is_array($output)) {
$current = $output;
}
}
if ($output !== null) {
return $output;
}
$row = current(explode('.', $parsedLine));
$key = substr($parsedLine, strlen($row) + 1);
return $this->language[$locale][$file][$row][$key] ?? null;
}
/**
* Parses the language string which should include the
* filename as the first segment (separated by period).
*/
protected function parseLine(string $line, string $locale): array
{
$file = substr($line, 0, strpos($line, '.'));
$line = substr($line, strlen($file) + 1);
if (! isset($this->language[$locale][$file]) || ! array_key_exists($line, $this->language[$locale][$file])) {
$this->load($file, $locale);
}
return [$file, $line];
}
/**
* Advanced message formatting.
*
* @param array|string $message
* @param list<string> $args
*
* @return array|string
*/
protected function formatMessage($message, array $args = [])
{
if (! $this->intlSupport || $args === []) {
return $message;
}
if (is_array($message)) {
foreach ($message as $index => $value) {
$message[$index] = $this->formatMessage($value, $args);
}
return $message;
}
$formatted = MessageFormatter::formatMessage($this->locale, $message, $args);
if ($formatted === false) {
// Format again to get the error message.
try {
$fmt = new MessageFormatter($this->locale, $message);
$formatted = $fmt->format($args);
$fmtError = '"' . $fmt->getErrorMessage() . '" (' . $fmt->getErrorCode() . ')';
} catch (IntlException $e) {
$fmtError = '"' . $e->getMessage() . '" (' . $e->getCode() . ')';
}
$argsString = implode(
', ',
array_map(static fn ($element): string => '"' . $element . '"', $args),
);
$argsUrlEncoded = implode(
', ',
array_map(static fn ($element): string => '"' . rawurlencode($element) . '"', $args),
);
log_message(
'error',
'Language.invalidMessageFormat: $message: "' . $message
. '", $args: ' . $argsString
. ' (urlencoded: ' . $argsUrlEncoded . '),'
. ' MessageFormatter Error: ' . $fmtError,
);
return $message . "\n【Warning】Also, invalid string(s) was passed to the Language class. See log file for details.";
}
return $formatted;
}
/**
* Loads a language file in the current locale. If $return is true,
* will return the file's contents, otherwise will merge with
* the existing language lines.
*
* @return list<mixed>|null
*/
protected function load(string $file, string $locale, bool $return = false)
{
if (! array_key_exists($locale, $this->loadedFiles)) {
$this->loadedFiles[$locale] = [];
}
if (in_array($file, $this->loadedFiles[$locale], true)) {
// Don't load it more than once.
return [];
}
if (! array_key_exists($locale, $this->language)) {
$this->language[$locale] = [];
}
if (! array_key_exists($file, $this->language[$locale])) {
$this->language[$locale][$file] = [];
}
$path = "Language/{$locale}/{$file}.php";
$lang = $this->requireFile($path);
if ($return) {
return $lang;
}
$this->loadedFiles[$locale][] = $file;
// Merge our string
$this->language[$locale][$file] = $lang;
return null;
}
/**
* A simple method for including files that can be
* overridden during testing.
*/
protected function requireFile(string $path): array
{
$files = service('locator')->search($path, 'php', false);
$strings = [];
foreach ($files as $file) {
// On some OS's we were seeing failures
// on this command returning boolean instead
// of array during testing, so we've removed
// the require_once for now.
if (is_file($file)) {
$strings[] = require $file;
}
}
if (isset($strings[1])) {
$string = array_shift($strings);
$strings = array_replace_recursive($string, ...$strings);
} elseif (isset($strings[0])) {
$strings = $strings[0];
}
return $strings;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Encryption.php | system/Language/en/Encryption.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.
*/
// Encryption language settings
return [
'noDriverRequested' => 'No driver requested; Miss Daisy will be so upset!',
'noHandlerAvailable' => 'Unable to find an available "{0}" encryption handler.',
'unKnownHandler' => '"{0}" cannot be configured.',
'starterKeyNeeded' => 'Encrypter needs a starter key.',
'authenticationFailed' => 'Decrypting: authentication failed.',
'encryptionFailed' => 'Encryption failed.',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Number.php | system/Language/en/Number.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.
*/
// Number language settings
return [
'terabyteAbbr' => 'TB',
'gigabyteAbbr' => 'GB',
'megabyteAbbr' => 'MB',
'kilobyteAbbr' => 'KB',
'bytes' => 'Bytes',
// don't forget the space in front of these!
'thousand' => ' thousand',
'million' => ' million',
'billion' => ' billion',
'trillion' => ' trillion',
'quadrillion' => ' quadrillion',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Database.php | system/Language/en/Database.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.
*/
// Database language settings
return [
'invalidEvent' => '"{0}" is not a valid Model Event callback.',
'invalidArgument' => 'You must provide a valid "{0}".',
'invalidAllowedFields' => 'Allowed fields must be specified for model: "{0}"',
'emptyDataset' => 'There is no data to {0}.',
'emptyPrimaryKey' => 'There is no primary key defined when trying to make {0}.',
'failGetFieldData' => 'Failed to get field data from database.',
'failGetIndexData' => 'Failed to get index data from database.',
'failGetForeignKeyData' => 'Failed to get foreign key data from database.',
'parseStringFail' => 'Parsing key string failed.',
'featureUnavailable' => 'This feature is not available for the database you are using.',
'tableNotFound' => 'Table "{0}" was not found in the current database.',
'noPrimaryKey' => '"{0}" model class does not specify a Primary Key.',
'noDateFormat' => '"{0}" model class does not have a valid dateFormat.',
'fieldNotExists' => 'Field "{0}" not found.',
'forEmptyInputGiven' => 'Empty statement is given for the field "{0}"',
'forFindColumnHaveMultipleColumns' => 'Only single column allowed in Column name.',
'methodNotAvailable' => 'You cannot use "{1}" in "{0}". This is a method of the Query Builder Class.',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/HTTP.php | system/Language/en/HTTP.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.
*/
// HTTP language settings
return [
// CurlRequest
'missingCurl' => 'CURL must be enabled to use the CURLRequest class.',
'invalidSSLKey' => 'Cannot set SSL Key. "{0}" is not a valid file.',
'sslCertNotFound' => 'SSL certificate not found at: "{0}"',
'curlError' => '{0} : {1}',
// IncomingRequest
'invalidNegotiationType' => '"{0}" is not a valid negotiation type. Must be one of: media, charset, encoding, language.',
'invalidJSON' => 'Failed to parse JSON string. Error: {0}',
'unsupportedJSONFormat' => 'The provided JSON format is not supported.',
// Message
'invalidHTTPProtocol' => 'Invalid HTTP Protocol Version: {0}',
// Negotiate
'emptySupportedNegotiations' => 'You must provide an array of supported values to all Negotiations.',
// RedirectResponse
'invalidRoute' => 'The route for "{0}" cannot be found.',
// DownloadResponse
'cannotSetBinary' => 'When setting filepath cannot set binary.',
'cannotSetFilepath' => 'When setting binary cannot set filepath: "{0}"',
'notFoundDownloadSource' => 'Not found download body source.',
'cannotSetCache' => 'It does not support caching for downloading.',
'cannotSetStatusCode' => 'It does not support change status code for downloading. code: {0}, reason: {1}',
// Response
'missingResponseStatus' => 'HTTP Response is missing a status code',
'invalidStatusCode' => '{0} is not a valid HTTP return status code',
'unknownStatusCode' => 'Unknown HTTP status code provided with no message: {0}',
// URI
'cannotParseURI' => 'Unable to parse URI: "{0}"',
'segmentOutOfRange' => 'Request URI segment is out of range: "{0}"',
'invalidPort' => 'Ports must be between 0 and 65535. Given: {0}',
'malformedQueryString' => 'Query strings may not include URI fragments.',
// Page Not Found
'pageNotFound' => 'Page Not Found',
'emptyController' => 'No Controller specified.',
'controllerNotFound' => 'Controller or its method is not found: {0}::{1}',
'methodNotFound' => 'Controller method is not found: "{0}"',
'localeNotSupported' => 'Locale is not supported: {0}',
// CSRF
// @deprecated use 'Security.disallowedAction'
'disallowedAction' => 'The action you requested is not allowed.',
// Uploaded file moving
'alreadyMoved' => 'The uploaded file has already been moved.',
'invalidFile' => 'The original file is not a valid file.',
'moveFailed' => 'Could not move file "{0}" to "{1}". Reason: {2}',
'uploadErrOk' => 'The file uploaded with success.',
'uploadErrIniSize' => 'The file "%s" exceeds your upload_max_filesize ini directive.',
'uploadErrFormSize' => 'The file "%s" exceeds the upload limit defined in your form.',
'uploadErrPartial' => 'The file "%s" was only partially uploaded.',
'uploadErrNoFile' => 'No file was uploaded.',
'uploadErrCantWrite' => 'The file "%s" could not be written on disk.',
'uploadErrNoTmpDir' => 'File could not be uploaded: missing temporary directory.',
'uploadErrExtension' => 'File upload was stopped by a PHP extension.',
'uploadErrUnknown' => 'The file "%s" was not uploaded due to an unknown error.',
// SameSite setting
// @deprecated
'invalidSameSiteSetting' => '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/Time.php | system/Language/en/Time.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.
*/
// Time language settings
return [
'invalidFormat' => '"{0}" is not a valid datetime format',
'invalidMonth' => 'Months must be between 1 and 12. Given: {0}',
'invalidDay' => 'Days must be between 1 and 31. Given: {0}',
'invalidOverDay' => 'Days must be between 1 and {0}. Given: {1}',
'invalidHours' => 'Hours must be between 0 and 23. Given: {0}',
'invalidMinutes' => 'Minutes must be between 0 and 59. Given: {0}',
'invalidSeconds' => 'Seconds must be between 0 and 59. Given: {0}',
'years' => '{0, plural, =1{# year} other{# years}}',
'months' => '{0, plural, =1{# month} other{# months}}',
'weeks' => '{0, plural, =1{# week} other{# weeks}}',
'days' => '{0, plural, =1{# day} other{# days}}',
'hours' => '{0, plural, =1{# hour} other{# hours}}',
'minutes' => '{0, plural, =1{# minute} other{# minutes}}',
'seconds' => '{0, plural, =1{# second} other{# seconds}}',
'ago' => '{0} ago',
'inFuture' => 'in {0}',
'yesterday' => 'Yesterday',
'tomorrow' => 'Tomorrow',
'now' => 'Just now',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Images.php | system/Language/en/Images.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.
*/
// Images language settings
return [
'sourceImageRequired' => 'You must specify a source image in your preferences.',
'gdRequired' => 'The GD image library is required to use this feature.',
'gdRequiredForProps' => 'Your server must support the GD image library in order to determine the image properties.',
'gifNotSupported' => 'GIF images are often not supported due to licensing restrictions. You may have to use JPG or PNG images instead.',
'jpgNotSupported' => 'JPG images are not supported.',
'pngNotSupported' => 'PNG images are not supported.',
'webpNotSupported' => 'WEBP images are not supported.',
'fileNotSupported' => 'The supplied file is not a supported image type.',
'unsupportedImageCreate' => 'Your server does not support the GD function required to process this type of image.',
'jpgOrPngRequired' => 'The image resize protocol specified in your preferences only works with JPEG or PNG image types.',
'rotateUnsupported' => 'Image rotation does not appear to be supported by your server.',
'libPathInvalid' => 'The path to your image library is not correct. Please set the correct path in your image preferences. "{0}"',
'imageProcessFailed' => 'Image processing failed. Please verify that your server supports the chosen protocol and that the path to your image library is correct.',
'rotationAngleRequired' => 'An angle of rotation is required to rotate the image.',
'invalidPath' => 'The path to the image is not correct.',
'copyFailed' => 'The image copy routine failed.',
'missingFont' => 'Unable to find a font to use.',
'saveFailed' => 'Unable to save the image. Please make sure the image and file directory are writable.',
'invalidDirection' => 'Flip direction can be only "vertical" or "horizontal". Given: "{0}"',
'exifNotSupported' => 'Reading EXIF data is not supported by this PHP installation.',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Test.php | system/Language/en/Test.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.
*/
// Testing language settings
return [
'invalidMockClass' => '"{0}" is not a valid Mock class',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Language.php | system/Language/en/Language.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.
*/
// "Language" language settings
return [
'invalidMessageFormat' => 'Invalid message format: "{0}", args: "{1}"',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Filters.php | system/Language/en/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.
*/
// Filters language settings
return [
'noFilter' => '"{0}" filter must have a matching alias defined.',
'incorrectInterface' => '"{0}" must implement CodeIgniter\Filters\FilterInterface.',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Email.php | system/Language/en/Email.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.
*/
// Email language settings
return [
'mustBeArray' => 'The email validation method must be passed an array.',
'invalidAddress' => 'Invalid email address: "{0}"',
'attachmentMissing' => 'Unable to locate the following email attachment: "{0}"',
'attachmentUnreadable' => 'Unable to open this attachment: "{0}"',
'noFrom' => 'Cannot send mail with no "From" header.',
'noRecipients' => 'You must include recipients: To, Cc, or Bcc',
'sendFailurePHPMail' => 'Unable to send email using PHP mail(). Your server might not be configured to send mail using this method.',
'sendFailureSendmail' => 'Unable to send email using Sendmail. Your server might not be configured to send mail using this method.',
'sendFailureSmtp' => 'Unable to send email using SMTP. Your server might not be configured to send mail using this method.',
'sent' => 'Your message has been successfully sent using the following protocol: {0}',
'noSocket' => 'Unable to open a socket to Sendmail. Please check settings.',
'noHostname' => 'You did not specify a SMTP hostname.',
'SMTPError' => 'The following SMTP error was encountered: {0}',
'noSMTPAuth' => 'Error: You must assign an SMTP username and password.',
'failedSMTPLogin' => 'Failed to send AUTH LOGIN command. Error: {0}',
'SMTPAuthUsername' => 'Failed to authenticate username. Error: {0}',
'SMTPAuthPassword' => 'Failed to authenticate password. Error: {0}',
'SMTPDataFailure' => 'Unable to send data: {0}',
'exitStatus' => 'Exit status code: {0}',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Fabricator.php | system/Language/en/Fabricator.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.
*/
// Fabricator language settings
return [
'invalidModel' => 'Invalid model supplied for fabrication.',
'missingFormatters' => 'No valid formatters defined.',
'createFailed' => 'Fabricator failed to insert on table "{0}": {1}',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Core.php | system/Language/en/Core.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.
*/
// Core language settings
return [
'copyError' => 'An error was encountered while attempting to replace the file "{0}". Please make sure your file directory is writable.',
'enabledZlibOutputCompression' => 'Your zlib.output_compression ini directive is turned on. This will not work well with output buffers.',
'invalidFile' => 'Invalid file: "{0}"',
'invalidDirectory' => 'Directory does not exist: "{0}"',
'invalidPhpVersion' => 'Your PHP version must be {0} or higher to run CodeIgniter. Current version: {1}',
'missingExtension' => 'The framework needs the following extension(s) installed and loaded: "{0}".',
'noHandlers' => '"{0}" must provide at least one Handler.',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Errors.php | system/Language/en/Errors.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.
*/
// Errors language settings
return [
'pageNotFound' => '404 - Page Not Found',
'sorryCannotFind' => 'Sorry! Cannot seem to find the page you were looking for.',
'badRequest' => '400 - Bad Request',
'sorryBadRequest' => 'Sorry! Something is wrong with your request.',
'whoops' => 'Whoops!',
'weHitASnag' => 'We seem to have hit a snag. Please try again later...',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Log.php | system/Language/en/Log.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.
*/
// Log language settings
return [
'invalidLogLevel' => '"{0}" is an invalid log level.',
'invalidMessageType' => 'The given message type "{0}" is not supported.',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Security.php | system/Language/en/Security.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.
*/
// Security language settings
return [
'disallowedAction' => 'The action you requested is not allowed.',
'insecureCookie' => 'Attempted to send a secure cookie over a non-secure connection.',
// @deprecated
'invalidSameSite' => 'The SameSite value 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/Cast.php | system/Language/en/Cast.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.
*/
// Cast language settings
return [
'baseCastMissing' => 'The "{0}" class must inherit the "CodeIgniter\Entity\Cast\BaseCast" class.',
'invalidCastMethod' => 'The "{0}" is invalid cast method, valid methods are: ["get", "set"].',
'invalidTimestamp' => 'Type casting "timestamp" expects a correct timestamp.',
'jsonErrorCtrlChar' => 'Unexpected control character found.',
'jsonErrorDepth' => 'Maximum stack depth exceeded.',
'jsonErrorStateMismatch' => 'Underflow or the modes mismatch.',
'jsonErrorSyntax' => 'Syntax error, malformed JSON.',
'jsonErrorUnknown' => 'Unknown error.',
'jsonErrorUtf8' => 'Malformed UTF-8 characters, possibly incorrectly encoded.',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Publisher.php | system/Language/en/Publisher.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.
*/
// Publisher language settings
return [
'collision' => 'Publisher encountered an unexpected "{0}" while copying "{1}" to "{2}".',
'destinationNotAllowed' => 'Destination is not on the allowed list of Publisher directories: "{0}"',
'fileNotAllowed' => '"{0}" fails the following restriction for "{1}": {2}',
// Publish Command
'publishMissing' => 'No Publisher classes detected in {0} across all namespaces.',
'publishMissingNamespace' => 'No Publisher classes detected in {0} in the {1} namespace.',
'publishSuccess' => '"{0}" published {1} file(s) to "{2}".',
'publishFailure' => '"{0}" failed to publish to "{1}".',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/CLI.php | system/Language/en/CLI.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.
*/
// CLI language settings
return [
'altCommandPlural' => 'Did you mean one of these?',
'altCommandSingular' => 'Did you mean this?',
'commandNotFound' => 'Command "{0}" not found.',
'generator' => [
'cancelOperation' => 'Operation has been cancelled.',
'className' => [
'cell' => 'Cell class name',
'command' => 'Command class name',
'config' => 'Config class name',
'controller' => 'Controller class name',
'default' => 'Class name',
'entity' => 'Entity class name',
'filter' => 'Filter class name',
'migration' => 'Migration class name',
'model' => 'Model class name',
'seeder' => 'Seeder class name',
'test' => 'Test class name',
'validation' => 'Validation class name',
],
'commandType' => 'Command type',
'databaseGroup' => 'Database group',
'fileCreate' => 'File created: {0}',
'fileError' => 'Error while creating file: "{0}"',
'fileExist' => 'File exists: "{0}"',
'fileOverwrite' => 'File overwritten: "{0}"',
'parentClass' => 'Parent class',
'returnType' => 'Return type',
'tableName' => 'Table name',
'usingCINamespace' => 'Warning: Using the "CodeIgniter" namespace will generate the file in the system directory.',
'viewName' => [
'cell' => 'Cell view name',
],
],
'helpArguments' => 'Arguments:',
'helpDescription' => 'Description:',
'helpOptions' => 'Options:',
'helpUsage' => 'Usage:',
'invalidColor' => 'Invalid "{0}" color: "{1}".',
'namespaceNotDefined' => 'Namespace "{0}" is not defined.',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Format.php | system/Language/en/Format.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.
*/
// Format language settings
return [
'invalidFormatter' => '"{0}" is not a valid Formatter class.',
'invalidJSON' => 'Failed to parse JSON string. Error: {0}',
'invalidMime' => 'No Formatter defined for mime type: "{0}".',
'missingExtension' => 'The SimpleXML extension is required to format XML.',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Cookie.php | system/Language/en/Cookie.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.
*/
// Cookie language settings
return [
'invalidExpiresTime' => 'Invalid "{0}" type for "Expires" attribute. Expected: string, integer, DateTimeInterface object.',
'invalidExpiresValue' => 'The cookie expiration time is not valid.',
'invalidCookieName' => 'The cookie name "{0}" contains invalid characters.',
'emptyCookieName' => 'The cookie name cannot be empty.',
'invalidSecurePrefix' => 'Using the "__Secure-" prefix requires setting the "Secure" attribute.',
'invalidHostPrefix' => 'Using the "__Host-" prefix must be set with the "Secure" flag, must not have a "Domain" attribute, and the "Path" is set to "/".',
'invalidSameSite' => 'The SameSite value must be None, Lax, Strict or a blank string, {0} given.',
'invalidSameSiteNone' => 'Using the "SameSite=None" attribute requires setting the "Secure" attribute.',
'invalidCookieInstance' => '"{0}" class expected cookies array to be instances of "{1}" but got "{2}" at index {3}.',
'unknownCookieInstance' => 'Cookie object with name "{0}" and prefix "{1}" was not found in the collection.',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Language/en/Router.php | system/Language/en/Router.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.
*/
// Router language settings
return [
'invalidParameter' => 'A parameter does not match the expected type.',
'missingDefaultRoute' => 'Unable to determine what should be displayed. A default route has not been specified in the routing file.',
'invalidDynamicController' => 'A dynamic controller is not allowed for security reasons. Route handler: "{0}"',
'invalidControllerName' => 'The namespace delimiter is a backslash (\), not a slash (/). Route handler: "{0}"',
];
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.