From fac3ff1dbf41ab8343e5b421bde80c9223f52bb1 Mon Sep 17 00:00:00 2001 From: Christopher Pitt Date: Mon, 18 Mar 2019 15:52:33 +0200 Subject: [PATCH] Improve readme --- readme.md | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 79 insertions(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 002a089..e107a61 100644 --- a/readme.md +++ b/readme.md @@ -11,4 +11,82 @@ composer install composer test ``` -I want to write a blog post about how to use this, practically. When that's done, I will replace this paragraph with a link to the post. +## Defining types + +We support most of the built-in types: + +```php +use App\Profile; +use Pre\PropTypes; + +$profile = Profile::find(1); + +$definitions = [ + "name" => PropTypes::string()->isRequired(), + "age" => PropTypes::int(), + "rating" => PropTypes::float(), + "permissions" => PropTypes::arrayOf(PropTypes::string()), + "thumbnail" => PropTypes::either( + PropTypes::string(), // uri + PropTypes::resource(), // file handle + ), + "profile" => PropTypes::objectOf(Profile::class)->isRequired(), + "notifier" => PropTypes::closure()->isRequired(), + "isAdmin" => PropTypes::bool()->isRequired(), +]; + +$properties = [ + "name" => "Joe", + "profile" => $profile, + "notifier" => function($message) use ($profile) { + $profile->notify($message); + }, + "isAdmin" => false, +]; + +try { + PropTypes::validate($definitions, $properties); +} catch (InvalidArgumentException $e) { + // ...handle the error +} +``` + +- `isRequired` will ensure the value is present in the accompanying properties array +- `either` allows one or more types (preferably two distinct types) for comparison + +There are also variations on these: + +- `PropTypes::array()` expects any array values, without a specific type +- `PropTypes::boolean()` is the same as `PropTypes::bool()` +- `PropTypes::integer()` is the same as `PropTypes::int()` +- `PropTypes::double()` expects double values +- `PropTypes::iterable()` expects any iterable values +- `PropTypes::numeric()` expects any numeric values +- `PropTypes::object()` expects any object values, without a specific type + +## Validating types + +We don't automatically validate props – this must be done by the consumer. And example Phpx render method demonstrates this: + +```php +use Pre\PropTypes; +use function Pre\Phpx\Html\render as renderHTML; + +function render($type, $props = []) { + $props = (array) $props; + + if (class_exists($type)) { + if (method_exists($type, "propTypes")) { + PropTypes::validate($type::propTypes(), $props); + } + + if (method_exists($type, "defaultProps")) { + $props = array_merge($type::defaultProps(), $props); + } + } + + return renderHTML($type, $props); +} + +render("App\\Custom\\Component"); +```