Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,31 @@ composer require mll-lab/php-utils

See [tests](tests).

### SafeCast

PHP's native type casts like `(int)` and `(float)` can produce unexpected results, especially when casting from strings.
The `SafeCast` utility provides safe alternatives that validate input before casting:

```php
use MLL\Utils\SafeCast;

// Safe integer casting
SafeCast::toInt(42); // 42
SafeCast::toInt('42'); // 42
SafeCast::toInt('hello'); // throws InvalidArgumentException

// Safe float casting
SafeCast::toFloat(3.14); // 3.14
SafeCast::toFloat('3.14'); // 3.14
SafeCast::toFloat('abc'); // throws InvalidArgumentException

// Safe string casting
SafeCast::toString(42); // '42'
SafeCast::toString(null); // ''
```

See [tests](tests/SafeCastTest.php) for more examples.

### Holidays

You can add custom holidays by registering a method that returns a map of holidays for a given year.
Expand Down
3 changes: 2 additions & 1 deletion src/IlluminaSampleSheet/V2/BclConvert/OverrideCycles.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use MLL\Utils\IlluminaSampleSheet\IlluminaSampleSheetException;
use MLL\Utils\IlluminaSampleSheet\V2\HeaderSection;
use MLL\Utils\SafeCast;

class OverrideCycles
{
Expand Down Expand Up @@ -55,7 +56,7 @@ public function makeOverrideCycle(string $cycleString): OverrideCycle

return new OverrideCycle(
array_map(
fn (array $match): CycleTypeWithCount => new CycleTypeWithCount(new CycleType($match[1]), (int) $match[2]),
fn (array $match): CycleTypeWithCount => new CycleTypeWithCount(new CycleType($match[1]), SafeCast::toInt($match[2])),
$matches
)
);
Expand Down
7 changes: 2 additions & 5 deletions src/LightcyclerExportSheet/LightcyclerDataParsingTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace MLL\Utils\LightcyclerExportSheet;

use Illuminate\Support\Collection;
use MLL\Utils\SafeCast;

trait LightcyclerDataParsingTrait
{
Expand All @@ -14,11 +15,7 @@ protected function parseFloatValue(?string $value): ?float
return null;
}

if (! is_numeric($cleanString)) {
throw new \InvalidArgumentException("Invalid float value: '{$cleanString}'");
}

return (float) $cleanString;
return SafeCast::toFloat($cleanString);
}

/** @return array{float, float} */
Expand Down
3 changes: 2 additions & 1 deletion src/LightcyclerExportSheet/LightcyclerXmlParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Support\Collection;
use MLL\Utils\Microplate\Coordinates;
use MLL\Utils\Microplate\CoordinateSystem12x8;
use MLL\Utils\SafeCast;

use function Safe\simplexml_load_string;

Expand Down Expand Up @@ -77,7 +78,7 @@ private function extractPropertiesFromXml(\SimpleXMLElement $xmlElement): array
$properties = [];

