-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 80402d5
Showing
23 changed files
with
2,022 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
/vendor | ||
/build | ||
/test-reports | ||
composer.lock | ||
phpunit.xml | ||
psalm.xml | ||
.phpunit.result.cache | ||
.idea |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
# Changelog | ||
All notable changes to this project will be documented in this file. | ||
|
||
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) | ||
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). | ||
|
||
## [0.1.0] - 2020-05-21 | ||
### Added | ||
- Initial release |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
The MIT License (MIT) | ||
|
||
Copyright (c) 2018 Artem Zakirullin | ||
|
||
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: | ||
|
||
The above copyright notice and this permission notice shall be included in | ||
all copies or substantial portions of the Software. | ||
|
||
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
## In the era of strict typing we face a few problems 😕 | ||
|
||
- Type casting (`PHP`'s native implementation is way too "smart") | ||
- Pointless casts like `array => int` are *allowed* | ||
- Boilerplate code to work with variables/arrays (check if `isset()`, throw an exception, cast the type, etc.) | ||
|
||
Consider an example: | ||
```php | ||
$params = $request->getQueryParams(); | ||
$userId = $params['userId'] ?? null; | ||
if ($userId === null) { | ||
throw new BadRequestException(); | ||
} | ||
$userId = (int)$userId; | ||
``` | ||
|
||
## Way too verbose. Any ideas? 🤔 | ||
|
||
```php | ||
$userId = (new TypedAccessor($params))['userId']->getAsInt(); | ||
``` | ||
|
||
## A few real-world examples 🌎 | ||
|
||
```php | ||
$value = new TypedAccessor('25'); | ||
$value->getInt(); // UnexpectedTypeException | ||
$value->getAsInt(); // 25 | ||
|
||
$value = new TypedAccessor('abc'); | ||
$value->getInt(); // UnexpectedTypeException | ||
$value->getAsInt(); // UncastableValueException | ||
$value->findInt(); // null | ||
$value->findInt() ?? 1; // 1 | ||
|
||
$config = new TypedAccessor(['param' => '1']); | ||
$config['a']['b']->getInt(); // MissingKeyException: "MissingKeyException: a.b" | ||
$config['a']->findInt(); // null | ||
$config['param']->getInt(); // UnexpectedTypeException | ||
$config['param']->getAsInt(); // 1 | ||
$config['param']->findInt(); // null | ||
$config['param']->findAsInt(); // 1 | ||
``` | ||
|
||
Having trouble grasping `get()`/`find()`? Check out brilliant [Ocramius's slides](https://ocramius.github.io/doctrine-best-practices/#/94). | ||
|
||
## The behaviour now is rather predictable 🍀 | ||
|
||
```php | ||
'\d+' => int // OK` | ||
'buzz12' => int // UncastableValueException | ||
bool => int // UncastableValueException | ||
array => int // UncastableValueException | ||
object => int // UncastableValueException | ||
resource => int // UncastableValueException | ||
``` | ||
|
||
Fairly simple, isn't it? | ||
|
||
### Why one needs THAT naive type casting? 🤔 | ||
|
||
Let's imagine a library that is configured that way: | ||
```php | ||
$config = [ | ||
'retries' => 5, // int | ||
'delay' => 20, // int | ||
] | ||
|
||
// Initialization | ||
$retries = $config['retries'] ?? null; | ||
if ($retries === null) { | ||
throw new MissingConfigKeyException(...); | ||
} | ||
... | ||
$retries = (int)$retries; | ||
$delay = (int)$delay; | ||
``` | ||
|
||
Client-side code: | ||
```php | ||
$config => [ | ||
'retries' => [5, 10, 30], // (int)array => 1 | ||
'delay' => true, // (int)bool => 1 | ||
] | ||
``` | ||
|
||
No matter if that's a misuse or a result of major update: The system will continue to work. | ||
And that's the worst thing about it. It will continue to work, though, not in a way it was supposed to work. | ||
`PHP` is trying to do its best to let it work *at least somehow*. | ||
|
||
## The library comes in handy in a variety of scenarios 🚀 | ||
|
||
- Deserialized data | ||
- Request `body`/`query` | ||
- `API` responses | ||
- etc. | ||
|
||
```bash | ||
$ composer require zakirullin/typed-accessor | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
{ | ||
"name": "zakirullin/typed-accessor", | ||
"type": "library", | ||
"description": "Convenient array-related routine & better type casting", | ||
"keywords": [ | ||
"array", | ||
"type", | ||
"cast", | ||
"language", | ||
"php", | ||
"json" | ||
], | ||
"homepage": "https://github.com/zakirullin/typed-accessor", | ||
"license": "MIT", | ||
"authors": [ | ||
{ | ||
"name": "Artem Zakirullin", | ||
"email": "[email protected]" | ||
} | ||
], | ||
"config": { | ||
"sort-packages": true | ||
}, | ||
"require": { | ||
"php": "^7.2" | ||
}, | ||
"require-dev": { | ||
"infection/infection": "^0.15", | ||
"phpunit/phpunit": "^8.0", | ||
"vimeo/psalm": "^3.8" | ||
}, | ||
"autoload": { | ||
"psr-4": { | ||
"Zakirullin\\TypedAccessor\\": "src/" | ||
} | ||
}, | ||
"autoload-dev": { | ||
"psr-4": { | ||
"Zakirullin\\TypedAccessor\\Tests\\": "tests/unit" | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
{ | ||
"timeout": 10, | ||
"source": { | ||
"directories": [ | ||
"src" | ||
] | ||
}, | ||
"logs": { | ||
"text": "build/log/infection/text.txt", | ||
"summary": "build/log/infection/summary.txt", | ||
"debug": "build/log/infection/debug.txt", | ||
"perMutator": "build/log/infection/per-mutator.md" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
<?xml version="1.0" encoding="UTF-8"?> | ||
<phpunit | ||
colors="true" | ||
forceCoversAnnotation="true" | ||
defaultTestSuite="all"> | ||
<testsuites> | ||
<testsuite name="all"> | ||
<directory>tests/unit/</directory> | ||
</testsuite> | ||
<testsuite name="unit"> | ||
<directory>tests/unit/</directory> | ||
</testsuite> | ||
</testsuites> | ||
<filter> | ||
<whitelist processUncoveredFilesFromWhitelist="true"> | ||
<directory suffix=".php">src/</directory> | ||
</whitelist> | ||
</filter> | ||
</phpunit> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
<?xml version="1.0"?> | ||
<psalm | ||
errorLevel="1" | ||
resolveFromConfigFile="true" | ||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
xmlns="https://getpsalm.org/schema/config" | ||
xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd" | ||
> | ||
<projectFiles> | ||
<directory name="src" /> | ||
<ignoreFiles> | ||
<directory name="vendor" /> | ||
</ignoreFiles> | ||
</projectFiles> | ||
</psalm> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
<?php | ||
declare(strict_types=1); | ||
|
||
namespace Zakirullin\TypedAccessor\Exception; | ||
|
||
use RuntimeException; | ||
use Throwable; | ||
|
||
final class CannotModifyAccessorException extends RuntimeException implements TypedAccessorExceptionInterface | ||
{ | ||
/** | ||
* @var array | ||
*/ | ||
private $keySequence; | ||
|
||
/** | ||
* @param array $keySequence | ||
* @param Throwable|null $previous | ||
*/ | ||
public function __construct(array $keySequence, Throwable $previous = null) | ||
{ | ||
$this->keySequence = $keySequence; | ||
|
||
$message = "TypedAccessor cannot modify it's value"; | ||
|
||
parent::__construct($message, 0, $previous); | ||
} | ||
|
||
/** | ||
* @psalm-return list<string> | ||
* @return array | ||
*/ | ||
public function getKeySequence(): array | ||
{ | ||
return $this->keySequence; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
<?php | ||
declare(strict_types=1); | ||
|
||
namespace Zakirullin\TypedAccessor\Exception; | ||
|
||
use RuntimeException; | ||
use Throwable; | ||
use function implode; | ||
|
||
final class MissingKeyException extends RuntimeException implements TypedAccessorExceptionInterface | ||
{ | ||
/** | ||
* @var array | ||
*/ | ||
private $keySequence; | ||
|
||
/** | ||
* @param array $keySequence | ||
* @param Throwable|null $previous | ||
*/ | ||
public function __construct(array $keySequence, Throwable $previous = null) | ||
{ | ||
$this->keySequence = $keySequence; | ||
|
||
$message = "Missing key: '{$this->getKey()}'"; | ||
|
||
parent::__construct($message, 0, $previous); | ||
} | ||
|
||
/** | ||
* @return array | ||
*/ | ||
public function getKeySequence(): array | ||
{ | ||
return $this->keySequence; | ||
} | ||
|
||
/** | ||
* @return string | ||
*/ | ||
private function getKey(): string | ||
{ | ||
$absoluteKey = implode('.', $this->keySequence); | ||
|
||
return $absoluteKey; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
<?php | ||
declare(strict_types=1); | ||
|
||
namespace Zakirullin\TypedAccessor\Exception; | ||
|
||
interface TypedAccessorExceptionInterface | ||
{ | ||
/** | ||
* @psalm-return list<string> | ||
* @return array | ||
*/ | ||
public function getKeySequence(): array; | ||
} |
Oops, something went wrong.