1. Go to this page and download the library: Download joelbutcher/php-optional library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
joelbutcher / php-optional example snippets
namespace App\DataObjects;
use JoelButcher\PhpOptional\Optional;
use Psl\Type;
use Webmozart\Assert\Assert;
class UpdateProfile
{
public function __construct(
private readonly int $id
private readonly Optional $name
private readonly Optional $email
private readonly Options $bio
) {
//
}
public static function fromFormRequest(int $id UpdateProfileRequest $request): self
{
return new self(
id: $id,
name: Optional::forNullable($request->get('name')),
email: Optional::forNullable($request->get('email')),
bio: Optional::forNullable($request->get('bio')),
);
}
public static function fromArray(array $data): self
{
Assert::keyExists($post, 'id');
Assert::positiveInteger($post['id']);
return new self(
id: $data['id'],
name: Optional::forOptionalArrayKey($data, 'name', Type\non_empty_string()),
email: Optional::forOptionalArrayKey($data, 'email', Type\non_empty_string()),
bio: Optional::forOptionalArrayKey($data, 'bio', Type\non_empty_string()),
);
}
public function handle(UserRepository $users): void
{
$user = $users->findOneById($this->id);
// These callbacks are only called if the value for each optional field is present.
$this->name->apply(fn (string $name) => $user->updateName($name));
$this->email->apply(fn (string $email) => $user->updateEmail($email));
$this->bio->apply(fn (string $bio) => $user->updateBio($bio));
$users->save($user);
}
}
OptionalField::forPossiblyMissingArrayKey(
['foo' => 'bar'],
'foo',
\Psl\Type\positive_int()
); // crashes: `foo` does not contain a `positive-int`!
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.