arraypress / wp-cast-utils
A lightweight WordPress library for type casting and data conversion
dev-main
2025-07-07 18:01 UTC
Requires
- php: >=7.4
This package is auto-updated.
Last update: 2025-09-02 10:17:44 UTC
README
A lightweight WordPress library for type casting and data conversion. Provides simple, reliable methods for converting between data types with special handling for WordPress-specific formats.
Features
- 🎯 Simple API: 14 easy-to-remember methods for common conversions
- 🔧 WordPress-Ready: Handles serialized data, JSON, and WordPress formats
- ⚡ Smart Conversions: Intelligent handling of arrays, CSV, JSON, and boolean values
- 🛡️ Type Safety: Strict typing with predictable return values
- 📱 Modern Output: Clean formatting without unnecessary decimals
- 📅 Date Handling: WordPress-compatible date formatting and conversion
Requirements
- PHP 7.4 or later
- WordPress 5.0 or later
Installation
composer require arraypress/wp-cast-utils
Basic Usage
Type Casting
use ArrayPress\CastUtils\Cast; // Boolean conversion (handles 'yes'/'no', 'true'/'false', etc.) Cast::bool( 'yes' ); // true Cast::bool( 'false' ); // false Cast::bool( 1 ); // true // Integer conversion with optional absolute value Cast::int( '123' ); // 123 Cast::int( '-45' ); // -45 Cast::int( '-45', true ); // 45 (absolute) // Float conversion with optional absolute value Cast::float( '123.45' ); // 123.45 Cast::float( '-67.89', true ); // 67.89 (absolute) // Smart number conversion (int or float) Cast::number( '123' ); // 123 (int) Cast::number( '123.45' ); // 123.45 (float) Cast::number( '-67', true ); // 67 (absolute int) // String conversion Cast::string( [ 'a', 'b' ] ); // '["a","b"]' Cast::string( 123 ); // '123'
String Case Conversion
// Case conversions Cast::upper( 'hello world' ); // 'HELLO WORLD' Cast::lower( 'HELLO WORLD' ); // 'hello world' Cast::title( 'hello world' ); // 'Hello World' Cast::sentence( 'HELLO WORLD' ); // 'Hello world'
Array Conversions
// Smart array conversion Cast::array( 'a,b,c' ); // ['a', 'b', 'c'] (CSV) Cast::array( '{"x":1,"y":2}' ); // ['x' => 1, 'y' => 2] (JSON) Cast::array( 'a:2:{i:0;s:1:"a";i:1;s:1:"b";}' ); // ['a', 'b'] (WordPress serialized) // Array to CSV Cast::csv( [ 'apple', 'banana', 'cherry' ] ); // 'apple,banana,cherry' Cast::csv( [ 'red', 'green', 'blue' ], '|' ); // 'red|green|blue'
JSON & WordPress
// JSON encoding Cast::json( [ 'name' => 'John', 'age' => 30 ] ); // '{"name":"John","age":30}' // Pretty JSON (great for debugging) Cast::json( [ 'name' => 'John' ], true ); // { // "name": "John" // } // WordPress slugs Cast::slug( 'Hello World!' ); // 'hello-world' Cast::slug( 'Café & Bar' ); // 'cafe-bar'
Date Conversion
// Date formatting Cast::date( '2024-01-15' ); // '2024-01-15 00:00:00' Cast::date( '2024-01-15 14:30:00', 'Y-m-d' ); // '2024-01-15' Cast::date( 1705329000 ); // '2024-01-15 14:30:00' (from timestamp) Cast::date( 'January 15, 2024', 'F j, Y' ); // 'January 15, 2024' Cast::date( 'invalid' ); // null
Flexible Value Conversion
// Dynamic casting (core types only) Cast::value( $meta_value, 'bool' ); // Casts to boolean Cast::value( $data, 'array' ); // Casts to array Cast::value( $input, 'int' ); // Casts to integer // Using WordPress functions Cast::value( $text, 'sanitize_text_field' ); // Calls WordPress function Cast::value( $number, 'absint' ); // WordPress absolute integer // Custom callbacks Cast::value( $data, function ( $value ) { return strtoupper( trim( $value ) ); } );
API Reference
Core Methods
Method | Description | Returns |
---|---|---|
bool($value) |
Convert to boolean with smart string handling | bool |
int($value, $absolute = false) |
Convert to integer, optionally absolute | int |
float($value, $absolute = false) |
Convert to float, optionally absolute | float |
number($value, $absolute = false) |
Smart int/float detection | int|float |
array($value) |
Smart array conversion (JSON, CSV, serialized) | array |
string($value) |
Convert to string (JSON encode objects/arrays) | string |
Format Methods
Method | Description | Returns |
---|---|---|
json($value, $pretty = false) |
Convert to JSON string | string|null |
slug($value) |
Convert to WordPress-safe slug | string |
csv($array, $separator = ',') |
Convert array to CSV string | string |
date($value, $format = 'Y-m-d H:i:s') |
Convert to formatted date | string|null |
String Case Methods
Method | Description | Returns |
---|---|---|
upper($value) |
Convert to uppercase | string |
lower($value) |
Convert to lowercase | string |
title($value) |
Convert to title case | string |
sentence($value) |
Convert to sentence case | string |
Flexible Conversion
Method | Description | Returns |
---|---|---|
value($value, $type, $default = null) |
Convert using type string or callback | mixed |
Common Use Cases
WordPress Meta Values
// Handle various meta value formats $featured = Cast::meta( 'post', $post_id, 'featured', 'bool' ); $tags = Cast::meta( 'post', $post_id, 'tags', 'array' ); $settings = Cast::meta( 'option', null, 'my_plugin_settings', 'array' ); $publish_date = Cast::date( Cast::meta( 'post', $post_id, 'event_date', 'string' ), 'F j, Y' ); $publish_date = Cast::meta( 'post', $post_id, 'event_date', 'date' ); // Uses default 'Y-m-d H:i:s'
Form Data Processing
// Clean form inputs $age = Cast::number( $_POST['age'], true ); // Smart int/float with absolute $email = Cast::lower( $_POST['email'] ); // Normalize email case $name = Cast::title( $_POST['name'] ); // Proper name formatting $interests = Cast::array( $_POST['interests'] ); // Handles CSV or array $event_date = Cast::date( $_POST['date'], 'Y-m-d H:i:s' );
API Responses
// Prepare data for JSON APIs $response = [ 'user_id' => Cast::int( $user->ID ), 'is_active' => Cast::bool( $user->active ), 'full_name' => Cast::title( $user->display_name ), 'tags' => Cast::array( $user->tags ), 'slug' => Cast::slug( $user->display_name ), 'created_at' => Cast::date( $user->user_registered, 'c' ) // ISO 8601 ]; return wp_send_json( $response );
Configuration & Settings
// Handle plugin options $config = get_option( 'my_plugin_config' ); $enabled = Cast::value( $config['enabled'] ?? '', 'bool', false ); $max_items = Cast::value( $config['max_items'] ?? '', 'int', 10 ); $categories = Cast::value( $config['categories'] ?? '', 'array', [] ); $last_sync = Cast::date( $config['last_sync'] ?? '', 'Y-m-d H:i:s' );
Content Processing
// Clean and format content $title = Cast::title( $post_title ); // "hello world" → "Hello World" $slug = Cast::slug( $title ); // "Hello World" → "hello-world" $excerpt = Cast::sentence( $post_excerpt ); // "LOREM IPSUM" → "Lorem ipsum" $tags_csv = Cast::csv( $post_tags ); // ['php', 'wordpress'] → "php,wordpress"
Key Benefits
- Predictable: Always returns the expected type
- WordPress-Native: Uses
wp_json_encode()
,maybe_unserialize()
,sanitize_title()
- Error-Safe: Won't throw exceptions on invalid input
- Memory Efficient: Simple conversions without heavy dependencies
- Developer-Friendly: Easy to remember method names
- Comprehensive: Handles dates, strings, numbers, arrays, and formatting
Requirements
- PHP 7.4+
- WordPress 5.0+
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This project is licensed under the GPL-2.0-or-later License.