|
| 1 | +# PHP Schema Builder |
| 2 | + |
| 3 | +[](https://packagist.org/packages/ipagdevs/schema-builder) |
| 4 | +[](LICENSE.md) |
| 5 | +[](https://travis-ci.com/ipagdevs/schema-builder) |
| 6 | +[](https://packagist.org/packages/ipagdevs/schema-builder) |
| 7 | + |
| 8 | +A powerful and intuitive library for building schema-driven data models in PHP. Validate, parse, and serialize complex data structures with ease, ensuring your data models are robust and reliable. |
| 9 | + |
| 10 | +## Features |
| 11 | + |
| 12 | +- **Fluent Schema Definition:** Define your model's structure using a clean and fluent API. |
| 13 | +- **Rich Type System:** Supports `int`, `string`, `float`, `bool`, `date`, `enum`, and complex types like arrays and nested relationships. |
| 14 | +- **Powerful Validation:** Built-in validation rules like `required`, `nullable`, `min`, `max`, `limit`, `between`, and more. |
| 15 | +- **Relationships:** Easily define `has` (one) and `hasMany` (many) relationships between models. |
| 16 | +- **Mutators:** Transform attribute values with custom logic on get or set. |
| 17 | +- **Smart Serialization:** Control how your models are converted to JSON, including hiding sensitive attributes. |
| 18 | +- **Defaults and Nullables:** Effortlessly handle default values and nullable attributes. |
| 19 | +- **Strongly Typed:** Designed to work well with modern, strongly-typed PHP (8.1+). |
| 20 | + |
| 21 | +## Installation |
| 22 | + |
| 23 | +Install the library via Composer: |
| 24 | + |
| 25 | +```bash |
| 26 | +composer require ipagdevs/schema-builder |
| 27 | +``` |
| 28 | + |
| 29 | +## Core Concepts |
| 30 | + |
| 31 | +### 1. Model |
| 32 | + |
| 33 | +The `Model` is the heart of the library. You extend the base `IpagDevs\Model\Model` class to create your own data models. Each model is responsible for defining its structure through a schema. |
| 34 | + |
| 35 | +### 2. Schema |
| 36 | + |
| 37 | +The `Schema` defines the "shape" of your data: its attributes, types, and validation rules. You define the schema within your model by implementing the `schema()` method. |
| 38 | + |
| 39 | +### 3. Mutators |
| 40 | + |
| 41 | +`Mutators` allow you to apply custom transformations to data when an attribute is set or retrieved. This is perfect for formatting, sanitizing, or deriving values. |
| 42 | + |
| 43 | +## Getting Started: A Simple Example |
| 44 | + |
| 45 | +Let's create a simple `Review` model. |
| 46 | + |
| 47 | +```php |
| 48 | +<?php |
| 49 | + |
| 50 | +use IpagDevs\Model\Model; |
| 51 | +use IpagDevs\Model\Schema\Schema; |
| 52 | +use IpagDevs\Model\Schema\SchemaBuilder; |
| 53 | + |
| 54 | +class Review extends Model |
| 55 | +{ |
| 56 | + protected function schema(SchemaBuilder $schema): Schema |
| 57 | + { |
| 58 | + $schema->int('rating')->required(); |
| 59 | + $schema->string('comment')->nullable(); |
| 60 | + $schema->string('author')->default('Anonymous'); |
| 61 | + |
| 62 | + return $schema->build(); |
| 63 | + } |
| 64 | +} |
| 65 | +``` |
| 66 | + |
| 67 | +Now, let's use it to parse and handle data: |
| 68 | + |
| 69 | +```php |
| 70 | +// Parse data from an array |
| 71 | +$review = Review::parse([ |
| 72 | + 'rating' => 5, |
| 73 | + 'comment' => 'Excellent product!' |
| 74 | +]); |
| 75 | + |
| 76 | +// Get attributes |
| 77 | +echo $review->get('rating'); // 5 |
| 78 | +echo $review->get('author'); // 'Anonymous' (from default) |
| 79 | + |
| 80 | +// Parsing with missing required data will throw an exception |
| 81 | +try { |
| 82 | + Review::parse(['comment' => 'This will fail.']); |
| 83 | +} catch (\IpagDevs\Model\Schema\Exception\SchemaAttributeParseException $e) { |
| 84 | + // "Missing required attribute" |
| 85 | + echo $e->getMessage(); |
| 86 | +} |
| 87 | + |
| 88 | +// Convert to JSON |
| 89 | +echo json_encode($review, JSON_PRETTY_PRINT); |
| 90 | +// or |
| 91 | +echo json_encode($review->jsonSerialize(), JSON_PRETTY_PRINT); |
| 92 | +``` |
| 93 | + |
| 94 | +**JSON Output:** |
| 95 | + |
| 96 | +```json |
| 97 | +{ |
| 98 | + "rating": 5, |
| 99 | + "comment": "Excellent product!", |
| 100 | + "author": "Anonymous" |
| 101 | +} |
| 102 | +``` |
| 103 | + |
| 104 | +## Advanced Usage & Features |
| 105 | + |
| 106 | +Here's a more comprehensive `Product` model that showcases many of the library's features. |
| 107 | + |
| 108 | +```php |
| 109 | +<?php |
| 110 | + |
| 111 | +use IpagDevs\Model\Model; |
| 112 | +use IpagDevs\Model\Schema\Schema; |
| 113 | +use IpagDevs\Model\Schema\Mutator; |
| 114 | +use IpagDevs\Model\Schema\SchemaBuilder; |
| 115 | +use IpagDevs\Model\Schema\MutatorContext; |
| 116 | + |
| 117 | +class Category extends Model |
| 118 | +{ |
| 119 | + protected function schema(SchemaBuilder $schema): Schema |
| 120 | + { |
| 121 | + $schema->int('id')->required(); |
| 122 | + $schema->string('name')->required(); |
| 123 | + return $schema->build(); |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +class Product extends Model |
| 128 | +{ |
| 129 | + protected function schema(SchemaBuilder $schema): Schema |
| 130 | + { |
| 131 | + // Basic Types |
| 132 | + $schema->int('id')->required(); |
| 133 | + $schema->float('price')->min(0.01)->required(); |
| 134 | + $schema->bool('is_active')->default(true); |
| 135 | + $schema->date('available_since', 'Y-m-d')->required(); |
| 136 | + $schema->enum('condition', ['new', 'used', 'refurbished']); |
| 137 | + |
| 138 | + // String Validation |
| 139 | + $schema->string('name')->between(5, 50); // min 5, max 50 chars |
| 140 | + $schema->string('description')->limit(200)->nullable(); |
| 141 | + $schema->string('short_description')->truncate(10); // Truncates if > 10 chars |
| 142 | + |
| 143 | + // Arrays and Lists |
| 144 | + $schema->string('tags')->list()->nullable(); // An array of strings |
| 145 | + $schema->int('alternate_ids')->list()->nullable(); // An array of integers |
| 146 | + $schema->string('matrix')->list()->list()->nullable(); // An array of arrays of strings |
| 147 | + |
| 148 | + // Hidden Attributes |
| 149 | + $schema->string('internal_code')->hidden(); // Always hidden from jsonSerialize() |
| 150 | + $schema->string('promo_code')->nullable()->hiddenIf( |
| 151 | + fn($value, Product $model) => $model->get('price') > 100.0 |
| 152 | + ); |
| 153 | + |
| 154 | + // Relationships |
| 155 | + $schema->has('category', Category::class)->required(); |
| 156 | + $schema->hasMany('reviews', Review::class)->nullable(); |
| 157 | + |
| 158 | + // Mutated Attributes |
| 159 | + $schema->string('sku'); |
| 160 | + $schema->string('slug'); |
| 161 | + |
| 162 | + return $schema->build(); |
| 163 | + } |
| 164 | + |
| 165 | + // Mutator for the 'sku' attribute |
| 166 | + public function sku(): Mutator |
| 167 | + { |
| 168 | + return new Mutator( |
| 169 | + getter: fn($value) => "SKU-{$value}", |
| 170 | + setter: function ($value, MutatorContext $context) { |
| 171 | + $value = mb_strtoupper(str_replace(' ', '-', $value)); |
| 172 | + $context->assert(mb_ereg_match('^[A-Z0-9\-]+$', $value), "Invalid SKU format."); |
| 173 | + return $value; |
| 174 | + } |
| 175 | + ); |
| 176 | + } |
| 177 | + |
| 178 | + // Mutator for the 'slug' attribute (derived from 'name') |
| 179 | + public function slug(): Mutator |
| 180 | + { |
| 181 | + return new Mutator( |
| 182 | + setter: fn($value, MutatorContext $context) => mb_strtolower(str_replace(' ', '-', $context->target->get('name'))) |
| 183 | + ); |
| 184 | + } |
| 185 | +} |
| 186 | +``` |
| 187 | + |
| 188 | +### Parsing Complex Data |
| 189 | + |
| 190 | +You can now parse a complete data structure that matches the schema. |
| 191 | + |
| 192 | +```php |
| 193 | +$productData = [ |
| 194 | + 'id' => 101, |
| 195 | + 'name' => 'Awesome Wireless Keyboard', |
| 196 | + 'price' => 129.99, |
| 197 | + 'available_since' => '2025-10-20', |
| 198 | + 'condition' => 'new', |
| 199 | + 'internal_code' => 'XYZ-SECRET', |
| 200 | + 'short_description' => 'This will be truncated for sure.', |
| 201 | + 'tags' => ['wireless', 'mechanical', 'rgb'], |
| 202 | + 'category' => ['id' => 15, 'name' => 'Peripherals'], |
| 203 | + 'reviews' => [ |
| 204 | + ['rating' => 5, 'comment' => 'Best keyboard ever!'], |
| 205 | + ['rating' => 4, 'author' => 'A happy user'], |
| 206 | + ], |
| 207 | + 'sku' => 'awk-101-blue', |
| 208 | + 'promo_code' => 'SAVE10' |
| 209 | +]; |
| 210 | + |
| 211 | +$product = Product::parse($productData); |
| 212 | + |
| 213 | +// Accessing data |
| 214 | +echo $product->get('name'); // 'Awesome Wireless Keyboard' |
| 215 | +echo $product->get('short_description'); // 'This will ' |
| 216 | + |
| 217 | +// Mutators are applied automatically |
| 218 | +echo $product->get('sku'); // 'SKU-AWK-101-BLUE' |
| 219 | +echo $product->get('slug'); // 'awesome-wireless-keyboard' |
| 220 | + |
| 221 | +// Relationships are parsed into Model instances |
| 222 | +echo get_class($product->get('category')); // 'Category' |
| 223 | +echo get_class($product->get('reviews')[0]); // 'Review' |
| 224 | +``` |
| 225 | + |
| 226 | +### Attribute Types and Validation |
| 227 | + |
| 228 | +| Method | Description | |
| 229 | +| --------------------------------- | ---------------------------------------------------------------------------- | |
| 230 | +| `->required()` | The attribute must be present in the input data. | |
| 231 | +| `->nullable()` | The attribute can be `null`. | |
| 232 | +| `->default($value)` | Sets a default value if the attribute is not provided. | |
| 233 | +| `->min($value)` | For `float` or `int`, sets a minimum value. | |
| 234 | +| `->max($value)` | For `float` or `int`, sets a maximum value. | |
| 235 | +| `->limit($chars)` | For `string`, enforces a maximum character length. | |
| 236 | +| `->truncate($chars)` | For `string`, truncates the string if it exceeds the character limit. | |
| 237 | +| `->between($min, $max)` | For `string`, enforces a min and max character length. | |
| 238 | +| `->positives([...])` | For `bool`, defines values that should be parsed as `true`. | |
| 239 | +| `->negatives([...])` | For `bool`, defines values that should be parsed as `false`. | |
| 240 | +| `->list()` or `->array()` | Converts an attribute into an array of its original type. Chainable. | |
| 241 | +| `->hidden()` | Hides the attribute from `jsonSerialize()` output. | |
| 242 | +| `->hiddenIf(callable $check)` | Hides the attribute from `jsonSerialize()` if the callback returns `true`. | |
| 243 | +| `->hiddenIfNull()` | A shortcut for hiding an attribute if its value is `null`. | |
| 244 | + |
| 245 | +### Serialization |
| 246 | + |
| 247 | +The library provides two ways to convert a model to an array. |
| 248 | + |
| 249 | +#### `jsonSerialize()` |
| 250 | + |
| 251 | +This method is automatically called by `json_encode()`. It respects the `hidden()`, `hiddenIf()`, and `hiddenIfNull()` rules, making it safe for public API responses. It also serializes nested models and collections. |
| 252 | + |
| 253 | +```php |
| 254 | +$product = Product::parse($productData); |
| 255 | +$json = $product->jsonSerialize(); |
| 256 | + |
| 257 | +// $json will NOT contain 'internal_code'. |
| 258 | +// 'promo_code' will be hidden because price > 100. |
| 259 | +// 'category' and 'reviews' will be arrays of serialized data. |
| 260 | +``` |
| 261 | + |
| 262 | +#### `toArray()` |
| 263 | + |
| 264 | +This method converts the model and all its relations into a "raw" array, including all attributes (even hidden ones). It's useful for debugging or internal data transfer. |
| 265 | + |
| 266 | +```php |
| 267 | +$array = $product->toArray(); |
| 268 | + |
| 269 | +// $array WILL contain 'internal_code'. |
| 270 | +``` |
| 271 | + |
| 272 | +## Contributing |
| 273 | + |
| 274 | +Contributions are welcome! Please feel free to submit a pull request or open an issue for any bugs or feature requests. |
| 275 | + |
| 276 | +## License |
| 277 | + |
| 278 | +The MIT License (MIT). Please see [License File](LICENSE.md) for more information. |
0 commit comments