Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions system/Cache/Handlers/MemcachedHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,11 @@ public function decrement(string $key, int $offset = 1): false|int

$key = static::validateKey($key, $this->prefix);

// FIXME: third parameter isn't other handler actions.

return $this->memcached->decrement($key, $offset, $offset, 60);
// Memcached counters are unsigned and saturate at 0, so a missing
// key can only ever be initialized to 0, never a negative value.
// Use Memcached::decrement()'s own default of 0 as the initial
// value instead of $offset, so a new key no longer starts positive.
return $this->memcached->decrement($key, $offset, 0, 60);
}

public function clean(): bool
Expand Down
38 changes: 19 additions & 19 deletions system/CodeIgniter.php
Original file line number Diff line number Diff line change
Expand Up @@ -505,29 +505,29 @@ protected function handleRequest(?RouteCollectionInterface $routes, Cache $cache
// If startController returned a Response (from an attribute or Closure), use it
if ($returned instanceof ResponseInterface) {
$this->gatherOutput($cacheConfig, $returned);
}
// Closure controller has run in startController().
elseif (! is_callable($this->controller)) {
$controller = $this->createController();
} else {
// Closure controller has run in startController().
if (! is_callable($this->controller)) {
$controller = $this->createController();

if (! method_exists($controller, '_remap') && ! is_callable([$controller, $this->method], false)) {
throw PageNotFoundException::forMethodNotFound($this->method);
}
if (! method_exists($controller, '_remap') && ! is_callable([$controller, $this->method], false)) {
throw PageNotFoundException::forMethodNotFound($this->method);
}

// Is there a "post_controller_constructor" event?
Events::trigger('post_controller_constructor');
// Is there a "post_controller_constructor" event?
Events::trigger('post_controller_constructor');

$returned = $this->runController($controller);
} else {
$this->benchmark->stop('controller_constructor');
$this->benchmark->stop('controller');
}

// If $returned is a string, then the controller output something,
// probably a view, instead of echoing it directly. Send it along
// so it can be used with the output.
$this->gatherOutput($cacheConfig, $returned);
$returned = $this->runController($controller);
} else {
$this->benchmark->stop('controller_constructor');
$this->benchmark->stop('controller');
}

// If $returned is a string, then the controller output something,
// probably a view, instead of echoing it directly. Send it along
// so it can be used with the output.
$this->gatherOutput($cacheConfig, $returned);
}
if ($this->enableFilters) {
/** @var Filters $filters */
$filters = service('filters');
Expand Down
32 changes: 15 additions & 17 deletions system/Database/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public function load(array $params = [], string $alias = '')
throw new InvalidArgumentException('You have not selected a database type to connect to.');
}

assert($this->checkDbExtension($params['DBDriver']));
$this->checkDbExtension($params['DBDriver']);

$this->connections[$alias] = $this->initDriver($params['DBDriver'], 'Connection', $params);

Expand Down Expand Up @@ -154,15 +154,17 @@ protected function initDriver(string $driver, string $class, $argument): object
}

/**
* Check the PHP database extension is loaded.
* Check if the PHP database extension is loaded.
*
* @param string $driver DB driver or FQCN for custom driver
*
* @throws ConfigException if the driver is invalid
* @throws CriticalError if the required PHP extension is not loaded
*/
private function checkDbExtension(string $driver): bool
private function checkDbExtension(string $driver): void
{
if (str_contains($driver, '\\')) {
// Cannot check a fully qualified classname for a custom driver.
return true;
return; // Cannot check a fully qualified classname for a custom driver.
}

$extensionMap = [
Expand All @@ -174,21 +176,17 @@ private function checkDbExtension(string $driver): bool
'OCI8' => 'oci8',
];

$extension = $extensionMap[$driver] ?? '';

if ($extension === '') {
$message = 'Invalid DBDriver name: "' . $driver . '"';

throw new ConfigException($message);
}
$extension = $extensionMap[$driver]
?? throw new ConfigException(sprintf('Invalid DBDriver name: "%s".', $driver));

if (extension_loaded($extension)) {
return true;
return;
}

$message = 'The required PHP extension "' . $extension . '" is not loaded.'
. ' Install and enable it to use "' . $driver . '" driver.';

throw new CriticalError($message);
throw new CriticalError(sprintf(
'The required PHP extension "%s" is not loaded. Install and enable it to use "%s" driver.',
$extension,
$driver,
));
}
}
9 changes: 8 additions & 1 deletion system/Database/SQLite3/Table.php
Original file line number Diff line number Diff line change
Expand Up @@ -333,9 +333,16 @@ protected function createTable()
}

