') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); fix: use native PHP truthiness for condition evaluation in when()/whenNot() by michalsn · Pull Request #9576 · codeigniter4/CodeIgniter4 · GitHub
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
4 changes: 2 additions & 2 deletions system/Traits/ConditionalTrait.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -29,7 +29,7 @@ trait ConditionalTrait
*/
public function when($condition, callable $callback, ?callable $defaultCallback = null): self
{
if ($condition !== '' && $condition !== false && $condition !== null) {
if ((bool) $condition) {
$callback($this, $condition);
} elseif ($defaultCallback !== null) {
$defaultCallback($this);
Expand All@@ -52,7 +52,7 @@ public function when($condition, callable $callback, ?callable $defaultCallback
*/
public function whenNot($condition, callable $callback, ?callable $defaultCallback = null): self
{
if ($condition === '' || $condition === null || $condition === false || $condition === '0') {
if (! (bool) $condition) {
$callback($this, $condition);
} elseif ($defaultCallback !== null) {
$defaultCallback($this);
Expand Down
58 changes: 58 additions & 0 deletions tests/system/Database/Builder/WhenTest.php
Original file line numberDiff line numberDiff line change
Expand Up@@ -15,7 +15,9 @@

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\Mock\MockConnection;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use stdClass;

/**
* @internal
Expand DownExpand Up@@ -101,6 +103,23 @@ public function testWhenPassesParemeters(): void
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
}

#[DataProvider('provideConditionValues')]
public function testWhenRunsDefaultCallbackBasedOnCondition(mixed $condition, bool $expectDefault): void
{
$builder = $this->db->table('jobs');

$builder = $builder->when($condition, static function ($query): void {
$query->select('id');
}, static function ($query): void {
$query->select('name');
});

$expected = $expectDefault ? 'name' : 'id';
$expectedSQL = 'SELECT "' . $expected . '" FROM "jobs"';

$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
}

public function testWhenNotFalse(): void
{
$builder = $this->db->table('jobs');
Expand DownExpand Up@@ -166,4 +185,43 @@ public function testWhenNotPassesParemeters(): void
$expectedSQL = 'SELECT * FROM "jobs" WHERE "name" = \'0\'';
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
}

#[DataProvider('provideConditionValues')]
public function testWhenNotRunsDefaultCallbackBasedOnCondition(mixed $condition, bool $expectDefault): void
{
$builder = $this->db->table('jobs');

$builder = $builder->whenNot($condition, static function ($query): void {
$query->select('id');
}, static function ($query): void {
$query->select('name');
});

$expected = $expectDefault ? 'id' : 'name';
$expectedSQL = 'SELECT "' . $expected . '" FROM "jobs"';

$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
}

/**
* @return array<string, array{0: mixed, 1: bool}>
*/
public static function provideConditionValues(): array
{
return [
'false' => [false, true], // [condition, expectedDefaultCallbackRuns]
'int 0' => [0, true],
'float 0.0' => [0.0, true],
'empty string' => ['', true],
'string 0' => ['0', true],
'empty array' => [[], true],
'null' => [null, true],
'true' => [true, false],
'int 1' => [1, false],
'float 1.1' => [1.1, false],
'non-empty string' => ['foo', false],
'non-empty array' => [[1], false],
'object' => [new stdClass(), false],
];
}
}
1 change: 1 addition & 0 deletions user_guide_src/source/changelogs/v4.6.2.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,7 @@ Deprecations
Bugs Fixed
**********

- **Database:** Fixed a bug where ``when()`` and ``whenNot()`` in ``ConditionalTrait`` incorrectly evaluated certain falsy values (such as ``[]``, ``0``, ``0.0``, and ``'0'``) as truthy, causing callbacks to be executed unexpectedly. These methods now cast the condition to a boolean using ``(bool)`` to ensure consistent behavior with PHP's native truthiness.
- **Security:** Fixed a bug where the ``sanitize_filename()`` function from the Security helper would throw an error when used in CLI requests.

See the repo's
Expand Down
7 changes: 4 additions & 3 deletions user_guide_src/source/database/query_builder.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -1272,9 +1272,10 @@ $builder->when()
.. versionadded:: 4.3.0

This allows modifying the query based on a condition without breaking out of the
query builder chain. The first parameter is the condition, and it should evaluate
to a boolean. The second parameter is a callable that will be ran
when the condition is true.
query builder chain. The first parameter is the condition, and it is evaluated
using PHP's native boolean logic - meaning that values like ``false``, ``null``,
``0``, ``'0'``, ``0.0``, empty string ``''`` and empty array ``[]`` will be considered false.
The second parameter is a callable that will be ran when the condition is true.

For example, you might only want to apply a given WHERE statement based on the
value sent within an HTTP request:
Expand Down