Skip to content

Commit 8135730

Browse files
author
Joel Butcher
committed
Initial commit
0 parents  commit 8135730

13 files changed

+867
-0
lines changed

.gitattributes

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
* text=auto
2+
3+
*.md diff=markdown
4+
*.php diff=php
5+
6+
/.github export-ignore
7+
/tests export-ignore
8+
.gitattributes export-ignore
9+
.gitignore export-ignore
10+
phpunit.xml.dist export-ignore

.github/workflows/tests.yml

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
name: tests
2+
3+
on:
4+
push:
5+
pull_request:
6+
schedule:
7+
- cron: '0 0 * * *'
8+
9+
jobs:
10+
tests:
11+
12+
runs-on: ubuntu-18.04
13+
strategy:
14+
fail-fast: true
15+
matrix:
16+
php: [ '8.0', 8.1, 8.2 ]
17+
18+
name: PHP ${{ matrix.php }}
19+
20+
steps:
21+
- name: Checkout code
22+
uses: actions/checkout@v2
23+
24+
- name: Setup PHP
25+
uses: shivammathur/setup-php@v2
26+
with:
27+
php-version: ${{ matrix.php }}
28+
tools: composer:v2
29+
coverage: xdebug
30+
31+
- name: Install dependencies
32+
run: composer update --prefer-dist --no-interaction --no-progress
33+
34+
- name: Execute tests
35+
run: vendor/bin/pest --verbose --coverage --min=100
36+
37+
- name: Check static analysis
38+
run: vendor/bin/phpstan --xdebug analyse
39+
40+
- name: Check code style analysis
41+
run: vendor/bin/pint --test

.gitignore

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
.idea/
2+
vendor/
3+
composer.lock
4+
.env
5+
.phpunit.result.cache

LICENSE.md

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
The MIT License (MIT)
2+
3+
Copyright (c) Joel Butcher
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6+
7+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8+
9+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10+

README.md

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# PHP Optional
2+
3+
Inspired by Java's [Optional](https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/master/src/java.base/share/classes/java/util/function/Predicate.java) class, this package aims to provide a comprehensive API
4+
for optional field values.
5+
6+
## Examples
7+
8+
You can use the `Optional` class in a variety of ways, see below for a few examples:
9+
10+
### Updating a user's profile
11+
12+
The below class indicates who this package may be used to update a users profile information. All fields are optional, because
13+
our user may not want to update all fields.
14+
15+
```php
16+
<?php
17+
18+
namespace App\DataObjects;
19+
20+
use JoelButcher\PhpOptional\Optional;
21+
use Psl\Type;
22+
use Webmozart\Assert\Assert;
23+
24+
class UpdateProfile
25+
{
26+
public function __construct(
27+
private readonly int $id
28+
private readonly Optional $name
29+
private readonly Optional $email
30+
private readonly Options $bio
31+
) {
32+
//
33+
}
34+
35+
public static function fromFormRequest(int $id UpdateProfileRequest $request): self
36+
{
37+
return new self(
38+
id: $id,
39+
name: Optional::forNullable($request->get('name')),
40+
email: Optional::forNullable($request->get('email')),
41+
bio: Optional::forNullable($request->get('bio')),
42+
);
43+
}
44+
45+
public static function fromArray(array $data): self
46+
{
47+
Assert::keyExists($post, 'id');
48+
Assert::positiveInteger($post['id']);
49+
50+
51+
return new self(
52+
id: $data['id'],
53+
name: Optional::forOptionalArrayKey($data, 'name', Type\non_empty_string()),
54+
email: Optional::forOptionalArrayKey($data, 'email', Type\non_empty_string()),
55+
bio: Optional::forOptionalArrayKey($data, 'bio', Type\non_empty_string()),
56+
);
57+
}
58+
59+
public function handle(UserRepository $users): void
60+
{
61+
$user = $users->findOneById($this->id);
62+
63+
// These callbacks are only called if the value for each optional field is present.
64+
$this->name->apply(fn (string $name) => $user->updateName($name));
65+
$this->email->apply(fn (string $email) => $user->updateEmail($email));
66+
$this->bio->apply(fn (string $bio) => $user->updateBio($bio));
67+
68+
$users->save($user);
69+
}
70+
}
71+
```
72+
73+
Noticed the `\Psl\Type\non_empty_string()` call? That's an abstraction coming from `azjezz/psl`, which allows for having a type declared both at runtime and at static analysis level. We use it to parse inputs into valid values, or to produce crashes, if something is malformed.
74+
75+
The `azjezz/psl`, `Psl\Type` tooling gives us both type safety and runtime validation by implicitly validating our values:
76+
77+
```php
78+
OptionalField::forPossiblyMissingArrayKey(
79+
['foo' => 'bar'],
80+
'foo',
81+
\Psl\Type\positive_int()
82+
); // crashes: `foo` does not contain a `positive-int`!
83+
```

composer.json

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
{
2+
"name": "joelbutcher/php-optional",
3+
"description": "An opinionated implementation of Java's Optional class for PHP.",
4+
"type": "library",
5+
"license": "MIT",
6+
"authors": [
7+
{
8+
"name": "Joel Butcher",
9+
"email": "joel@joelbutcher.co.uk"
10+
}
11+
],
12+
"require": {
13+
"php": "^8.0.2",
14+
"vimeo/psalm": "^4.30",
15+
"azjezz/psl": "^1.9|^2.1"
16+
},
17+
"require-dev": {
18+
"pestphp/pest": "^1.22",
19+
"phpstan/phpstan": "^1.9",
20+
"laravel/pint": "^1.2"
21+
},
22+
"autoload": {
23+
"psr-4": {
24+
"JoelButcher\\PhpOptional\\": "src/",
25+
"JoelButcher\\PhpOptional\\Tests\\": "tests/"
26+
}
27+
},
28+
"config": {
29+
"allow-plugins": {
30+
"pestphp/pest-plugin": true
31+
}
32+
}
33+
}

phpstan.neon

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
parameters:
2+
3+
paths:
4+
- src/
5+
6+
level: 7

phpunit.xml.dist

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
4+
bootstrap="vendor/autoload.php"
5+
colors="true"
6+
>
7+
<testsuites>
8+
<testsuite name="Test Suite">
9+
<directory suffix="Test.php">./tests</directory>
10+
</testsuite>
11+
</testsuites>
12+
<coverage processUncoveredFiles="true">
13+
<include>
14+
<directory suffix=".php">./src</directory>
15+
</include>
16+
</coverage>
17+
</phpunit>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<?php
2+
3+
namespace JoelButcher\PhpOptional\Exceptions;
4+
5+
class NoSuchElementException extends \RuntimeException
6+
{
7+
//
8+
}

0 commit comments

Comments
 (0)