|
1 | 1 | # Gowork Safe - Type Safety Tools |
2 | 2 |
|
3 | 3 | Mainly for Symfony |
| 4 | + |
| 5 | +### SafeAssocArray |
| 6 | + |
| 7 | +```php |
| 8 | +$user = [ |
| 9 | + 'name' => 'John', |
| 10 | + 'age' => 18, |
| 11 | + 'sports' => ['football', 'handball'], |
| 12 | +]; |
| 13 | + |
| 14 | +$safe = SafeAssocArray::from($user); |
| 15 | +$safe->string('name'); // 'John' |
| 16 | +$safe->int('age'); // 18 |
| 17 | + |
| 18 | +$safe->string('nickname', '--'); // '-' |
| 19 | +$safe->stringNullable('nickname'); // NULL |
| 20 | +$safe->string('nickname'); // InvalidArgumentException |
| 21 | + |
| 22 | +$safe->strings('sports'); // ['football', 'handball'] |
| 23 | +$safe->ints('sports'); // InvalidArgumentException |
| 24 | + |
| 25 | +``` |
| 26 | + |
| 27 | +### SafeConsoleInput |
| 28 | + |
| 29 | +```php |
| 30 | +final class ExampleCommand extends Command |
| 31 | +{ |
| 32 | + // ... |
| 33 | + protected function execute(InputInterface $input, OutputInterface $output): int |
| 34 | + { |
| 35 | + $arguments = SafeConsoleInput::arguments($input); |
| 36 | + |
| 37 | + // require string from argument |
| 38 | + $file = $arguments->string('name'); |
| 39 | + |
| 40 | + $options = SafeConsoleInput::options($input); |
| 41 | + |
| 42 | + // integer with default value |
| 43 | + $limit = $options->int('limit', 20); |
| 44 | + |
| 45 | + // optional integer value |
| 46 | + $pageOrNull = $options->intNullable('page'); |
| 47 | + |
| 48 | + // bool |
| 49 | + $isDryRun = $options->bool('dry-run', false); |
| 50 | + |
| 51 | + // string[] |
| 52 | + $tags = $options->strings('tag'); |
| 53 | + |
| 54 | + // int[] |
| 55 | + $tags = $options->ints('status'); |
| 56 | + } |
| 57 | +} |
| 58 | +``` |
| 59 | + |
| 60 | +### SafeRequest |
| 61 | + |
| 62 | +```php |
| 63 | +final class ExampleAction extends Command |
| 64 | +{ |
| 65 | + // ... |
| 66 | + public function __invoke(Request $request): Response |
| 67 | + { |
| 68 | + $safeRequest = SafeRequest::from($request); |
| 69 | + $query = $safeRequest->query(); |
| 70 | + $post = $safeReques->request(); |
| 71 | + $attributes = $safeReques->attributes(); |
| 72 | + |
| 73 | + $ip = $safeReques->ip(); |
| 74 | + $postId = $attributes->string('postId'); |
| 75 | + $tags = $post->strings('tags'); |
| 76 | + // ... |
| 77 | + } |
| 78 | +} |
| 79 | +``` |
0 commit comments