Skip to content

Commit 343bd17

Browse files
author
Greg Bowler
committed
Test bool casting
1 parent 0b74953 commit 343bd17

File tree

2 files changed

+36
-5
lines changed

2 files changed

+36
-5
lines changed

src/DataObject.php

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,19 +29,19 @@ public function get(string $name):mixed {
2929
}
3030

3131
public function getString(string $name):?string {
32-
return $this->getAsScalar($name, "string");
32+
return $this->getAsType($name, "string");
3333
}
3434

3535
public function getInt(string $name):?int {
36-
return $this->getAsScalar($name, "int");
36+
return $this->getAsType($name, "int");
3737
}
3838

3939
public function getFloat(string $name):?float {
40-
return $this->getAsScalar($name, "float");
40+
return $this->getAsType($name, "float");
4141
}
4242

4343
public function getBool(string $name):?bool {
44-
// TODO: Implement getBool() method.
44+
return $this->getAsType($name, "bool");
4545
}
4646

4747
public function getDateTime(string $name):DateTimeInterface {
@@ -60,7 +60,7 @@ public function asObject(bool $nested = true):object {
6060
return (object)$this->asArray($nested);
6161
}
6262

63-
private function getAsScalar(
63+
private function getAsType(
6464
string $name,
6565
string $type
6666
):float|null|bool|int|string {
@@ -78,6 +78,8 @@ private function getAsScalar(
7878
return (string)$value;
7979
case "bool":
8080
return (bool)$value;
81+
default:
82+
return new $type($value);
8183
}
8284
}
8385
}

test/phpunit/DataObjectTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,4 +123,33 @@ public function testGetFloatFromBool() {
123123
self::assertSame(1.00, $sut->getFloat("this-is-true"));
124124
self::assertSame(0.00, $sut->getFloat("this-is-false"));
125125
}
126+
127+
public function testGetBoolFromString() {
128+
$sut = (new DataObject())
129+
->with("non-empty", "something")
130+
->with("empty", "");
131+
132+
self::assertTrue($sut->getBool("non-empty"));
133+
self::assertFalse($sut->getBool("empty"));
134+
}
135+
136+
public function testGetBoolFromInt() {
137+
$sut = (new DataObject())
138+
->with("zero", 0)
139+
->with("one", 1)
140+
->with("two", 2);
141+
142+
self::assertFalse($sut->getBool("zero"));
143+
self::assertTrue($sut->getBool("one"));
144+
self::assertTrue($sut->getBool("two"));
145+
}
146+
147+
public function testGetBoolFromFloat() {
148+
$sut = (new DataObject())
149+
->with("zero", 0.00)
150+
->with("pi", 3.14159);
151+
152+
self::assertFalse($sut->getBool("zero"));
153+
self::assertTrue($sut->getBool("pi"));
154+
}
126155
}

0 commit comments

Comments
 (0)