foreach ($this->foreignKeys as $foreignKey) {
$foreignTableName = $foreignKey->foreign_table_name;
$prefix = $this->db->DBPrefix;

if ($prefix !== '' && str_starts_with($foreignTableName, $prefix)) {
$foreignTableName = substr($foreignTableName, strlen($prefix));
}

$this->forge->addForeignKey(
$foreignKey->column_name,
trim($foreignKey->foreign_table_name, $this->db->DBPrefix),
$foreignTableName,
$foreignKey->foreign_column_name,
);
}
Expand Down
2 changes: 1 addition & 1 deletion system/Files/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ public function move(string $targetPath, ?string $name = null, bool $overwrite =
throw FileException::forUnableToMove($this->getBasename(), $targetPath, strip_tags($error['message']));
}

@chmod($destination, 0777 & ~umask());
@chmod($destination, 0666 & ~umask());

return new self($destination);
}
Expand Down
2 changes: 1 addition & 1 deletion system/HTTP/Files/FileCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ protected function createFileObject(array $array)

return new UploadedFile(
$array['tmp_name'] ?? null,
$array['name'] ?? null,
$array['name'],
$array['type'] ?? null,
($array['size'] ?? null) === null ? null : (int) $array['size'],
$array['error'] ?? null,
Expand Down
2 changes: 1 addition & 1 deletion system/HTTP/Files/UploadedFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ public function move(string $targetPath, ?string $name = null, bool $overwrite =
throw HTTPException::forMoveFailed(basename($this->path), $targetPath, $message);
}

@chmod($targetPath, 0777 & ~umask());
@chmod($destination, 0666 & ~umask());

// Success, so store our new information
$this->path = $targetPath;
Expand Down
2 changes: 1 addition & 1 deletion system/HTTP/SiteURIFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ private function createURIFromRoutePath(string $routePath): SiteURI
*/
private function getHost(): ?string
{
$httpHostPort = $this->superglobals->server('HTTP_HOST') ?? null;
$httpHostPort = $this->superglobals->server('HTTP_HOST');

if ($httpHostPort !== null) {
[$httpHost] = explode(':', $httpHostPort, 2);
Expand Down
2 changes: 1 addition & 1 deletion system/Helpers/Array/ArrayHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ public static function recursiveCount(array $array, int $counter = 0): int
* @param list<int|list<int|string>|string> $array
* @param int|string|null $sortByIndex
*/
public static function sortValuesByNatural(array &$array, $sortByIndex = null): bool
public static function sortValuesByNatural(array &$array, $sortByIndex = null): true
{
return usort($array, static function ($currentValue, $nextValue) use ($sortByIndex): int {
if ($sortByIndex !== null) {
Expand Down
2 changes: 1 addition & 1 deletion system/Router/RouteCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1520,7 +1520,7 @@ private function checkSubdomains($subdomains): bool

// Routes can be limited to any sub-domain. In that case, though,
// it does require a sub-domain to be present.
if (! in_array($this->currentSubdomain, [null, ''], true) && in_array('*', $subdomains, true)) {
if ($this->currentSubdomain !== '' && in_array('*', $subdomains, true)) {
return true;
}

Expand Down
7 changes: 6 additions & 1 deletion tests/system/Cache/Handlers/MemcachedHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,12 @@ public function testDecrement(): void

$this->assertSame(9, $memcachedHandler->decrement(self::$key1, 1));
$this->assertFalse($memcachedHandler->decrement(self::$key2, 1));
$this->assertSame(1, $memcachedHandler->decrement(self::$key3, 1));
// A key that doesn't exist yet starts at 0, not at the offset
// (Memcached counters are unsigned, so it can't start negative).
$this->assertSame(0, $memcachedHandler->decrement(self::$key3, 5));
// Memcached stores counter values as decimal strings on the wire, so
// a plain get() on a counter key returns a string, not an int.
$this->assertSame('0', $memcachedHandler->get(self::$key3));
}

public function testClean(): void
Expand Down
33 changes: 33 additions & 0 deletions tests/system/CodeIgniterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1308,4 +1308,37 @@ public function testResetForWorkerMode(): void
$this->assertSame($csp->getStyleNonce(), RichRenderer::$css_nonce);
$this->assertTrue(RichRenderer::$needs_pre_render);
}

public function testGatherOutputCalledOnceWhenControllerReturnsResponse(): void
{
$this->resetServices();

$superglobals = service('superglobals');
$superglobals->setServer('argv', ['index.php', 'pages/test']);
$superglobals->setServer('argc', 2);
$superglobals->setServer('REQUEST_URI', '/pages/test');
$superglobals->setServer('SCRIPT_NAME', '/index.php');

$routes = service('routes');
$routes->add('pages/test', static fn () => service('response')->setBody('Test Body'));

$config = new App();
$codeigniter = new class ($config) extends MockCodeIgniter {
public int $gatherOutputCalls = 0;

protected function gatherOutput(?Cache $cacheConfig = null, $returned = null): void
{
$this->gatherOutputCalls++;
parent::gatherOutput($cacheConfig, $returned);
}
};

ob_start();
$codeigniter->run($routes);
ob_end_clean();

// When startController() returns a ResponseInterface (e.g. from a closure route),
// gatherOutput() must be called exactly once — not twice as in the original bug.
$this->assertSame(1, $codeigniter->gatherOutputCalls);
}
}
62 changes: 62 additions & 0 deletions tests/system/Database/Live/SQLite3/AlterTableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,68 @@ public function testProcessCopiesOldData(): void
$this->seeInDatabase('foo', ['email' => 'funkalicious@example.com']);
}

public function testDropColumnKeepsForeignKeyTableNameWhenPrefixIsSet(): void
{
$config = [
'DBDriver' => 'SQLite3',
'database' => ':memory:',
'DBDebug' => true,
'DBPrefix' => 'db_',
];

$db = db_connect($config, false);
$this->assertInstanceOf(Connection::class, $db);

$forge = Database::forge($db);
$this->assertInstanceOf(Forge::class, $forge);

// The referenced table must begin with a character that also appears in
// the prefix, or the prefix stripping cannot damage its name.
$forge->addField([
'id' => [
'type' => 'integer',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
]);
$forge->addPrimaryKey('id');
$forge->createTable('bandit_fk');

$forge->addField([
'id' => [
'type' => 'integer',
'constraint' => 11,
'unsigned' => true,
'auto_increment' => true,
],
'key_id' => [
'type' => 'integer',
'constraint' => 11,
'unsigned' => true,
],
'name' => [
'type' => 'varchar',
'constraint' => 255,
'null' => true,
],
]);
$forge->addPrimaryKey('id');
$forge->addForeignKey('key_id', 'bandit_fk', 'id');
$forge->createTable('bandit');

// Dropping a column rebuilds the table, recreating its foreign keys.
$this->assertTrue($forge->dropColumn('bandit', 'name'));

$keys = array_values($db->getForeignKeyData('bandit'));

$this->assertCount(1, $keys);
$this->assertSame($db->DBPrefix . 'bandit_fk', $keys[0]->foreign_table_name);

$forge->dropTable('bandit', true);
$forge->dropTable('bandit_fk', true);
}

protected function createTable(string $tableName = 'foo'): void
{
// Create support table for foreign keys
Expand Down
9 changes: 9 additions & 0 deletions tests/system/Files/FileWithVfsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,4 +150,13 @@ public function testMoveReturnsNewInstance(): void
$this->assertInstanceOf(File::class, $file);
$this->assertSame($destination . '/apple.php', $file->getPathname());
}

public function testMovePermissions(): void
{
$destination = $this->start . 'baker';
$this->file->move($destination);

$expectedPerms = 0666 & ~umask();
$this->assertSame($expectedPerms, $this->root->getChild('baker/apple.php')->getPermissions());
}
}
1 change: 1 addition & 0 deletions tests/system/HTTP/Files/FileMovingTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ public function testMove(): void

$this->assertTrue($this->root->hasChild('destination/' . $finalFilename . '.txt'));
$this->assertTrue($this->root->hasChild('destination/' . $finalFilename . '_1.txt'));
$this->assertSame(0666 & ~umask(), $this->root->getChild('destination/' . $finalFilename . '.txt')->getPermissions());
}

public function testMoveSanitizesClientNameByDefault(): void
Expand Down
Loading
Loading