Skip to content

Commit 95072b8

Browse files
committed
feat: add IntBoolCast for Entity
1 parent d94e054 commit 95072b8

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

system/Entity/Cast/IntBoolCast.php

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
3+
/**
4+
* This file is part of CodeIgniter 4 framework.
5+
*
6+
* (c) CodeIgniter Foundation <[email protected]>
7+
*
8+
* For the full copyright and license information, please view
9+
* the LICENSE file that was distributed with this source code.
10+
*/
11+
12+
namespace CodeIgniter\Entity\Cast;
13+
14+
/**
15+
* Int Bool Cast
16+
*
17+
* DB column: int (0/1) <--> Class property: bool
18+
*/
19+
final class IntBoolCast extends BaseCast
20+
{
21+
/**
22+
* @param int $value
23+
*/
24+
public static function get($value, array $params = []): bool
25+
{
26+
return (bool) $value;
27+
}
28+
29+
/**
30+
* @param bool|int|string $value
31+
*/
32+
public static function set($value, array $params = []): int
33+
{
34+
return (int) $value;
35+
}
36+
}

system/Entity/Entity.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
use CodeIgniter\Entity\Cast\CSVCast;
1818
use CodeIgniter\Entity\Cast\DatetimeCast;
1919
use CodeIgniter\Entity\Cast\FloatCast;
20+
use CodeIgniter\Entity\Cast\IntBoolCast;
2021
use CodeIgniter\Entity\Cast\IntegerCast;
2122
use CodeIgniter\Entity\Cast\JsonCast;
2223
use CodeIgniter\Entity\Cast\ObjectCast;
@@ -80,6 +81,7 @@ class Entity implements JsonSerializable
8081
'float' => FloatCast::class,
8182
'int' => IntegerCast::class,
8283
'integer' => IntegerCast::class,
84+
'int_bool' => IntBoolCast::class,
8385
'json' => JsonCast::class,
8486
'object' => ObjectCast::class,
8587
'string' => StringCast::class,

tests/system/Entity/EntityTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,33 @@ public function testCastInteger()
293293
$this->assertSame(3, $entity->first);
294294
}
295295

296+
public function testCastIntBool()
297+
{
298+
$entity = new class () extends Entity {
299+
protected $casts = [
300+
'active' => 'int_bool',
301+
];
302+
};
303+
304+
$entity->setAttributes(['active' => '1']);
305+
306+
$this->assertTrue($entity->active);
307+
308+
$entity->setAttributes(['active' => '0']);
309+
310+
$this->assertFalse($entity->active);
311+
312+
$entity->active = true;
313+
314+
$this->assertTrue($entity->active);
315+
$this->assertSame(['active' => 1], $entity->toRawArray());
316+
317+
$entity->active = false;
318+
319+
$this->assertFalse($entity->active);
320+
$this->assertSame(['active' => 0], $entity->toRawArray());
321+
}
322+
296323
public function testCastFloat()
297324
{
298325
$entity = $this->getCastEntity();

0 commit comments

Comments
 (0)