foreach ($xmlElement->prop as $propertyNode) {
$propertyName = (string) $propertyNode->attributes()->name;
$propertyName = SafeCast::toString($propertyNode->attributes()->name);
$propertyValue = $propertyNode->__toString();

if (! isset($properties[$propertyName])) {
Expand Down
7 changes: 6 additions & 1 deletion src/LightcyclerSampleSheet/AbsoluteQuantificationSample.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use MLL\Utils\Microplate\Coordinates;
use MLL\Utils\Microplate\CoordinateSystem12x8;
use MLL\Utils\SafeCast;

class AbsoluteQuantificationSample
{
Expand Down Expand Up @@ -42,7 +43,11 @@ public static function formatConcentration(?int $concentration): ?string
return null;
}

$exponent = (int) floor(log10(abs($concentration)));
if ($concentration === 0) {
return '0.00E0';
}

$exponent = SafeCast::toInt(floor(log10(abs($concentration))));
$mantissa = $concentration / (10 ** $exponent);

return number_format($mantissa, 2) . 'E' . $exponent;
Expand Down
9 changes: 5 additions & 4 deletions src/Microplate/CoordinateSystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace MLL\Utils\Microplate;

use Illuminate\Support\Arr;
use MLL\Utils\SafeCast;

/**
* Children should be called `CoordinateSystemXxY`, where X is the number of columns and Y is the number of rows.
Expand Down Expand Up @@ -34,14 +35,14 @@ public function paddedColumns(): array
/** 0-pad column to be as long as the longest column in the coordinate system. */
public function padColumn(int $column): string
{
$maxColumnLength = strlen((string) $this->columnsCount());
$maxColumnLength = strlen(SafeCast::toString($this->columnsCount()));

return str_pad((string) $column, $maxColumnLength, '0', STR_PAD_LEFT);
return str_pad(SafeCast::toString($column), $maxColumnLength, '0', STR_PAD_LEFT);
}

public function rowForRowFlowPosition(int $position): string
{
$index = (int) floor(($position - 1) / $this->columnsCount());
$index = SafeCast::toInt(floor(($position - 1) / $this->columnsCount()));

return $this->rows()[$index];
}
Expand All @@ -58,7 +59,7 @@ public function columnForRowFlowPosition(int $position): int

public function columnForColumnFlowPosition(int $position): int
{
$index = (int) floor(($position - 1) / $this->rowsCount());
$index = SafeCast::toInt(floor(($position - 1) / $this->rowsCount()));

return $this->columns()[$index];
}
Expand Down
3 changes: 2 additions & 1 deletion src/Microplate/Coordinates.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Illuminate\Support\Arr;
use MLL\Utils\Microplate\Enums\FlowDirection;
use MLL\Utils\Microplate\Exceptions\UnexpectedFlowDirection;
use MLL\Utils\SafeCast;

use function Safe\preg_match;

Expand Down Expand Up @@ -89,7 +90,7 @@ public static function fromString(string $coordinatesString, CoordinateSystem $c
}
/** @var array{1: string, 2: string} $matches */

return new static($matches[1], (int) $matches[2], $coordinateSystem);
return new static($matches[1], SafeCast::toInt($matches[2]), $coordinateSystem);
}

/**
Expand Down
3 changes: 2 additions & 1 deletion src/Microplate/FullColumnSection.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use MLL\Utils\Microplate\Exceptions\MicroplateIsFullException;
use MLL\Utils\Microplate\Exceptions\SectionIsFullException;
use MLL\Utils\SafeCast;

/**
* A section that occupies all wells of a column if one sample exists in this column.
Expand Down Expand Up @@ -90,6 +91,6 @@ private function sectionCanGrow(): bool

private function reservedColumns(): int
{
return (int) ceil($this->sectionItems->count() / $this->sectionedMicroplate->coordinateSystem->rowsCount());
return SafeCast::toInt(ceil($this->sectionItems->count() / $this->sectionedMicroplate->coordinateSystem->rowsCount()));
}
}
3 changes: 2 additions & 1 deletion src/Microplate/MicroplateSet/MicroplateSet.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use MLL\Utils\Microplate\Coordinates;
use MLL\Utils\Microplate\CoordinateSystem;
use MLL\Utils\Microplate\Enums\FlowDirection;
use MLL\Utils\SafeCast;

/** @template TCoordinateSystem of CoordinateSystem */
abstract class MicroplateSet
Expand Down Expand Up @@ -39,7 +40,7 @@ public function locationFromPosition(int $setPosition, FlowDirection $direction)
throw new \OutOfRangeException("Expected a position between 1-{$positionsCount}, got: {$setPosition}.");
}

$plateIndex = (int) floor(($setPosition - 1) / $this->coordinateSystem->positionsCount());
$plateIndex = SafeCast::toInt(floor(($setPosition - 1) / $this->coordinateSystem->positionsCount()));
$positionOnSinglePlate = $setPosition - ($plateIndex * $this->coordinateSystem->positionsCount());

