Skip to content

Commit

Permalink
Add toInteger/fromInteger helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
tvdijen committed Feb 4, 2025
1 parent 98bf400 commit c3f26ea
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
},
"require": {
"php": "^8.1",
"ext-bcmath": "*",
"ext-date": "*",
"ext-dom": "*",
"ext-filter": "*",
Expand Down
35 changes: 34 additions & 1 deletion src/Type/IntegerValue.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
namespace SimpleSAML\XML\Type;

use SimpleSAML\XML\Assert\Assert;
use SimpleSAML\XML\Exception\SchemaViolationException;
use SimpleSAML\XML\Exception\{RuntimeException, SchemaViolationException};

use function bccomp;
use function intval;
use function strval;

/**
* @package simplesaml/xml-common
Expand All @@ -27,4 +31,33 @@ protected function validateValue(string $value): void
{
Assert::validInteger($this->sanitizeValue($value), SchemaViolationException::class);
}


/**
* Convert from integer
*
* @param int $value
* @return static
*/
protected static function fromInteger(int $value): static
{
return new static(strval($value));
}


/**
* Convert to integer
*
* @return int
*/
public function toInteger(): int
{
$value = $this->getValue();

if (bccomp($value, strval(PHP_INT_MAX)) === 1) {
throw new RuntimeException("Cannot convert to integer: out of bounds.");
}

return intval($value);
}
}

0 comments on commit c3f26ea

Please sign in to comment.