PHPackages                             ctw/ctw-cast - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. ctw/ctw-cast

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

ctw/ctw-cast
============

This package provides utility classes for type-safe casting in PHP 8.3+ with comprehensive error handling.

1.0.1(5mo ago)012BSD-3-ClausePHPPHP ^8.3CI passing

Since Nov 25Pushed 5mo agoCompare

[ Source](https://github.com/jonathanmaron/ctw-cast)[ Packagist](https://packagist.org/packages/ctw/ctw-cast)[ RSS](/packages/ctw-ctw-cast/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (3)Versions (3)Used By (0)

Package "ctw/ctw-cast"
======================

[](#package-ctwctw-cast)

[![Latest Stable Version](https://camo.githubusercontent.com/8cf4cb43bfec6553c78078b1ac760368c5b3674854ad4b7758de84aa86211b2a/68747470733a2f2f706f7365722e707567782e6f72672f6374772f6374772d636173742f762f737461626c65)](https://packagist.org/packages/ctw/ctw-cast)[![GitHub Actions](https://github.com/jonathanmaron/ctw-cast/actions/workflows/tests.yml/badge.svg)](https://github.com/jonathanmaron/ctw-cast/actions/workflows/tests.yml)[![Scrutinizer Build](https://camo.githubusercontent.com/f6569097781222d3cf45f59f5df90c7cd17cc487861fe6c40c0f5a3d9a533522/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a6f6e617468616e6d61726f6e2f6374772d636173742f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jonathanmaron/ctw-cast/build-status/master)[![Scrutinizer Quality](https://camo.githubusercontent.com/f6023cab3e8f249c99d854b2e1c8144e3f6e91df92ab1bb5f17c0b2848b7893b/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a6f6e617468616e6d61726f6e2f6374772d636173742f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jonathanmaron/ctw-cast/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/0ab9927df4a64c6c27ed992c9d9ffaef5e41998ba3d5e4f92824c935d6c2f437/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a6f6e617468616e6d61726f6e2f6374772d636173742f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jonathanmaron/ctw-cast/?branch=master)

Type-safe casting utility for PHP 8.3+ applications with comprehensive error handling.

Introduction
------------

[](#introduction)

### Why This Library Exists

[](#why-this-library-exists)

Modern PHP development with strict types (`declare(strict_types=1)`) demands precise type handling. However, many data sources in PHP return `mixed` or loosely-typed values:

- **Superglobals** (`$_GET`, `$_POST`, `$_SERVER`, `$_ENV`, `$_COOKIE`, `$_SESSION`) return `mixed`
- **Environment variables** via `getenv()` return `string|false`
- **Legacy libraries** often return untyped or loosely-typed data
- **Database results** may return strings for numeric columns
- **Configuration files** (JSON, XML, YAML, INI) parse to mixed arrays
- **External APIs** return decoded JSON with uncertain types

PHP's native type casting (`(int)`, `(string)`, etc.) is permissive and can silently produce unexpected results:

```
(int) "42abc";     // 42 (silently ignores "abc")
(int) [];          // 0 (arrays become 0 or 1)
(bool) "false";    // true (non-empty string)
(float) "invalid"; // 0.0 (no error)
```

This library provides **validated, predictable type conversions** that throw exceptions for invalid input rather than silently corrupting data.

### Problems This Library Solves

[](#problems-this-library-solves)

1. **Silent data corruption**: Native casts convert invalid values without warning
2. **Inconsistent boolean handling**: PHP treats `"false"`, `"no"`, `"off"` as `true`
3. **Missing validation**: No built-in way to reject non-numeric strings for number conversion
4. **Overflow detection**: Native `(int)` silently wraps on overflow
5. **Type ambiguity**: Superglobals and legacy code return `mixed`, breaking strict typing

### Accessing Data from Superglobals

[](#accessing-data-from-superglobals)

When working with `$_GET`, `$_POST`, `$_SERVER`, `$_ENV`, and other superglobals, values are always `mixed`. This library ensures type-safe access:

```
use Ctw\Cast\Cast;

// Environment variables
$debug    = Cast::toBool($_ENV['DEBUG'] ?? 'false');
$port     = Cast::toInt($_ENV['DB_PORT'] ?? '3306');
$timeout  = Cast::toFloat($_ENV['TIMEOUT'] ?? '30.0');
$appName  = Cast::toString($_ENV['APP_NAME'] ?? '');

// GET/POST parameters
$page     = Cast::toInt($_GET['page'] ?? '1');
$limit    = Cast::toInt($_GET['limit'] ?? '10');
$active   = Cast::toBool($_POST['active'] ?? 'false');
$tags     = Cast::toArray($_POST['tags'] ?? '[]');

// Server variables
$port     = Cast::toInt($_SERVER['SERVER_PORT'] ?? '80');
$https    = Cast::toBool($_SERVER['HTTPS'] ?? 'off');

// Session data
$userId   = Cast::toInt($_SESSION['user_id'] ?? '0');
$prefs    = Cast::toArray($_SESSION['preferences'] ?? '{}');
```

### Working with Legacy Libraries

[](#working-with-legacy-libraries)

Many older PHP libraries return untyped data. This library bridges the gap between legacy code and modern strict-typed applications:

```
use Ctw\Cast\Cast;

// Legacy database result (returns strings for all columns)
$row    = $legacyDb->fetchRow("SELECT id, price, active FROM products");
$id     = Cast::toInt($row['id']);
$price  = Cast::toFloat($row['price']);
$active = Cast::toBool($row['active']);

// Legacy configuration loader
$config     = $legacyLoader->load('app.ini');
$maxSize    = Cast::toInt($config['upload_max_size']);
$debugMode  = Cast::toBool($config['debug']);
$allowedIps = Cast::toArray($config['allowed_ips']);

// Legacy API client
$response = $legacyClient->get('/api/users');
$users    = Cast::toArray($response);
$jsonOut  = Cast::toJson($users);

// Untyped function returns
$result = some_legacy_function();
$count  = Cast::toInt($result);
```

### Where to Use This Library

[](#where-to-use-this-library)

- **Controllers**: Validate and cast request parameters
- **Service layers**: Ensure type safety when processing external data
- **CLI commands**: Parse command-line arguments and environment variables
- **Data mappers**: Convert database results to typed domain objects
- **API handlers**: Validate incoming JSON payloads
- **Configuration loaders**: Parse and validate config values
- **Queue workers**: Process messages with mixed payloads
- **Middleware**: Sanitize and type request/response data

### Design Goals

[](#design-goals)

1. **Fail fast**: Invalid conversions throw `CastException` immediately
2. **Explicit behavior**: Every conversion rule is documented and predictable
3. **No silent corruption**: Ambiguous values are rejected, not guessed
4. **PHPStan/Psalm friendly**: Return types are precise, enabling static analysis
5. **Zero dependencies**: No external packages required

Requirements
------------

[](#requirements)

- PHP 8.3 or higher
- strict\_types enabled

Installation
------------

[](#installation)

Install by adding the package as a [Composer](https://getcomposer.org) requirement:

```
composer require ctw/cast
```

Usage Examples
--------------

[](#usage-examples)

```
use Ctw\Cast\Cast;

$string = Cast::toString($value);
$int    = Cast::toInt($value);
$float  = Cast::toFloat($value);
$bool   = Cast::toBool($value);
$array  = Cast::toArray($value);
$json   = Cast::toJson($value);
```

---

`Cast::toString(mixed $value): string`
--------------------------------------

[](#casttostringmixed-value-string)

Converts values to string representation with explicit, predictable rules.

```
Cast::toString(42);        // "42"
Cast::toString(true);      // "1"
Cast::toString(null);      // ""
```

Input TypeInput ValueOutputstring`"hello"``"hello"`int`42``"42"`int`-17``"-17"`int`0``"0"`float`3.14``"3.14"`float`-2.5``"-2.5"`float`1.0``"1"`float`INF``"INF"`float`NAN``"NAN"`bool`true``"1"`bool`false``"0"`null`null``""`objectwith `__toString()``__toString()` resultobjectwithout `__toString()`CastExceptionarray`[1, 2, 3]`CastExceptionresource`fopen(...)`CastException---

`Cast::toInt(mixed $value): int`
--------------------------------

[](#casttointmixed-value-int)

Converts values to integers with validation, rounding, and overflow detection.

```
Cast::toInt("42");   // 42
Cast::toInt(3.7);    // 4 (rounded)
Cast::toInt(null);   // 0
```

Input TypeInput ValueOutputint`42``42`int`-17``-17`bool`true``1`bool`false``0`null`null``0`float`3.14``3` (rounded)float`3.5``4` (rounded)float`-2.7``-3` (rounded)string`"42"``42`string`"  42  "``42` (trimmed)string`"3.14"``3` (rounded)string`"1e3"``1000`float`INF`CastExceptionfloat`NAN`CastExceptionfloat`1e20` (overflow)CastExceptionstring`""`CastExceptionstring`"hello"`CastExceptionstring`"42abc"`CastExceptionstringout of int rangeCastExceptionarray`[1, 2, 3]`CastExceptionobject`stdClass`CastExceptionresource`fopen(...)`CastException---

`Cast::toFloat(mixed $value): float`
------------------------------------

[](#casttofloatmixed-value-float)

Converts values to floating-point numbers with validation.

```
Cast::toFloat("3.14");   // 3.14
Cast::toFloat(42);       // 42.0
Cast::toFloat(true);     // 1.0
```

Input TypeInput ValueOutputfloat`3.14``3.14`float`-2.5``-2.5`float`INF``INF`float`NAN``NAN`int`42``42.0`int`-17``-17.0`int`0``0.0`bool`true``1.0`bool`false``0.0`null`null``0.0`string`"3.14"``3.14`string`"  3.14  "``3.14` (trimmed)string`"42"``42.0`string`"1e3"``1000.0`string`"-2.5"``-2.5`string`""`CastExceptionstring`"hello"`CastExceptionstring`"42abc"`CastExceptionarray`[1, 2, 3]`CastExceptionobject`stdClass`CastExceptionresource`fopen(...)`CastException---

`Cast::toBool(mixed $value): bool`
----------------------------------

[](#casttoboolmixed-value-bool)

Strict boolean conversion with explicit allowed values only.

```
Cast::toBool("yes");   // true
Cast::toBool(0);       // false
Cast::toBool(null);    // false
```

Input TypeInput ValueOutputbool`true``true`bool`false``false`int`1``true`int`0``false`float`1.0``true`float`0.0``false`null`null``false`string`"true"``true`string`"1"``true`string`"yes"``true`string`"on"``true`string`"y"``true`string`"t"``true`string`"false"``false`string`"0"``false`string`"no"``false`string`"off"``false`string`"n"``false`string`"f"``false`string`""``false`string`"  TRUE  "``true` (trimmed, case-insensitive)int`2`CastExceptionint`-1`CastExceptionfloat`3.14`CastExceptionfloat`-1.0`CastExceptionstring`"hello"`CastExceptionstring`"2"`CastExceptionarray`[1, 2, 3]`CastExceptionobject`stdClass`CastExceptionresource`fopen(...)`CastException---

`Cast::toArray(mixed $value): array`
------------------------------------

[](#casttoarraymixed-value-array)

Intelligent array conversion with multiple strategies for different types.

```
Cast::toArray('{"a":1}');   // ["a" => 1]
Cast::toArray(42);          // [42]
Cast::toArray(null);        // []
```

Input TypeInput ValueOutputarray`[1, 2, 3]``[1, 2, 3]`null`null``[]`string`""``[]`string`"  "``[]` (trimmed)string`'{"a":1}'``["a" => 1]` (JSON parsed)string`'[1,2,3]'``[1, 2, 3]` (JSON parsed)string`'{invalid}'``['{invalid}']` (wrapped)string`"hello"``["hello"]` (wrapped)int`42``[42]`float`3.14``[3.14]`bool`true``[true]`object`Traversable``iterator_to_array()` resultobjectwith `toArray()``toArray()` resultobject`stdClass{a:1}``["a" => 1]` (via `get_object_vars`)resource`fopen(...)`CastException---

`Cast::toJson(mixed $value, int $flags = ..., int $depth = 512): string`
------------------------------------------------------------------------

[](#casttojsonmixed-value-int-flags---int-depth--512-string)

Type-safe JSON encoding with comprehensive validation and error handling.

```
Cast::toJson(['name' => 'John']);   // '{"name":"John"}'
Cast::toJson(true);                 // 'true'
Cast::toJson(null);                 // 'null'
```

Input TypeInput ValueOutputnull`null``"null"`string`"hello"``"\"hello\""`string`"with/slash"``"\"with/slash\""`int`42``"42"`int`-17``"-17"`bool`true``"true"`bool`false``"false"`float`3.14``"3.14"`array`[1, 2, 3]``"[1,2,3]"`array`["a" => 1]``"{\"a\":1}"`object`JsonSerializable`via `jsonSerialize()`objectwith `toArray()`via `toArray()`object`stdClass{a:1}``"{\"a\":1}"`float`INF`CastExceptionfloat`NAN`CastException(any)depth &lt; 1CastExceptionobject`toArray()` not returning arrayCastExceptionresource`fopen(...)`CastException**Default flags:** `JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE`

---

Error Handling
--------------

[](#error-handling)

All methods throw `CastException` for invalid inputs:

```
use Ctw\Cast\Cast;
use Ctw\Cast\Exception\CastException;

try {
    $result = Cast::toInt($userInput);
} catch (CastException $e) {
    error_log($e->getMessage());
}
```

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance70

Regular maintenance activity

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

175d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/18d8bc9bdee8ab1b0cfccce6a06d2438acbed3a58b0046c4834c5678f6769342?d=identicon)[jonathanmaron](/maintainers/jonathanmaron)

---

Top Contributors

[![jonathanmaron](https://avatars.githubusercontent.com/u/298462?v=4)](https://github.com/jonathanmaron "jonathanmaron (25 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ctw-ctw-cast/health.svg)

```
[![Health](https://phpackages.com/badges/ctw-ctw-cast/health.svg)](https://phpackages.com/packages/ctw-ctw-cast)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
