File tree Expand file tree Collapse file tree 3 files changed +65
-0
lines changed Expand file tree Collapse file tree 3 files changed +65
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 1717use CodeIgniter \Entity \Cast \CSVCast ;
1818use CodeIgniter \Entity \Cast \DatetimeCast ;
1919use CodeIgniter \Entity \Cast \FloatCast ;
20+ use CodeIgniter \Entity \Cast \IntBoolCast ;
2021use CodeIgniter \Entity \Cast \IntegerCast ;
2122use CodeIgniter \Entity \Cast \JsonCast ;
2223use 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,
Original file line number Diff line number Diff 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 ();
You can’t perform that action at this time.
0 commit comments