Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
someniatko committed Apr 20, 2021
0 parents commit 1363321
Show file tree
Hide file tree
Showing 9 changed files with 253 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/vendor
/composer.lock
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright (c) 2021 someniatko

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.
46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# someniatko/result-type

Library representing a generic Result type with Success and Error states,
made for aiding this functional programming pattern in PHP.

It is generically typed using Psalm annotations, so you are expected to use Psalm if
you want typechecking of your code.

**Why using this library if `graham-campbell/result-type` exists?**
Unfortunately, there are several downsides of that library:
- while it's also typed with Psalm annotations, actually using and checking against them might be painful.
- it's coupled to the `phpoption/phpoption` library which unfortunately suffers from the same problem.
- there is no convenience method in Result interface which would allow getting either value from it.


## Installation
This library requires PHP 7.4 or 8.0.
You can install it via Composer:

```shell
composer install someniatko/result-type
```


## Usage

See [`ResultInterface`](src/ResultInterface.php) for details.

Example:

```php
<?php

use Someniatko\ResultType\Success;
use Someniatko\ResultType\Error;

$value = (new Success('Let it be'))
->map(fn (string $s) => substr_count($s, ' ')) // Success<2>
->chain(fn (int $wordsCount) => $wordsCount > 3
? new Success('Long text')
: new Error('short text')
) // Error<'short text'>
->map(fn (string $s) => str_replace(' ', '', $s)) // will not be called because we're in Error result
->mapError(fn (string $s) => strtoupper($s)) // Error<'SHORT TEXT'>
->get(); // 'SHORT TEXT'
```
22 changes: 22 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "someniatko/result-type",
"license": "MIT",
"description": "Functional-ish generic Result type: either Success or Error",
"require": {
"php": "~7.4 || ~8.0"
},
"require-dev": {
"phpunit/phpunit": "^9.5",
"psalm/phar": "^4.7"
},
"autoload": {
"psr-4": {
"Someniatko\\ResultType\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Test\\": "test/"
}
}
}
12 changes: 12 additions & 0 deletions phpcs.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8" ?>
<ruleset
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
name="PHP_CodeSniffer"
xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/squizlabs/PHP_CodeSniffer/master/phpcs.xsd"
>
<file>src</file>
<file>test</file>

<rule ref="PSR12">
</rule>
</ruleset>
15 changes: 15 additions & 0 deletions psalm.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?xml version="1.0"?>
<psalm
totallyTyped="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" />
<directory name="test" />
<ignoreFiles>
<directory name="vendor" />
</ignoreFiles>
</projectFiles>
</psalm>
44 changes: 44 additions & 0 deletions src/Error.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

namespace Someniatko\ResultType;

/**
* @template-covariant TError
* @template-implements ResultInterface<never-return, TError>
* @psalm-immutable
*/
final class Error implements ResultInterface
{
/** @var TError */
private $value;

/** @param TError $value */
public function __construct($value)
{
$this->value = $value;
}

public function map(callable $map): ResultInterface
{
// no success value, so nothing to map.
return $this;
}

public function mapError(callable $map): ResultInterface
{
return new self($map($this->value));
}

public function chain(callable $map): ResultInterface
{
// no success value, so nothing to map.
return $this;
}

public function get()
{
return $this->value;
}
}
62 changes: 62 additions & 0 deletions src/ResultInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

declare(strict_types=1);

namespace Someniatko\ResultType;

/**
* @template-covariant TSuccess
* @template-covariant TError
* @psalm-immutable
*/
interface ResultInterface
{
/**
* Takes a callable which maps **success** value to a new value, returns new ResultInterface.
* The callable will be called only if this result is Success.
*
* If this result is Success, returns new Success with changed value.
* If this result is Error, returns it as is.
*
* @template TNewSuccess
*
* @param callable(TSuccess):TNewSuccess $map
* @return self<TNewSuccess, TError>
*/
public function map(callable $map): self;

/**
* Takes a callable which maps **error** value to a new value, returns new ResultInterface.
* The callable will be called only if this result is Error.
*
* If this result is Success, returns it as is.
* If this result is Error, returns new Error with changed value.
* @template TNewError
*
* @param callable(TError):TNewError $map
* @return self<TSuccess, TNewError>
*/
public function mapError(callable $map): self;

/**
* Chains Success path processing. May either just change Success value, or change the result type to Error.
* Takes a callable which takes **success** value and returns new ResultInterface.
* The callable will be called only if this result is Success.
*
* @template TNewSuccess
* @template TNewError
*
* @param callable(TSuccess):self<TNewSuccess, TNewError> $map
* @return self<TNewSuccess, TError|TNewError>
*/
public function chain(callable $map): self;

/**
* Returns the final value of this result.
* The value will be returned for both Success and Error cases.
*
* @return TSuccess|TError
*/
public function get();
}
43 changes: 43 additions & 0 deletions src/Success.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php

declare(strict_types=1);

namespace Someniatko\ResultType;

/**
* @template-covariant TSuccess
* @template-implements ResultInterface<TSuccess, never-return>
* @psalm-immutable
*/
final class Success implements ResultInterface
{
/** @var TSuccess */
private $value;

/** @param TSuccess $value */
public function __construct($value)
{
$this->value = $value;
}

public function map(callable $map): ResultInterface
{
return new self($map($this->value));
}

public function mapError(callable $map): ResultInterface
{
// no error, so nothing to map.
return $this;
}

public function chain(callable $map): ResultInterface
{
return $map($this->value);
}

public function get()
{
return $this->value;
}
}

0 comments on commit 1363321

Please sign in to comment.