Skip to content

Commit

Permalink
Cast property value to boolean using boolean() method
Browse files Browse the repository at this point in the history
  • Loading branch information
Programie committed Apr 18, 2018
1 parent ec26b22 commit 1a9e499
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 0 deletions.
12 changes: 12 additions & 0 deletions examples/boolean.php
@@ -0,0 +1,12 @@
<?php
use com\selfcoders\pini\Pini;

require_once __DIR__ . "/../vendor/autoload.php";

$ini = new Pini(__DIR__ . "/example.ini");

$section = $ini->getSection("my section");

echo "some key = " . var_export($property = $section->getProperty("some key")->boolean(), true) . "\n";
echo "some bool = " . var_export($property = $section->getProperty("some bool")->boolean(), true) . "\n";
echo "another bool = " . var_export($property = $section->getProperty("another bool")->boolean(), true) . "\n";
2 changes: 2 additions & 0 deletions examples/example.ini
Expand Up @@ -9,6 +9,8 @@ some key = some value
;multiple lines
;in comments
another key = another value
some bool = true
another bool = false

[arrays]
myarray[] = value
Expand Down
24 changes: 24 additions & 0 deletions src/main/php/com/selfcoders/pini/Property.php
Expand Up @@ -27,6 +27,30 @@ public function __construct($name, $value = null)
$this->comment = array();
}

/**
* Get the value of this property as a boolean.
*
* "true" and "1" will result in true
* "false" and "0" will result in false
* everything else will result in null
*
* @return bool|null
*/
public function boolean()
{
$value = strtolower($this->value);

if ($value === "true" or $value === "1") {
return true;
}

if ($value === "false" or $value === "0") {
return false;
}

return null;
}

/**
* Get this property as a string in INI format.
*
Expand Down
11 changes: 11 additions & 0 deletions src/test/php/PiniTest.php
Expand Up @@ -55,6 +55,17 @@ public function testMergeArray()
$this->assertEquals(array("replaced"), $property->value);
}

public function testBoolean()
{
$ini = new Pini(__DIR__ . "/../../../examples/example.ini");

$section = $ini->getSection("my section");

$this->assertNull($section->getProperty("some key")->boolean());
$this->assertTrue($section->getProperty("some bool")->boolean());
$this->assertFalse($section->getProperty("another bool")->boolean());
}

public function testSave()
{
$filename = tempnam(sys_get_temp_dir(), "ini");
Expand Down

0 comments on commit 1a9e499

Please sign in to comment.