return new Location(
Expand Down
170 changes: 170 additions & 0 deletions src/SafeCast.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
<?php declare(strict_types=1);

namespace MLL\Utils;

use function Safe\preg_match;

/**
* Safe type casting utilities to prevent unexpected or meaningless cast results.
*
* PHP's native type casts like (int) and (float) can produce unexpected results,
* especially when casting from strings. This class provides safe alternatives that
* validate the input before casting.
*
* Example of problematic native casts:
* - (int)"hello" returns 0 (misleading, not an error)
* - (int)"123abc" returns 123 (partial conversion, data loss)
* - (float)"1.23.45" returns 1.23 (invalid format accepted)
*
* The methods in this class throw exceptions for invalid inputs instead of
* silently producing incorrect values.
*/
class SafeCast
{
/**
* Safely cast a value to an integer.
*
* Only accepts:
* - Integers (returned as-is)
* - Numeric strings that represent valid integers
* - Floats that are exact integer values (e.g., 5.0)
*
* @param mixed $value The value to cast
*
* @throws \InvalidArgumentException If the value cannot be safely cast to an integer
*/
public static function toInt($value): int
{
if (is_int($value)) {
return $value;
}

// Allow floats that represent exact integers (e.g., 5.0 -> 5)
if (is_float($value)) {
if ($value === floor($value) && is_finite($value)) {
return (int) $value;
}

throw new \InvalidArgumentException('Float value "' . $value . '" cannot be safely cast to int (not a whole number or not finite)');
}

if (is_string($value)) {
$trimmed = trim($value);

// Empty string is not a valid integer
if ($trimmed === '') {
throw new \InvalidArgumentException('Empty string cannot be cast to int');
}

// Check if the string represents a valid integer
if (! self::isIntegerString($trimmed)) {
throw new \InvalidArgumentException('String value "' . $value . '" is not a valid integer format');
}

return (int) $trimmed;
}

throw new \InvalidArgumentException('Cannot cast value of type "' . gettype($value) . '" to int');
}

/**
* Safely cast a value to a float.
*
* Only accepts:
* - Floats (returned as-is)
* - Integers (cast to float)
* - Numeric strings that represent valid floats
*
* @param mixed $value The value to cast
*
* @throws \InvalidArgumentException If the value cannot be safely cast to a float
*/
public static function toFloat($value): float
{
if (is_float($value)) {
return $value;
}

if (is_int($value)) {
return (float) $value;
}

if (is_string($value)) {
$trimmed = trim($value);

// Empty string is not a valid float
if ($trimmed === '') {
throw new \InvalidArgumentException('Empty string cannot be cast to float');
}

// Check if the string represents a valid numeric value
if (! self::isNumericString($trimmed)) {
throw new \InvalidArgumentException('String value "' . $value . '" is not a valid numeric format');
}

return (float) $trimmed;
}

throw new \InvalidArgumentException('Cannot cast value of type "' . gettype($value) . '" to float');
}

/**
* Safely cast a value to a string.
*
* Only accepts:
* - Strings (returned as-is)
* - Integers and floats (converted to string)
* - Objects with __toString() method
* - null (converted to empty string)
*
* @param mixed $value The value to cast
*
* @throws \InvalidArgumentException If the value cannot be safely cast to a string
*/
public static function toString($value): string
{
if (is_string($value)) {
return $value;
}

if (is_int($value) || is_float($value)) {
return (string) $value;
}

if ($value === null) {
return '';
}

if (is_object($value) && method_exists($value, '__toString')) {
return (string) $value;
}

throw new \InvalidArgumentException('Cannot cast value of type "' . gettype($value) . '" to string');
}

/**
* Check if a string represents a valid integer.
*
* Accepts optional leading/trailing whitespace, optional sign, and digits only.
*/
private static function isIntegerString(string $value): bool
{
return preg_match('/^[+-]?\d+$/', $value) === 1;
}

/**
* Check if a string represents a valid numeric value (integer or float).
*
* Accepts scientific notation, decimals with optional sign.
*/
private static function isNumericString(string $value): bool
{
if (! is_numeric($value)) {
return false;
}

// is_numeric accepts some formats we want to reject, like hexadecimal (0x1F) or binary (0b1010).
// Check for these and reject them for stricter validation
return preg_match('/^0[xXbB]/', $value) !== 1;
}
}
7 changes: 4 additions & 3 deletions src/StringUtil.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,11 +171,12 @@ private static function guessEncoding(string $text): string
*/
public static function leftPadNumber($number, int $length): string
{
if (is_string($number) && ! is_numeric($number)) {
throw new \InvalidArgumentException("Expected numeric string, got: {$number}");
// For strings, validate they're numeric by casting to float first
if (is_string($number)) {
$number = SafeCast::toFloat($number);
}

return str_pad((string) $number, $length, '0', STR_PAD_LEFT);
return str_pad(SafeCast::toString($number), $length, '0', STR_PAD_LEFT);
}

/** Remove forbidden chars (<,>,:,",/,\,|,?,*) from file name. */
Expand Down
3 changes: 2 additions & 1 deletion src/Tecan/BasicCommands/BasicPipettingActionCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace MLL\Utils\Tecan\BasicCommands;

use MLL\Utils\SafeCast;
use MLL\Utils\Tecan\LiquidClass\LiquidClass;
use MLL\Utils\Tecan\Location\Location;

Expand Down Expand Up @@ -36,6 +37,6 @@ protected function getTipMask(): string

public function setTipMask(int $tipMask): void
{
$this->tipMask = (string) $tipMask;
$this->tipMask = SafeCast::toString($tipMask);
}
}
Loading