SHOW:
|
|
- or go back to the newest paste.
| 1 | <?php | |
| 2 | ||
| 3 | /** | |
| 4 | * @name Custom casting helper | |
| 5 | * @author [email protected] | |
| 6 | * @internal | |
| 7 | */ | |
| 8 | interface Castable {
| |
| 9 | static function cast($var); | |
| 10 | } | |
| 11 | ||
| 12 | /** | |
| 13 | * @example hard casting (validation) | |
| 14 | */ | |
| 15 | class ValidatedPositiveInteger implements Castable {
| |
| 16 | static function cast($var) {
| |
| 17 | if(!is_int($var)) {
| |
| 18 | throw new InvalidArgumentException('Value is not an integer');
| |
| 19 | } | |
| 20 | if($var < 1) {
| |
| 21 | throw new InvalidArgumentException('Integer is not positive');
| |
| 22 | } | |
| 23 | return $var; | |
| 24 | } | |
| 25 | } | |
| 26 | ||
| 27 | /** | |
| 28 | * @example soft casting (sanitization) | |
| 29 | */ | |
| 30 | class SanitizedPositiveInteger implements Castable {
| |
| 31 | static function cast($var) {
| |
| 32 | $var = (int)$var; | |
| 33 | if($var < 1) $var = 1; | |
| 34 | return $var; | |
| 35 | } | |
| 36 | } | |
| 37 | ||
| 38 | // usage: | |
| 39 | ||
| 40 | $var = (ClassName)$var; | |
| 41 | ||
| 42 | function foo(ClassName $var) {}
| |
| 43 | ||
| 44 | // in both cases will run under the hood: | |
| 45 | ||
| 46 | if($var instanceof Castable) $var = ClassName::cast($var); | |
| 47 | else { /*current behavior*/ }
| |
| 48 | ||
| 49 | // usable cases: | |
| 50 | ||
| 51 | // 1. custom types with internal logic | |
| 52 | // 2. sanitization and validation of input | |
| 53 | // 3. casting from array to object (e.g. json, db row, etc.) | |
| 54 | - | // 4. casting from stdClass to object |
| 54 | + | // 4. casting from stdClass to object |
| 55 | // 5. custom type juggling | |
| 56 | // 6. custom context dependent serialization/unserialization |