관리-도구
편집 파일: phpoption.tar
phpoption/src/PhpOption/None.php 0000604 00000004620 15224653441 0012707 0 ustar 00 <?php /* * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace PhpOption; use EmptyIterator; final class None extends Option { private static $instance; public static function create() { if (null === self::$instance) { self::$instance = new self(); } return self::$instance; } public function get() { throw new \RuntimeException('None has no value.'); } public function getOrCall($callable) { return call_user_func($callable); } public function getOrElse($default) { return $default; } public function getOrThrow(\Exception $ex) { throw $ex; } public function isEmpty() { return true; } public function isDefined() { return false; } public function orElse(Option $else) { return $else; } /** * @deprecated Use forAll() instead. */ public function ifDefined($callable) { // Just do nothing in that case. } public function forAll($callable) { return $this; } public function map($callable) { return $this; } public function flatMap($callable) { return $this; } public function filter($callable) { return $this; } public function filterNot($callable) { return $this; } public function select($value) { return $this; } public function reject($value) { return $this; } public function getIterator() { return new EmptyIterator(); } public function foldLeft($initialValue, $callable) { return $initialValue; } public function foldRight($initialValue, $callable) { return $initialValue; } private function __construct() { } } phpoption/src/PhpOption/Some.php 0000604 00000006176 15224653441 0012723 0 ustar 00 <?php /* * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace PhpOption; use ArrayIterator; final class Some extends Option { private $value; public function __construct($value) { $this->value = $value; } public static function create($value) { return new self($value); } public function isDefined() { return true; } public function isEmpty() { return false; } public function get() { return $this->value; } public function getOrElse($default) { return $this->value; } public function getOrCall($callable) { return $this->value; } public function getOrThrow(\Exception $ex) { return $this->value; } public function orElse(Option $else) { return $this; } /** * @deprecated Use forAll() instead. */ public function ifDefined($callable) { call_user_func($callable, $this->value); } public function forAll($callable) { call_user_func($callable, $this->value); return $this; } public function map($callable) { return new self(call_user_func($callable, $this->value)); } public function flatMap($callable) { $rs = call_user_func($callable, $this->value); if ( ! $rs instanceof Option) { throw new \RuntimeException('Callables passed to flatMap() must return an Option. Maybe you should use map() instead?'); } return $rs; } public function filter($callable) { if (true === call_user_func($callable, $this->value)) { return $this; } return None::create(); } public function filterNot($callable) { if (false === call_user_func($callable, $this->value)) { return $this; } return None::create(); } public function select($value) { if ($this->value === $value) { return $this; } return None::create(); } public function reject($value) { if ($this->value === $value) { return None::create(); } return $this; } public function getIterator() { return new ArrayIterator(array($this->value)); } public function foldLeft($initialValue, $callable) { return call_user_func($callable, $initialValue, $this->value); } public function foldRight($initialValue, $callable) { return call_user_func($callable, $this->value, $initialValue); } } phpoption/src/PhpOption/LazyOption.php 0000604 00000007420 15224653441 0014121 0 ustar 00 <?php /* * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace PhpOption; final class LazyOption extends Option { /** @var callable */ private $callback; /** @var array */ private $arguments; /** @var Option|null */ private $option; /** * Helper Constructor. * * @param callable $callback * @param array $arguments * * @return LazyOption */ public static function create($callback, array $arguments = array()) { return new self($callback, $arguments); } /** * Constructor. * * @param callable $callback * @param array $arguments */ public function __construct($callback, array $arguments = array()) { if (!is_callable($callback)) { throw new \InvalidArgumentException('Invalid callback given'); } $this->callback = $callback; $this->arguments = $arguments; } public function isDefined() { return $this->option()->isDefined(); } public function isEmpty() { return $this->option()->isEmpty(); } public function get() { return $this->option()->get(); } public function getOrElse($default) { return $this->option()->getOrElse($default); } public function getOrCall($callable) { return $this->option()->getOrCall($callable); } public function getOrThrow(\Exception $ex) { return $this->option()->getOrThrow($ex); } public function orElse(Option $else) { return $this->option()->orElse($else); } /** * @deprecated Use forAll() instead. */ public function ifDefined($callable) { $this->option()->ifDefined($callable); } public function forAll($callable) { return $this->option()->forAll($callable); } public function map($callable) { return $this->option()->map($callable); } public function flatMap($callable) { return $this->option()->flatMap($callable); } public function filter($callable) { return $this->option()->filter($callable); } public function filterNot($callable) { return $this->option()->filterNot($callable); } public function select($value) { return $this->option()->select($value); } public function reject($value) { return $this->option()->reject($value); } public function getIterator() { return $this->option()->getIterator(); } public function foldLeft($initialValue, $callable) { return $this->option()->foldLeft($initialValue, $callable); } public function foldRight($initialValue, $callable) { return $this->option()->foldRight($initialValue, $callable); } /** * @return Option */ private function option() { if (null === $this->option) { $this->option = call_user_func_array($this->callback, $this->arguments); if (!$this->option instanceof Option) { $this->option = null; throw new \RuntimeException('Expected instance of \PhpOption\Option'); } } return $this->option; } } phpoption/src/PhpOption/Option.php 0000604 00000025452 15224653441 0013266 0 ustar 00 <?php /* * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace PhpOption; use IteratorAggregate; /** * Base Option Class. * * @author Johannes M. Schmitt <schmittjoh@gmail.com> */ abstract class Option implements IteratorAggregate { /** * Creates an option given a return value. * * This is intended for consuming existing APIs and allows you to easily * convert them to an option. By default, we treat ``null`` as the None case, * and everything else as Some. * * @param mixed $value The actual return value. * @param mixed $noneValue The value which should be considered "None"; null * by default. * * @return Option */ public static function fromValue($value, $noneValue = null) { if ($value === $noneValue) { return None::create(); } return new Some($value); } /** * Creates an option from an array's value. * * If the key does not exist in the array, the array is not actually an array, or the * array's value at the given key is null, None is returned. * * Otherwise, Some is returned wrapping the value at the given key. * * @param mixed $array a potential array value * @param string $key the key to check * * @return Option */ public static function fromArraysValue($array, $key) { if ( ! isset($array[$key])) { return None::create(); } return new Some($array[$key]); } /** * Creates a lazy-option with the given callback. * * This is also a helper constructor for lazy-consuming existing APIs where * the return value is not yet an option. By default, we treat ``null`` as * None case, and everything else as Some. * * @param callable $callback The callback to evaluate. * @param array $arguments * @param mixed $noneValue The value which should be considered "None"; null * by default. * * @return Option */ public static function fromReturn($callback, array $arguments = array(), $noneValue = null) { return new LazyOption(function() use ($callback, $arguments, $noneValue) { $return = call_user_func_array($callback, $arguments); if ($return === $noneValue) { return None::create(); } return new Some($return); }); } /** * Option factory, which creates new option based on passed value. * If value is already an option, it simply returns * If value is a \Closure, LazyOption with passed callback created and returned. If Option returned from callback, * it returns directly (flatMap-like behaviour) * On other case value passed to Option::fromValue() method * * @param Option|\Closure|mixed $value * @param null $noneValue used when $value is mixed or Closure, for None-check * * @return Option */ public static function ensure($value, $noneValue = null) { if ($value instanceof Option) { return $value; } elseif ($value instanceof \Closure) { return new LazyOption(function() use ($value, $noneValue) { $return = $value(); if ($return instanceof Option) { return $return; } else { return Option::fromValue($return, $noneValue); } }); } else { return Option::fromValue($value, $noneValue); } } /** * Returns the value if available, or throws an exception otherwise. * * @throws \RuntimeException if value is not available * * @return mixed */ abstract public function get(); /** * Returns the value if available, or the default value if not. * * @param mixed $default * * @return mixed */ abstract public function getOrElse($default); /** * Returns the value if available, or the results of the callable. * * This is preferable over ``getOrElse`` if the computation of the default * value is expensive. * * @param callable $callable * * @return mixed */ abstract public function getOrCall($callable); /** * Returns the value if available, or throws the passed exception. * * @param \Exception $ex * * @return mixed */ abstract public function getOrThrow(\Exception $ex); /** * Returns true if no value is available, false otherwise. * * @return boolean */ abstract public function isEmpty(); /** * Returns true if a value is available, false otherwise. * * @return boolean */ abstract public function isDefined(); /** * Returns this option if non-empty, or the passed option otherwise. * * This can be used to try multiple alternatives, and is especially useful * with lazy evaluating options: * * ```php * $repo->findSomething() * ->orElse(new LazyOption(array($repo, 'findSomethingElse'))) * ->orElse(new LazyOption(array($repo, 'createSomething'))); * ``` * * @param Option $else * * @return Option */ abstract public function orElse(Option $else); /** * This is similar to map() below except that the return value has no meaning; * the passed callable is simply executed if the option is non-empty, and * ignored if the option is empty. * * In all cases, the return value of the callable is discarded. * * ```php * $comment->getMaybeFile()->ifDefined(function($file) { * // Do something with $file here. * }); * ``` * * If you're looking for something like ``ifEmpty``, you can use ``getOrCall`` * and ``getOrElse`` in these cases. * * @deprecated Use forAll() instead. * * @param callable $callable * * @return void */ abstract public function ifDefined($callable); /** * This is similar to map() except that the return value of the callable has no meaning. * * The passed callable is simply executed if the option is non-empty, and ignored if the * option is empty. This method is preferred for callables with side-effects, while map() * is intended for callables without side-effects. * * @param callable $callable * * @return Option */ abstract public function forAll($callable); /** * Applies the callable to the value of the option if it is non-empty, * and returns the return value of the callable wrapped in Some(). * * If the option is empty, then the callable is not applied. * * ```php * (new Some("foo"))->map('strtoupper')->get(); // "FOO" * ``` * * @param callable $callable * * @return Option */ abstract public function map($callable); /** * Applies the callable to the value of the option if it is non-empty, and * returns the return value of the callable directly. * * In contrast to ``map``, the return value of the callable is expected to * be an Option itself; it is not automatically wrapped in Some(). * * @param callable $callable must return an Option * * @return Option */ abstract public function flatMap($callable); /** * If the option is empty, it is returned immediately without applying the callable. * * If the option is non-empty, the callable is applied, and if it returns true, * the option itself is returned; otherwise, None is returned. * * @param callable $callable * * @return Option */ abstract public function filter($callable); /** * If the option is empty, it is returned immediately without applying the callable. * * If the option is non-empty, the callable is applied, and if it returns false, * the option itself is returned; otherwise, None is returned. * * @param callable $callable * * @return Option */ abstract public function filterNot($callable); /** * If the option is empty, it is returned immediately. * * If the option is non-empty, and its value does not equal the passed value * (via a shallow comparison ===), then None is returned. Otherwise, the * Option is returned. * * In other words, this will filter all but the passed value. * * @param mixed $value * * @return Option */ abstract public function select($value); /** * If the option is empty, it is returned immediately. * * If the option is non-empty, and its value does equal the passed value (via * a shallow comparison ===), then None is returned; otherwise, the Option is * returned. * * In other words, this will let all values through except the passed value. * * @param mixed $value * * @return Option */ abstract public function reject($value); /** * Binary operator for the initial value and the option's value. * * If empty, the initial value is returned. * If non-empty, the callable receives the initial value and the option's value as arguments * * ```php * * $some = new Some(5); * $none = None::create(); * $result = $some->foldLeft(1, function($a, $b) { return $a + $b; }); // int(6) * $result = $none->foldLeft(1, function($a, $b) { return $a + $b; }); // int(1) * * // This can be used instead of something like the following: * $option = Option::fromValue($integerOrNull); * $result = 1; * if ( ! $option->isEmpty()) { * $result += $option->get(); * } * ``` * * @param mixed $initialValue * @param callable $callable function(initialValue, callable): result * * @return mixed */ abstract public function foldLeft($initialValue, $callable); /** * foldLeft() but with reversed arguments for the callable. * * @param mixed $initialValue * @param callable $callable function(callable, initialValue): result * * @return mixed */ abstract public function foldRight($initialValue, $callable); } phpoption/LICENSE 0000604 00000026134 15224653441 0007601 0 ustar 00 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. phpoption/composer.json 0000604 00000001112 15224653441 0011303 0 ustar 00 { "name": "phpoption/phpoption", "description": "Option Type for PHP", "keywords": ["php","option","language","type"], "type": "library", "license": "Apache2", "authors": [ { "name": "Johannes M. Schmitt", "email": "schmittjoh@gmail.com" } ], "require": { "php": ">=5.3.0" }, "require-dev": { "phpunit/phpunit": "4.7.*" }, "autoload": { "psr-0": { "PhpOption\\": "src/" } }, "extra": { "branch-alias": { "dev-master": "1.3-dev" } } } phpoption/Makefile 0000604 00000002647 15224653441 0010237 0 ustar 00 install: @docker run -it -w /data -v ${PWD}:/data:delegated -v ~/.composer:/root/.composer:delegated --entrypoint composer --rm registry.gitlab.com/grahamcampbell/php:7.4-base update @docker run -it -w /data -v ${PWD}:/data:delegated -v ~/.composer:/root/.composer:delegated --entrypoint composer --rm registry.gitlab.com/grahamcampbell/php:7.4-base bin all update phpunit: @rm -f bootstrap/cache/*.php && docker run -it -w /data -v ${PWD}:/data:delegated --entrypoint vendor/bin/phpunit --rm registry.gitlab.com/grahamcampbell/php:7.4-cli phpstan-analyze-src: @docker run -it -w /data -v ${PWD}:/data:delegated --entrypoint vendor/bin/phpstan --rm registry.gitlab.com/grahamcampbell/php:7.4-cli analyze src -c phpstan.src.neon.dist phpstan-analyze-tests: @docker run -it -w /data -v ${PWD}:/data:delegated --entrypoint vendor/bin/phpstan --rm registry.gitlab.com/grahamcampbell/php:7.4-cli analyze tests -c phpstan.tests.neon.dist psalm-analyze: @docker run -it -w /data -v ${PWD}:/data:delegated --entrypoint vendor/bin/psalm.phar --rm registry.gitlab.com/grahamcampbell/php:7.4-cli psalm-show-info: @docker run -it -w /data -v ${PWD}:/data:delegated --entrypoint vendor/bin/psalm .phar--rm registry.gitlab.com/grahamcampbell/php:7.4-cli --show-info=true test: phpunit phpstan-analyze-src phpstan-analyze-tests psalm-analyze clean: @rm -rf .phpunit.result.cache composer.lock vendor vendor-bin/*/composer.lock vendor-bin/*/vendor phpoption/tests/PhpOption/Tests/LazyOptionTest.php 0000604 00000014450 15224664617 0016446 0 ustar 00 <?php namespace PhpOption\Tests; use PhpOption\LazyOption; class LazyOptionTest extends \PHPUnit_Framework_TestCase { private $subject; public function setUp() { $this->subject = $this ->getMockBuilder('Subject') ->setMethods(array('execute')) ->getMock(); } public function testGetWithArgumentsAndConstructor() { $some = \PhpOption\LazyOption::create(array($this->subject, 'execute'), array('foo')); $this->subject ->expects($this->once()) ->method('execute') ->with('foo') ->will($this->returnValue(\PhpOption\Some::create('foo'))); $this->assertEquals('foo', $some->get()); $this->assertEquals('foo', $some->getOrElse(null)); $this->assertEquals('foo', $some->getOrCall('does_not_exist')); $this->assertEquals('foo', $some->getOrThrow(new \RuntimeException('does_not_exist'))); $this->assertFalse($some->isEmpty()); } public function testGetWithArgumentsAndCreate() { $some = new \PhpOption\LazyOption(array($this->subject, 'execute'), array('foo')); $this->subject ->expects($this->once()) ->method('execute') ->with('foo') ->will($this->returnValue(\PhpOption\Some::create('foo'))); $this->assertEquals('foo', $some->get()); $this->assertEquals('foo', $some->getOrElse(null)); $this->assertEquals('foo', $some->getOrCall('does_not_exist')); $this->assertEquals('foo', $some->getOrThrow(new \RuntimeException('does_not_exist'))); $this->assertFalse($some->isEmpty()); } public function testGetWithoutArgumentsAndConstructor() { $some = new \PhpOption\LazyOption(array($this->subject, 'execute')); $this->subject ->expects($this->once()) ->method('execute') ->will($this->returnValue(\PhpOption\Some::create('foo'))); $this->assertEquals('foo', $some->get()); $this->assertEquals('foo', $some->getOrElse(null)); $this->assertEquals('foo', $some->getOrCall('does_not_exist')); $this->assertEquals('foo', $some->getOrThrow(new \RuntimeException('does_not_exist'))); $this->assertFalse($some->isEmpty()); } public function testGetWithoutArgumentsAndCreate() { $option = \PhpOption\LazyOption::create(array($this->subject, 'execute')); $this->subject ->expects($this->once()) ->method('execute') ->will($this->returnValue(\PhpOption\Some::create('foo'))); $this->assertTrue($option->isDefined()); $this->assertFalse($option->isEmpty()); $this->assertEquals('foo', $option->get()); $this->assertEquals('foo', $option->getOrElse(null)); $this->assertEquals('foo', $option->getOrCall('does_not_exist')); $this->assertEquals('foo', $option->getOrThrow(new \RuntimeException('does_not_exist'))); } /** * @expectedException \RuntimeException * @expectedExceptionMessage None has no value */ public function testCallbackReturnsNull() { $option = \PhpOption\LazyOption::create(array($this->subject, 'execute')); $this->subject ->expects($this->once()) ->method('execute') ->will($this->returnValue(\PhpOption\None::create())); $this->assertFalse($option->isDefined()); $this->assertTrue($option->isEmpty()); $this->assertEquals('alt', $option->getOrElse('alt')); $this->assertEquals('alt', $option->getOrCall(function(){return 'alt';})); $option->get(); } /** * @expectedException \RuntimeException * @expectedExceptionMessage Expected instance of \PhpOption\Option */ public function testExceptionIsThrownIfCallbackReturnsNonOption() { $option = \PhpOption\LazyOption::create(array($this->subject, 'execute')); $this->subject ->expects($this->once()) ->method('execute') ->will($this->returnValue(null)); $this->assertFalse($option->isDefined()); } /** * @expectedException InvalidArgumentException * @expectedExceptionMessage Invalid callback given */ public function testInvalidCallbackAndConstructor() { new \PhpOption\LazyOption('invalidCallback'); } /** * @expectedException InvalidArgumentException * @expectedExceptionMessage Invalid callback given */ public function testInvalidCallbackAndCreate() { \PhpOption\LazyOption::create('invalidCallback'); } public function testifDefined() { $called = false; $self = $this; $this->assertNull(LazyOption::fromValue('foo')->ifDefined(function($v) use (&$called, $self) { $called = true; $self->assertEquals('foo', $v); })); $this->assertTrue($called); } public function testForAll() { $called = false; $self = $this; $this->assertInstanceOf('PhpOption\Some', LazyOption::fromValue('foo')->forAll(function($v) use (&$called, $self) { $called = true; $self->assertEquals('foo', $v); })); $this->assertTrue($called); } public function testOrElse() { $some = \PhpOption\Some::create('foo'); $lazy = \PhpOption\LazyOption::create(function() use ($some) {return $some;}); $this->assertSame($some, $lazy->orElse(\PhpOption\None::create())); $this->assertSame($some, $lazy->orElse(\PhpOption\Some::create('bar'))); } public function testFoldLeftRight() { $callback = function() { }; $option = $this->getMockForAbstractClass('PhpOption\Option'); $option->expects($this->once()) ->method('foldLeft') ->with(5, $callback) ->will($this->returnValue(6)); $lazyOption = new LazyOption(function() use ($option) { return $option; }); $this->assertSame(6, $lazyOption->foldLeft(5, $callback)); $option->expects($this->once()) ->method('foldRight') ->with(5, $callback) ->will($this->returnValue(6)); $lazyOption = new LazyOption(function() use ($option) { return $option; }); $this->assertSame(6, $lazyOption->foldRight(5, $callback)); } } phpoption/tests/PhpOption/Tests/NoneTest.php 0000604 00000006025 15224664617 0015234 0 ustar 00 <?php namespace PhpOption\Tests; use PhpOption\None; class NoneTest extends \PHPUnit_Framework_TestCase { private $none; /** * @expectedException \RuntimeException */ public function testGet() { $none = \PhpOption\None::create(); $none->get(); } public function testGetOrElse() { $none = \PhpOption\None::create(); $this->assertEquals('foo', $none->getOrElse('foo')); } public function testGetOrCall() { $none = \PhpOption\None::create(); $this->assertEquals('foo', $none->getOrCall(function() { return 'foo'; })); } /** * @expectedException \RuntimeException * @expectedExceptionMessage Not Found! */ public function testGetOrThrow() { None::create()->getOrThrow(new \RuntimeException('Not Found!')); } public function testIsEmpty() { $none = \PhpOption\None::create(); $this->assertTrue($none->isEmpty()); } public function testOrElse() { $option = \PhpOption\Some::create('foo'); $this->assertSame($option, \PhpOption\None::create()->orElse($option)); } public function testifDefined() { $this->assertNull($this->none->ifDefined(function() { throw new \LogicException('Should never be called.'); })); } public function testForAll() { $this->assertSame($this->none, $this->none->forAll(function() { throw new \LogicException('Should never be called.'); })); } public function testMap() { $this->assertSame($this->none, $this->none->map(function() { throw new \LogicException('Should not be called.'); })); } public function testFlatMap() { $this->assertSame($this->none, $this->none->flatMap(function() { throw new \LogicException('Should not be called.'); })); } public function testFilter() { $this->assertSame($this->none, $this->none->filter(function() { throw new \LogicException('Should not be called.'); })); } public function testFilterNot() { $this->assertSame($this->none, $this->none->filterNot(function() { throw new \LogicException('Should not be called.'); })); } public function testSelect() { $this->assertSame($this->none, $this->none->select(null)); } public function testReject() { $this->assertSame($this->none, $this->none->reject(null)); } public function testForeach() { $none = \PhpOption\None::create(); $called = 0; foreach ($none as $value) { $called++; } $this->assertEquals(0, $called); } public function testFoldLeftRight() { $this->assertSame(1, $this->none->foldLeft(1, function() { $this->fail(); })); $this->assertSame(1, $this->none->foldRight(1, function() { $this->fail(); })); } protected function setUp() { $this->none = None::create(); } } phpoption/tests/PhpOption/Tests/OptionTest.php 0000604 00000005625 15224664617 0015612 0 ustar 00 <?php namespace PhpOption\Tests; use PhpOption\None; use PhpOption\Option; use PhpOption\Some; class OptionTest extends \PHPUnit_Framework_TestCase { public function testfromValueWithDefaultNoneValue() { $this->assertInstanceOf('PhpOption\None', \PhpOption\Option::fromValue(null)); $this->assertInstanceOf('PhpOption\Some', \PhpOption\Option::fromValue('value')); } public function testFromValueWithFalseNoneValue() { $this->assertInstanceOf('PhpOption\None', \PhpOption\Option::fromValue(false, false)); $this->assertInstanceOf('PhpOption\Some', \PhpOption\Option::fromValue('value', false)); $this->assertInstanceOf('PhpOption\Some', \PhpOption\Option::fromValue(null, false)); } public function testFromArraysValue() { $this->assertEquals(None::create(), Option::fromArraysValue('foo', 'bar')); $this->assertEquals(None::create(), Option::fromArraysValue(null, 'bar')); $this->assertEquals(None::create(), Option::fromArraysValue(array('foo' => 'bar'), 'baz')); $this->assertEquals(None::create(), Option::fromArraysValue(array('foo' => null), 'foo')); $this->assertEquals(new Some('foo'), Option::fromArraysValue(array('foo' => 'foo'), 'foo')); } public function testFromReturn() { $null = function() { return null; }; $false = function() { return false; }; $some = function() { return 'foo'; }; $this->assertTrue(\PhpOption\Option::fromReturn($null)->isEmpty()); $this->assertFalse(\PhpOption\Option::fromReturn($false)->isEmpty()); $this->assertTrue(\PhpOption\Option::fromReturn($false, array(), false)->isEmpty()); $this->assertTrue(\PhpOption\Option::fromReturn($some)->isDefined()); $this->assertFalse(\PhpOption\Option::fromReturn($some, array(), 'foo')->isDefined()); } public function testOrElse() { $a = new \PhpOption\Some('a'); $b = new \PhpOption\Some('b'); $this->assertEquals('a', $a->orElse($b)->get()); } public function testOrElseWithNoneAsFirst() { $a = \PhpOption\None::create(); $b = new \PhpOption\Some('b'); $this->assertEquals('b', $a->orElse($b)->get()); } public function testOrElseWithLazyOptions() { $throws = function() { throw new \LogicException('Should never be called.'); }; $a = new \PhpOption\Some('a'); $b = new \PhpOption\LazyOption($throws); $this->assertEquals('a', $a->orElse($b)->get()); } public function testOrElseWithMultipleAlternatives() { $throws = new \PhpOption\LazyOption(function() { throw new \LogicException('Should never be called.'); }); $returns = new \PhpOption\LazyOption(function() { return new \PhpOption\Some('foo'); }); $a = \PhpOption\None::create(); $this->assertEquals('foo', $a->orElse($returns)->orElse($throws)->get()); } } phpoption/tests/PhpOption/Tests/EnsureTest.php 0000604 00000003532 15224664617 0015576 0 ustar 00 <?php namespace PhpOption\Tests; use PhpOption\None; use PhpOption\Option; use PhpOption\Some; /** * Tests for Option::ensure() method * * @covers Option::ensure */ class EnsureTest extends \PHPUnit_Framework_TestCase { protected function ensure($value, $noneValue = null) { $option = Option::ensure($value, $noneValue); $this->assertInstanceOf('PhpOption\Option', $option); return $option; } public function testMixedValue() { $option = $this->ensure(1); $this->assertTrue($option->isDefined()); $this->assertSame(1, $option->get()); $this->assertFalse($this->ensure(null)->isDefined()); $this->assertFalse($this->ensure(1,1)->isDefined()); } public function testReturnValue() { $option = $this->ensure(function() { return 1; }); $this->assertTrue($option->isDefined()); $this->assertSame(1, $option->get()); $this->assertFalse($this->ensure(function() { return null; })->isDefined()); $this->assertFalse($this->ensure(function() { return 1; }, 1)->isDefined()); } public function testOptionReturnsAsSameInstance() { $option = $this->ensure(1); $this->assertSame($option, $this->ensure($option)); } public function testOptionReturnedFromClosure() { $option = $this->ensure(function() { return Some::create(1); }); $this->assertTrue($option->isDefined()); $this->assertSame(1, $option->get()); $option = $this->ensure(function() { return None::create(); }); $this->assertFalse($option->isDefined()); } public function testClosureReturnedFromClosure() { $option = $this->ensure(function() { return function() {}; }); $this->assertTrue($option->isDefined()); $this->assertInstanceOf('Closure', $option->get()); } } phpoption/tests/PhpOption/Tests/PerformanceTest.php 0000604 00000004174 15224664617 0016601 0 ustar 00 <?php namespace PhpOption\Tests; /** * @group performance */ class PerformanceTest extends \PHPUnit_Framework_TestCase { private $traditionalRepo; private $phpOptionRepo; public function testSomeCase() { $traditionalTime = microtime(true); for ($i=0; $i<10000; $i++) { if (null === $rs = $this->traditionalRepo->findMaybe(true)) { $rs = new \stdClass(); } } $traditionalTime = microtime(true) - $traditionalTime; $phpOptionTime = microtime(true); for ($i=0; $i<10000; $i++) { $rs = $this->phpOptionRepo->findMaybe(true)->getOrElse(new \stdClass); } $phpOptionTime = microtime(true) - $phpOptionTime; $overheadPerInvocation = ($phpOptionTime - $traditionalTime) / 10000; printf("Overhead per invocation (some case): %.9fs\n", $overheadPerInvocation); } public function testNoneCase() { $traditionalTime = microtime(true); for ($i=0; $i<10000; $i++) { if (null === $rs = $this->traditionalRepo->findMaybe(false)) { $rs = new \stdClass(); } } $traditionalTime = microtime(true) - $traditionalTime; $phpOptionTime = microtime(true); for ($i=0; $i<10000; $i++) { $rs = $this->phpOptionRepo->findMaybe(false)->getOrElse(new \stdClass); } $phpOptionTime = microtime(true) - $phpOptionTime; $overheadPerInvocation = ($phpOptionTime - $traditionalTime) / 10000; printf("Overhead per invocation (none case): %.9fs\n", $overheadPerInvocation); } protected function setUp() { $this->traditionalRepo = new TraditionalRepo(); $this->phpOptionRepo = new PhpOptionRepo(); } } class TraditionalRepo { public function findMaybe($success) { if ($success) { return new \stdClass; } return null; } } class PhpOptionRepo { public function findMaybe($success) { if ($success) { return new \PhpOption\Some(new \stdClass); } return \PhpOption\None::create(); } } phpoption/tests/PhpOption/Tests/SomeTest.php 0000604 00000012251 15224664617 0015236 0 ustar 00 <?php namespace PhpOption\Tests; use PhpOption\Some; class SomeTest extends \PHPUnit_Framework_TestCase { public function testGet() { $some = new \PhpOption\Some('foo'); $this->assertEquals('foo', $some->get()); $this->assertEquals('foo', $some->getOrElse(null)); $this->assertEquals('foo', $some->getOrCall('does_not_exist')); $this->assertEquals('foo', $some->getOrThrow(new \RuntimeException('Not found'))); $this->assertFalse($some->isEmpty()); } public function testCreate() { $some = \PhpOption\Some::create('foo'); $this->assertEquals('foo', $some->get()); $this->assertEquals('foo', $some->getOrElse(null)); $this->assertEquals('foo', $some->getOrCall('does_not_exist')); $this->assertEquals('foo', $some->getOrThrow(new \RuntimeException('Not found'))); $this->assertFalse($some->isEmpty()); } public function testOrElse() { $some = \PhpOption\Some::create('foo'); $this->assertSame($some, $some->orElse(\PhpOption\None::create())); $this->assertSame($some, $some->orElse(\PhpOption\Some::create('bar'))); } public function testifDefined() { $called = false; $self = $this; $some = new Some('foo'); $this->assertNull($some->ifDefined(function($v) use (&$called, $self) { $called = true; $self->assertEquals('foo', $v); })); $this->assertTrue($called); } public function testForAll() { $called = false; $self = $this; $some = new Some('foo'); $this->assertSame($some, $some->forAll(function($v) use (&$called, $self) { $called = true; $self->assertEquals('foo', $v); })); $this->assertTrue($called); } public function testMap() { $some = new Some('foo'); $this->assertEquals('o', $some->map(function($v) { return substr($v, 1, 1); })->get()); } public function testFlatMap() { $repo = new Repository(array('foo')); $this->assertEquals(array('name' => 'foo'), $repo->getLastRegisteredUsername() ->flatMap(array($repo, 'getUser')) ->getOrCall(array($repo, 'getDefaultUser'))); } public function testFilter() { $some = new Some('foo'); $this->assertInstanceOf('PhpOption\None', $some->filter(function($v) { return 0 === strlen($v); })); $this->assertSame($some, $some->filter(function($v) { return strlen($v) > 0; })); } public function testFilterNot() { $some = new Some('foo'); $this->assertInstanceOf('PhpOption\None', $some->filterNot(function($v) { return strlen($v) > 0; })); $this->assertSame($some, $some->filterNot(function($v) { return strlen($v) === 0; })); } public function testSelect() { $some = new Some('foo'); $this->assertSame($some, $some->select('foo')); $this->assertInstanceOf('PhpOption\None', $some->select('bar')); $this->assertInstanceOf('PhpOption\None', $some->select(true)); } public function testReject() { $some = new Some('foo'); $this->assertSame($some, $some->reject(null)); $this->assertSame($some, $some->reject(true)); $this->assertInstanceOf('PhpOption\None', $some->reject('foo')); } public function testFoldLeftRight() { $some = new Some(5); $this->assertSame(6, $some->foldLeft(1, function($a, $b) { $this->assertEquals(1, $a); $this->assertEquals(5, $b); return $a + $b; })); $this->assertSame(6, $some->foldRight(1, function($a, $b) { $this->assertEquals(1, $b); $this->assertEquals(5, $a); return $a + $b; })); } public function testForeach() { $some = new Some('foo'); $called = 0; $extractedValue = null; foreach ($some as $value) { $extractedValue = $value; $called++; } $this->assertEquals('foo', $extractedValue); $this->assertEquals(1, $called); } } // For the interested reader of these tests, we have gone some great lengths // to come up with a non-contrived example that might also be used in the // real-world, and not only for testing purposes :) class Repository { private $users; public function __construct(array $users = array()) { $this->users = $users; } // A fast ID lookup, probably cached, sometimes we might not need the entire user. public function getLastRegisteredUsername() { if (empty($this->users)) { return \PhpOption\None::create(); } return new Some(end($this->users)); } // Returns a user object (we will live with an array here). public function getUser($name) { if (in_array($name, $this->users, true)) { return new Some(array('name' => $name)); } return \PhpOption\None::create(); } public function getDefaultUser() { return array('name' => 'muhuhu'); } } phpoption/tests/bootstrap.php 0000604 00000000341 15224664617 0012463 0 ustar 00 <?php if ( ! is_file($autoloadFile = __DIR__.'/../vendor/autoload.php')) { echo 'Could not find "vendor/autoload.php". Did you forget to run "composer install --dev"?'.PHP_EOL; exit(1); } require_once $autoloadFile; phpoption/.gitignore 0000604 00000000042 15224664617 0010561 0 ustar 00 vendor/ phpunit.xml composer.lock phpoption/README.md 0000604 00000013137 15224664617 0010061 0 ustar 00 PHP Option Type [](http://travis-ci.org/schmittjoh/php-option) [](https://scrutinizer-ci.com/g/schmittjoh/php-option/) =============== This adds an Option type for PHP. The Option type is intended for cases where you sometimes might return a value (typically an object), and sometimes you might return no value (typically null) depending on arguments, or other runtime factors. Often times, you forget to handle the case where no value is returned. Not intentionally of course, but maybe you did not account for all possible states of the system; or maybe you indeed covered all cases, then time goes on, code is refactored, some of these your checks might become invalid, or incomplete. Suddenly, without noticing, the no value case is not handled anymore. As a result, you might sometimes get fatal PHP errors telling you that you called a method on a non-object; users might see blank pages, or worse. On one hand, the Option type forces a developer to consciously think about both cases (returning a value, or returning no value). That in itself will already make your code more robust. On the other hand, the Option type also allows the API developer to provide more concise API methods, and empowers the API user in how he consumes these methods. Installation ============ Installation is super-easy via composer ``` composer require phpoption/phpoption ``` or add it to your composer.json file. Usage ===== Using the Option Type in your API --------------------------------- ```php class MyRepository { public function findSomeEntity($criteria) { if (null !== $entity = $this->em->find(...)) { return new \PhpOption\Some($entity); } // We use a singleton, for the None case. return \PhpOption\None::create(); } } ``` If you are consuming an existing library, you can also use a shorter version which by default treats ``null`` as ``None``, and everything else as ``Some`` case: ```php class MyRepository { public function findSomeEntity($criteria) { return \PhpOption\Option::fromValue($this->em->find(...)); // or, if you want to change the none value to false for example: return \PhpOption\Option::fromValue($this->em->find(...), false); } } ``` Case 1: You always Require an Entity in Calling Code ---------------------------------------------------- ```php $entity = $repo->findSomeEntity(...)->get(); // returns entity, or throws exception ``` Case 2: Fallback to Default Value If Not Available -------------------------------------------------- ```php $entity = $repo->findSomeEntity(...)->getOrElse(new Entity()); // Or, if you want to lazily create the entity. $entity = $repo->findSomeEntity(...)->getOrCall(function() { return new Entity(); }); ``` More Examples ============= No More Boiler Plate Code ------------------------- ```php // Before if (null === $entity = $this->findSomeEntity()) { throw new NotFoundException(); } echo $entity->name; // After echo $this->findSomeEntity()->get()->name; ``` No More Control Flow Exceptions ------------------------------- ```php // Before try { $entity = $this->findSomeEntity(); } catch (NotFoundException $ex) { $entity = new Entity(); } // After $entity = $this->findSomeEntity()->getOrElse(new Entity()); ``` More Concise Null Handling -------------------------- ```php // Before $entity = $this->findSomeEntity(); if (null === $entity) { return new Entity(); } return $entity; // After return $this->findSomeEntity()->getOrElse(new Entity()); ``` Trying Multiple Alternative Options ----------------------------------- If you'd like to try multiple alternatives, the ``orElse`` method allows you to do this very elegantly: ```php return $this->findSomeEntity() ->orElse($this->findSomeOtherEntity()) ->orElse($this->createEntity()); ``` The first option which is non-empty will be returned. This is especially useful with lazy-evaluated options, see below. Lazy-Evaluated Options ---------------------- The above example has the flaw that we would need to evaluate all options when the method is called which creates unnecessary overhead if the first option is already non-empty. Fortunately, we can easily solve this by using the ``LazyOption`` class: ```php return $this->findSomeEntity() ->orElse(new LazyOption(array($this, 'findSomeOtherEntity'))) ->orElse(new LazyOption(array($this, 'createEntity'))); ``` This way, only the options that are necessary will actually be evaluated. Performance Considerations ========================== Of course, performance is important. Attached is a performance benchmark which you can run on a machine of your choosing. The overhead incurred by the Option type comes down to the time that it takes to create one object, our wrapper. Also, we need to perform one additional method call to retrieve the value from the wrapper. * Overhead: Creation of 1 Object, and 1 Method Call * Average Overhead per Invocation (some case/value returned): 0.000000761s (that is 761 nano seconds) * Average Overhead per Invocation (none case/null returned): 0.000000368s (that is 368 nano seconds) The benchmark was run under Ubuntu precise with PHP 5.4.6. As you can see the overhead is surprisingly low, almost negligible. So in conclusion, unless you plan to call a method thousands of times during a request, there is no reason to stick to the ``object|null`` return value; better give your code some options! phpoption/phpunit.xml.dist 0000604 00000001246 15224664617 0011753 0 ustar 00 <?xml version="1.0" encoding="UTF-8"?> <phpunit backupGlobals="false" backupStaticAttributes="false" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" syntaxCheck="false" bootstrap="tests/bootstrap.php" > <testsuites> <testsuite name="PhpOption Type Test Suite"> <directory>./tests/PhpOption/</directory> </testsuite> </testsuites> <groups> <exclude> <group>performance</group> </exclude> </groups> </phpunit> phpoption/.travis.yml 0000604 00000000326 15224664617 0010707 0 ustar 00 language: php php: - 5.3 - 5.4 - 5.5 - hhvm before_script: - wget http://getcomposer.org/composer.phar - php composer.phar install --dev script: - phpunit matrix: allow_failures: - php: hhvm tests/PhpOption/Tests/LazyOptionTest.php 0000604 00000014450 15224667653 0014431 0 ustar 00 <?php namespace PhpOption\Tests; use PhpOption\LazyOption; class LazyOptionTest extends \PHPUnit_Framework_TestCase { private $subject; public function setUp() { $this->subject = $this ->getMockBuilder('Subject') ->setMethods(array('execute')) ->getMock(); } public function testGetWithArgumentsAndConstructor() { $some = \PhpOption\LazyOption::create(array($this->subject, 'execute'), array('foo')); $this->subject ->expects($this->once()) ->method('execute') ->with('foo') ->will($this->returnValue(\PhpOption\Some::create('foo'))); $this->assertEquals('foo', $some->get()); $this->assertEquals('foo', $some->getOrElse(null)); $this->assertEquals('foo', $some->getOrCall('does_not_exist')); $this->assertEquals('foo', $some->getOrThrow(new \RuntimeException('does_not_exist'))); $this->assertFalse($some->isEmpty()); } public function testGetWithArgumentsAndCreate() { $some = new \PhpOption\LazyOption(array($this->subject, 'execute'), array('foo')); $this->subject ->expects($this->once()) ->method('execute') ->with('foo') ->will($this->returnValue(\PhpOption\Some::create('foo'))); $this->assertEquals('foo', $some->get()); $this->assertEquals('foo', $some->getOrElse(null)); $this->assertEquals('foo', $some->getOrCall('does_not_exist')); $this->assertEquals('foo', $some->getOrThrow(new \RuntimeException('does_not_exist'))); $this->assertFalse($some->isEmpty()); } public function testGetWithoutArgumentsAndConstructor() { $some = new \PhpOption\LazyOption(array($this->subject, 'execute')); $this->subject ->expects($this->once()) ->method('execute') ->will($this->returnValue(\PhpOption\Some::create('foo'))); $this->assertEquals('foo', $some->get()); $this->assertEquals('foo', $some->getOrElse(null)); $this->assertEquals('foo', $some->getOrCall('does_not_exist')); $this->assertEquals('foo', $some->getOrThrow(new \RuntimeException('does_not_exist'))); $this->assertFalse($some->isEmpty()); } public function testGetWithoutArgumentsAndCreate() { $option = \PhpOption\LazyOption::create(array($this->subject, 'execute')); $this->subject ->expects($this->once()) ->method('execute') ->will($this->returnValue(\PhpOption\Some::create('foo'))); $this->assertTrue($option->isDefined()); $this->assertFalse($option->isEmpty()); $this->assertEquals('foo', $option->get()); $this->assertEquals('foo', $option->getOrElse(null)); $this->assertEquals('foo', $option->getOrCall('does_not_exist')); $this->assertEquals('foo', $option->getOrThrow(new \RuntimeException('does_not_exist'))); } /** * @expectedException \RuntimeException * @expectedExceptionMessage None has no value */ public function testCallbackReturnsNull() { $option = \PhpOption\LazyOption::create(array($this->subject, 'execute')); $this->subject ->expects($this->once()) ->method('execute') ->will($this->returnValue(\PhpOption\None::create())); $this->assertFalse($option->isDefined()); $this->assertTrue($option->isEmpty()); $this->assertEquals('alt', $option->getOrElse('alt')); $this->assertEquals('alt', $option->getOrCall(function(){return 'alt';})); $option->get(); } /** * @expectedException \RuntimeException * @expectedExceptionMessage Expected instance of \PhpOption\Option */ public function testExceptionIsThrownIfCallbackReturnsNonOption() { $option = \PhpOption\LazyOption::create(array($this->subject, 'execute')); $this->subject ->expects($this->once()) ->method('execute') ->will($this->returnValue(null)); $this->assertFalse($option->isDefined()); } /** * @expectedException InvalidArgumentException * @expectedExceptionMessage Invalid callback given */ public function testInvalidCallbackAndConstructor() { new \PhpOption\LazyOption('invalidCallback'); } /** * @expectedException InvalidArgumentException * @expectedExceptionMessage Invalid callback given */ public function testInvalidCallbackAndCreate() { \PhpOption\LazyOption::create('invalidCallback'); } public function testifDefined() { $called = false; $self = $this; $this->assertNull(LazyOption::fromValue('foo')->ifDefined(function($v) use (&$called, $self) { $called = true; $self->assertEquals('foo', $v); })); $this->assertTrue($called); } public function testForAll() { $called = false; $self = $this; $this->assertInstanceOf('PhpOption\Some', LazyOption::fromValue('foo')->forAll(function($v) use (&$called, $self) { $called = true; $self->assertEquals('foo', $v); })); $this->assertTrue($called); } public function testOrElse() { $some = \PhpOption\Some::create('foo'); $lazy = \PhpOption\LazyOption::create(function() use ($some) {return $some;}); $this->assertSame($some, $lazy->orElse(\PhpOption\None::create())); $this->assertSame($some, $lazy->orElse(\PhpOption\Some::create('bar'))); } public function testFoldLeftRight() { $callback = function() { }; $option = $this->getMockForAbstractClass('PhpOption\Option'); $option->expects($this->once()) ->method('foldLeft') ->with(5, $callback) ->will($this->returnValue(6)); $lazyOption = new LazyOption(function() use ($option) { return $option; }); $this->assertSame(6, $lazyOption->foldLeft(5, $callback)); $option->expects($this->once()) ->method('foldRight') ->with(5, $callback) ->will($this->returnValue(6)); $lazyOption = new LazyOption(function() use ($option) { return $option; }); $this->assertSame(6, $lazyOption->foldRight(5, $callback)); } } tests/PhpOption/Tests/NoneTest.php 0000604 00000006025 15224667653 0013217 0 ustar 00 <?php namespace PhpOption\Tests; use PhpOption\None; class NoneTest extends \PHPUnit_Framework_TestCase { private $none; /** * @expectedException \RuntimeException */ public function testGet() { $none = \PhpOption\None::create(); $none->get(); } public function testGetOrElse() { $none = \PhpOption\None::create(); $this->assertEquals('foo', $none->getOrElse('foo')); } public function testGetOrCall() { $none = \PhpOption\None::create(); $this->assertEquals('foo', $none->getOrCall(function() { return 'foo'; })); } /** * @expectedException \RuntimeException * @expectedExceptionMessage Not Found! */ public function testGetOrThrow() { None::create()->getOrThrow(new \RuntimeException('Not Found!')); } public function testIsEmpty() { $none = \PhpOption\None::create(); $this->assertTrue($none->isEmpty()); } public function testOrElse() { $option = \PhpOption\Some::create('foo'); $this->assertSame($option, \PhpOption\None::create()->orElse($option)); } public function testifDefined() { $this->assertNull($this->none->ifDefined(function() { throw new \LogicException('Should never be called.'); })); } public function testForAll() { $this->assertSame($this->none, $this->none->forAll(function() { throw new \LogicException('Should never be called.'); })); } public function testMap() { $this->assertSame($this->none, $this->none->map(function() { throw new \LogicException('Should not be called.'); })); } public function testFlatMap() { $this->assertSame($this->none, $this->none->flatMap(function() { throw new \LogicException('Should not be called.'); })); } public function testFilter() { $this->assertSame($this->none, $this->none->filter(function() { throw new \LogicException('Should not be called.'); })); } public function testFilterNot() { $this->assertSame($this->none, $this->none->filterNot(function() { throw new \LogicException('Should not be called.'); })); } public function testSelect() { $this->assertSame($this->none, $this->none->select(null)); } public function testReject() { $this->assertSame($this->none, $this->none->reject(null)); } public function testForeach() { $none = \PhpOption\None::create(); $called = 0; foreach ($none as $value) { $called++; } $this->assertEquals(0, $called); } public function testFoldLeftRight() { $this->assertSame(1, $this->none->foldLeft(1, function() { $this->fail(); })); $this->assertSame(1, $this->none->foldRight(1, function() { $this->fail(); })); } protected function setUp() { $this->none = None::create(); } } tests/PhpOption/Tests/OptionTest.php 0000604 00000005625 15224667653 0013575 0 ustar 00 <?php namespace PhpOption\Tests; use PhpOption\None; use PhpOption\Option; use PhpOption\Some; class OptionTest extends \PHPUnit_Framework_TestCase { public function testfromValueWithDefaultNoneValue() { $this->assertInstanceOf('PhpOption\None', \PhpOption\Option::fromValue(null)); $this->assertInstanceOf('PhpOption\Some', \PhpOption\Option::fromValue('value')); } public function testFromValueWithFalseNoneValue() { $this->assertInstanceOf('PhpOption\None', \PhpOption\Option::fromValue(false, false)); $this->assertInstanceOf('PhpOption\Some', \PhpOption\Option::fromValue('value', false)); $this->assertInstanceOf('PhpOption\Some', \PhpOption\Option::fromValue(null, false)); } public function testFromArraysValue() { $this->assertEquals(None::create(), Option::fromArraysValue('foo', 'bar')); $this->assertEquals(None::create(), Option::fromArraysValue(null, 'bar')); $this->assertEquals(None::create(), Option::fromArraysValue(array('foo' => 'bar'), 'baz')); $this->assertEquals(None::create(), Option::fromArraysValue(array('foo' => null), 'foo')); $this->assertEquals(new Some('foo'), Option::fromArraysValue(array('foo' => 'foo'), 'foo')); } public function testFromReturn() { $null = function() { return null; }; $false = function() { return false; }; $some = function() { return 'foo'; }; $this->assertTrue(\PhpOption\Option::fromReturn($null)->isEmpty()); $this->assertFalse(\PhpOption\Option::fromReturn($false)->isEmpty()); $this->assertTrue(\PhpOption\Option::fromReturn($false, array(), false)->isEmpty()); $this->assertTrue(\PhpOption\Option::fromReturn($some)->isDefined()); $this->assertFalse(\PhpOption\Option::fromReturn($some, array(), 'foo')->isDefined()); } public function testOrElse() { $a = new \PhpOption\Some('a'); $b = new \PhpOption\Some('b'); $this->assertEquals('a', $a->orElse($b)->get()); } public function testOrElseWithNoneAsFirst() { $a = \PhpOption\None::create(); $b = new \PhpOption\Some('b'); $this->assertEquals('b', $a->orElse($b)->get()); } public function testOrElseWithLazyOptions() { $throws = function() { throw new \LogicException('Should never be called.'); }; $a = new \PhpOption\Some('a'); $b = new \PhpOption\LazyOption($throws); $this->assertEquals('a', $a->orElse($b)->get()); } public function testOrElseWithMultipleAlternatives() { $throws = new \PhpOption\LazyOption(function() { throw new \LogicException('Should never be called.'); }); $returns = new \PhpOption\LazyOption(function() { return new \PhpOption\Some('foo'); }); $a = \PhpOption\None::create(); $this->assertEquals('foo', $a->orElse($returns)->orElse($throws)->get()); } } tests/PhpOption/Tests/EnsureTest.php 0000604 00000003532 15224667653 0013561 0 ustar 00 <?php namespace PhpOption\Tests; use PhpOption\None; use PhpOption\Option; use PhpOption\Some; /** * Tests for Option::ensure() method * * @covers Option::ensure */ class EnsureTest extends \PHPUnit_Framework_TestCase { protected function ensure($value, $noneValue = null) { $option = Option::ensure($value, $noneValue); $this->assertInstanceOf('PhpOption\Option', $option); return $option; } public function testMixedValue() { $option = $this->ensure(1); $this->assertTrue($option->isDefined()); $this->assertSame(1, $option->get()); $this->assertFalse($this->ensure(null)->isDefined()); $this->assertFalse($this->ensure(1,1)->isDefined()); } public function testReturnValue() { $option = $this->ensure(function() { return 1; }); $this->assertTrue($option->isDefined()); $this->assertSame(1, $option->get()); $this->assertFalse($this->ensure(function() { return null; })->isDefined()); $this->assertFalse($this->ensure(function() { return 1; }, 1)->isDefined()); } public function testOptionReturnsAsSameInstance() { $option = $this->ensure(1); $this->assertSame($option, $this->ensure($option)); } public function testOptionReturnedFromClosure() { $option = $this->ensure(function() { return Some::create(1); }); $this->assertTrue($option->isDefined()); $this->assertSame(1, $option->get()); $option = $this->ensure(function() { return None::create(); }); $this->assertFalse($option->isDefined()); } public function testClosureReturnedFromClosure() { $option = $this->ensure(function() { return function() {}; }); $this->assertTrue($option->isDefined()); $this->assertInstanceOf('Closure', $option->get()); } } tests/PhpOption/Tests/PerformanceTest.php 0000604 00000004174 15224667653 0014564 0 ustar 00 <?php namespace PhpOption\Tests; /** * @group performance */ class PerformanceTest extends \PHPUnit_Framework_TestCase { private $traditionalRepo; private $phpOptionRepo; public function testSomeCase() { $traditionalTime = microtime(true); for ($i=0; $i<10000; $i++) { if (null === $rs = $this->traditionalRepo->findMaybe(true)) { $rs = new \stdClass(); } } $traditionalTime = microtime(true) - $traditionalTime; $phpOptionTime = microtime(true); for ($i=0; $i<10000; $i++) { $rs = $this->phpOptionRepo->findMaybe(true)->getOrElse(new \stdClass); } $phpOptionTime = microtime(true) - $phpOptionTime; $overheadPerInvocation = ($phpOptionTime - $traditionalTime) / 10000; printf("Overhead per invocation (some case): %.9fs\n", $overheadPerInvocation); } public function testNoneCase() { $traditionalTime = microtime(true); for ($i=0; $i<10000; $i++) { if (null === $rs = $this->traditionalRepo->findMaybe(false)) { $rs = new \stdClass(); } } $traditionalTime = microtime(true) - $traditionalTime; $phpOptionTime = microtime(true); for ($i=0; $i<10000; $i++) { $rs = $this->phpOptionRepo->findMaybe(false)->getOrElse(new \stdClass); } $phpOptionTime = microtime(true) - $phpOptionTime; $overheadPerInvocation = ($phpOptionTime - $traditionalTime) / 10000; printf("Overhead per invocation (none case): %.9fs\n", $overheadPerInvocation); } protected function setUp() { $this->traditionalRepo = new TraditionalRepo(); $this->phpOptionRepo = new PhpOptionRepo(); } } class TraditionalRepo { public function findMaybe($success) { if ($success) { return new \stdClass; } return null; } } class PhpOptionRepo { public function findMaybe($success) { if ($success) { return new \PhpOption\Some(new \stdClass); } return \PhpOption\None::create(); } } tests/PhpOption/Tests/SomeTest.php 0000604 00000012251 15224667653 0013221 0 ustar 00 <?php namespace PhpOption\Tests; use PhpOption\Some; class SomeTest extends \PHPUnit_Framework_TestCase { public function testGet() { $some = new \PhpOption\Some('foo'); $this->assertEquals('foo', $some->get()); $this->assertEquals('foo', $some->getOrElse(null)); $this->assertEquals('foo', $some->getOrCall('does_not_exist')); $this->assertEquals('foo', $some->getOrThrow(new \RuntimeException('Not found'))); $this->assertFalse($some->isEmpty()); } public function testCreate() { $some = \PhpOption\Some::create('foo'); $this->assertEquals('foo', $some->get()); $this->assertEquals('foo', $some->getOrElse(null)); $this->assertEquals('foo', $some->getOrCall('does_not_exist')); $this->assertEquals('foo', $some->getOrThrow(new \RuntimeException('Not found'))); $this->assertFalse($some->isEmpty()); } public function testOrElse() { $some = \PhpOption\Some::create('foo'); $this->assertSame($some, $some->orElse(\PhpOption\None::create())); $this->assertSame($some, $some->orElse(\PhpOption\Some::create('bar'))); } public function testifDefined() { $called = false; $self = $this; $some = new Some('foo'); $this->assertNull($some->ifDefined(function($v) use (&$called, $self) { $called = true; $self->assertEquals('foo', $v); })); $this->assertTrue($called); } public function testForAll() { $called = false; $self = $this; $some = new Some('foo'); $this->assertSame($some, $some->forAll(function($v) use (&$called, $self) { $called = true; $self->assertEquals('foo', $v); })); $this->assertTrue($called); } public function testMap() { $some = new Some('foo'); $this->assertEquals('o', $some->map(function($v) { return substr($v, 1, 1); })->get()); } public function testFlatMap() { $repo = new Repository(array('foo')); $this->assertEquals(array('name' => 'foo'), $repo->getLastRegisteredUsername() ->flatMap(array($repo, 'getUser')) ->getOrCall(array($repo, 'getDefaultUser'))); } public function testFilter() { $some = new Some('foo'); $this->assertInstanceOf('PhpOption\None', $some->filter(function($v) { return 0 === strlen($v); })); $this->assertSame($some, $some->filter(function($v) { return strlen($v) > 0; })); } public function testFilterNot() { $some = new Some('foo'); $this->assertInstanceOf('PhpOption\None', $some->filterNot(function($v) { return strlen($v) > 0; })); $this->assertSame($some, $some->filterNot(function($v) { return strlen($v) === 0; })); } public function testSelect() { $some = new Some('foo'); $this->assertSame($some, $some->select('foo')); $this->assertInstanceOf('PhpOption\None', $some->select('bar')); $this->assertInstanceOf('PhpOption\None', $some->select(true)); } public function testReject() { $some = new Some('foo'); $this->assertSame($some, $some->reject(null)); $this->assertSame($some, $some->reject(true)); $this->assertInstanceOf('PhpOption\None', $some->reject('foo')); } public function testFoldLeftRight() { $some = new Some(5); $this->assertSame(6, $some->foldLeft(1, function($a, $b) { $this->assertEquals(1, $a); $this->assertEquals(5, $b); return $a + $b; })); $this->assertSame(6, $some->foldRight(1, function($a, $b) { $this->assertEquals(1, $b); $this->assertEquals(5, $a); return $a + $b; })); } public function testForeach() { $some = new Some('foo'); $called = 0; $extractedValue = null; foreach ($some as $value) { $extractedValue = $value; $called++; } $this->assertEquals('foo', $extractedValue); $this->assertEquals(1, $called); } } // For the interested reader of these tests, we have gone some great lengths // to come up with a non-contrived example that might also be used in the // real-world, and not only for testing purposes :) class Repository { private $users; public function __construct(array $users = array()) { $this->users = $users; } // A fast ID lookup, probably cached, sometimes we might not need the entire user. public function getLastRegisteredUsername() { if (empty($this->users)) { return \PhpOption\None::create(); } return new Some(end($this->users)); } // Returns a user object (we will live with an array here). public function getUser($name) { if (in_array($name, $this->users, true)) { return new Some(array('name' => $name)); } return \PhpOption\None::create(); } public function getDefaultUser() { return array('name' => 'muhuhu'); } } tests/bootstrap.php 0000604 00000000341 15224667653 0010446 0 ustar 00 <?php if ( ! is_file($autoloadFile = __DIR__.'/../vendor/autoload.php')) { echo 'Could not find "vendor/autoload.php". Did you forget to run "composer install --dev"?'.PHP_EOL; exit(1); } require_once $autoloadFile; .gitignore 0000604 00000000042 15224667653 0006544 0 ustar 00 vendor/ phpunit.xml composer.lock LICENSE 0000604 00000026134 15224667653 0005573 0 ustar 00 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. composer.json 0000604 00000002004 15224667653 0007276 0 ustar 00 { "name": "phpoption/phpoption", "description": "Option Type for PHP", "keywords": ["php", "option", "language", "type"], "license": "Apache-2.0", "authors": [ { "name": "Johannes M. Schmitt", "email": "schmittjoh@gmail.com" }, { "name": "Graham Campbell", "email": "hello@gjcampbell.co.uk" } ], "require": { "php": "^7.0 || ^8.0" }, "require-dev": { "bamarni/composer-bin-plugin": "^1.4.1", "phpunit/phpunit": "^6.5.14 || ^7.0.20 || ^8.5.19 || ^9.5.8" }, "autoload": { "psr-4": { "PhpOption\\": "src/PhpOption/" } }, "autoload-dev": { "psr-4": { "PhpOption\\Tests\\": "tests/PhpOption/Tests/" } }, "config": { "preferred-install": "dist" }, "extra": { "branch-alias": { "dev-master": "1.8-dev" } }, "minimum-stability": "dev", "prefer-stable": true } README.md 0000604 00000013137 15224667653 0006044 0 ustar 00 PHP Option Type [](http://travis-ci.org/schmittjoh/php-option) [](https://scrutinizer-ci.com/g/schmittjoh/php-option/) =============== This adds an Option type for PHP. The Option type is intended for cases where you sometimes might return a value (typically an object), and sometimes you might return no value (typically null) depending on arguments, or other runtime factors. Often times, you forget to handle the case where no value is returned. Not intentionally of course, but maybe you did not account for all possible states of the system; or maybe you indeed covered all cases, then time goes on, code is refactored, some of these your checks might become invalid, or incomplete. Suddenly, without noticing, the no value case is not handled anymore. As a result, you might sometimes get fatal PHP errors telling you that you called a method on a non-object; users might see blank pages, or worse. On one hand, the Option type forces a developer to consciously think about both cases (returning a value, or returning no value). That in itself will already make your code more robust. On the other hand, the Option type also allows the API developer to provide more concise API methods, and empowers the API user in how he consumes these methods. Installation ============ Installation is super-easy via composer ``` composer require phpoption/phpoption ``` or add it to your composer.json file. Usage ===== Using the Option Type in your API --------------------------------- ```php class MyRepository { public function findSomeEntity($criteria) { if (null !== $entity = $this->em->find(...)) { return new \PhpOption\Some($entity); } // We use a singleton, for the None case. return \PhpOption\None::create(); } } ``` If you are consuming an existing library, you can also use a shorter version which by default treats ``null`` as ``None``, and everything else as ``Some`` case: ```php class MyRepository { public function findSomeEntity($criteria) { return \PhpOption\Option::fromValue($this->em->find(...)); // or, if you want to change the none value to false for example: return \PhpOption\Option::fromValue($this->em->find(...), false); } } ``` Case 1: You always Require an Entity in Calling Code ---------------------------------------------------- ```php $entity = $repo->findSomeEntity(...)->get(); // returns entity, or throws exception ``` Case 2: Fallback to Default Value If Not Available -------------------------------------------------- ```php $entity = $repo->findSomeEntity(...)->getOrElse(new Entity()); // Or, if you want to lazily create the entity. $entity = $repo->findSomeEntity(...)->getOrCall(function() { return new Entity(); }); ``` More Examples ============= No More Boiler Plate Code ------------------------- ```php // Before if (null === $entity = $this->findSomeEntity()) { throw new NotFoundException(); } echo $entity->name; // After echo $this->findSomeEntity()->get()->name; ``` No More Control Flow Exceptions ------------------------------- ```php // Before try { $entity = $this->findSomeEntity(); } catch (NotFoundException $ex) { $entity = new Entity(); } // After $entity = $this->findSomeEntity()->getOrElse(new Entity()); ``` More Concise Null Handling -------------------------- ```php // Before $entity = $this->findSomeEntity(); if (null === $entity) { return new Entity(); } return $entity; // After return $this->findSomeEntity()->getOrElse(new Entity()); ``` Trying Multiple Alternative Options ----------------------------------- If you'd like to try multiple alternatives, the ``orElse`` method allows you to do this very elegantly: ```php return $this->findSomeEntity() ->orElse($this->findSomeOtherEntity()) ->orElse($this->createEntity()); ``` The first option which is non-empty will be returned. This is especially useful with lazy-evaluated options, see below. Lazy-Evaluated Options ---------------------- The above example has the flaw that we would need to evaluate all options when the method is called which creates unnecessary overhead if the first option is already non-empty. Fortunately, we can easily solve this by using the ``LazyOption`` class: ```php return $this->findSomeEntity() ->orElse(new LazyOption(array($this, 'findSomeOtherEntity'))) ->orElse(new LazyOption(array($this, 'createEntity'))); ``` This way, only the options that are necessary will actually be evaluated. Performance Considerations ========================== Of course, performance is important. Attached is a performance benchmark which you can run on a machine of your choosing. The overhead incurred by the Option type comes down to the time that it takes to create one object, our wrapper. Also, we need to perform one additional method call to retrieve the value from the wrapper. * Overhead: Creation of 1 Object, and 1 Method Call * Average Overhead per Invocation (some case/value returned): 0.000000761s (that is 761 nano seconds) * Average Overhead per Invocation (none case/null returned): 0.000000368s (that is 368 nano seconds) The benchmark was run under Ubuntu precise with PHP 5.4.6. As you can see the overhead is surprisingly low, almost negligible. So in conclusion, unless you plan to call a method thousands of times during a request, there is no reason to stick to the ``object|null`` return value; better give your code some options! phpunit.xml.dist 0000604 00000001246 15224667653 0007736 0 ustar 00 <?xml version="1.0" encoding="UTF-8"?> <phpunit backupGlobals="false" backupStaticAttributes="false" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" syntaxCheck="false" bootstrap="tests/bootstrap.php" > <testsuites> <testsuite name="PhpOption Type Test Suite"> <directory>./tests/PhpOption/</directory> </testsuite> </testsuites> <groups> <exclude> <group>performance</group> </exclude> </groups> </phpunit> .travis.yml 0000604 00000000326 15224667653 0006672 0 ustar 00 language: php php: - 5.3 - 5.4 - 5.5 - hhvm before_script: - wget http://getcomposer.org/composer.phar - php composer.phar install --dev script: - phpunit matrix: allow_failures: - php: hhvm src/PhpOption/LazyOption.php 0000604 00000007645 15224667653 0012124 0 ustar 00 <?php /* * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace PhpOption; /** * @template T * * @extends Option<T> */ final class LazyOption extends Option { /** @var callable(mixed...):(Option<T>) */ private $callback; /** @var array<int, mixed> */ private $arguments; /** @var Option<T>|null */ private $option; /** * @template S * @param callable(mixed...):(Option<S>) $callback * @param array<int, mixed> $arguments * * @return LazyOption<S> */ public static function create($callback, array $arguments = []): self { return new self($callback, $arguments); } /** * @param callable(mixed...):(Option<T>) $callback * @param array<int, mixed> $arguments */ public function __construct($callback, array $arguments = []) { if (!is_callable($callback)) { throw new \InvalidArgumentException('Invalid callback given'); } $this->callback = $callback; $this->arguments = $arguments; } public function isDefined(): bool { return $this->option()->isDefined(); } public function isEmpty(): bool { return $this->option()->isEmpty(); } public function get() { return $this->option()->get(); } public function getOrElse($default) { return $this->option()->getOrElse($default); } public function getOrCall($callable) { return $this->option()->getOrCall($callable); } public function getOrThrow(\Exception $ex) { return $this->option()->getOrThrow($ex); } public function orElse(Option $else) { return $this->option()->orElse($else); } public function ifDefined($callable) { $this->option()->forAll($callable); } public function forAll($callable) { return $this->option()->forAll($callable); } public function map($callable) { return $this->option()->map($callable); } public function flatMap($callable) { return $this->option()->flatMap($callable); } public function filter($callable) { return $this->option()->filter($callable); } public function filterNot($callable) { return $this->option()->filterNot($callable); } public function select($value) { return $this->option()->select($value); } public function reject($value) { return $this->option()->reject($value); } public function getIterator() { return $this->option()->getIterator(); } public function foldLeft($initialValue, $callable) { return $this->option()->foldLeft($initialValue, $callable); } public function foldRight($initialValue, $callable) { return $this->option()->foldRight($initialValue, $callable); } /** * @return Option<T> */ private function option(): Option { if (null === $this->option) { /** @var mixed */ $option = call_user_func_array($this->callback, $this->arguments); if ($option instanceof Option) { $this->option = $option; } else { throw new \RuntimeException(sprintf('Expected instance of %s', Option::class)); } } return $this->option; } } src/PhpOption/Option.php 0000604 00000032034 15224667653 0011252 0 ustar 00 <?php /* * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace PhpOption; use ArrayAccess; use IteratorAggregate; /** * @template T * * @implements IteratorAggregate<T> */ abstract class Option implements IteratorAggregate { /** * Creates an option given a return value. * * This is intended for consuming existing APIs and allows you to easily * convert them to an option. By default, we treat ``null`` as the None * case, and everything else as Some. * * @template S * * @param S $value The actual return value. * @param S $noneValue The value which should be considered "None"; null by * default. * * @return Option<S> */ public static function fromValue($value, $noneValue = null) { if ($value === $noneValue) { return None::create(); } return new Some($value); } /** * Creates an option from an array's value. * * If the key does not exist in the array, the array is not actually an * array, or the array's value at the given key is null, None is returned. * Otherwise, Some is returned wrapping the value at the given key. * * @template S * * @param array<string|int,S>|ArrayAccess<string|int,S>|null $array A potential array or \ArrayAccess value. * @param string $key The key to check. * * @return Option<S> */ public static function fromArraysValue($array, $key) { if (!(is_array($array) || $array instanceof ArrayAccess) || !isset($array[$key])) { return None::create(); } return new Some($array[$key]); } /** * Creates a lazy-option with the given callback. * * This is also a helper constructor for lazy-consuming existing APIs where * the return value is not yet an option. By default, we treat ``null`` as * None case, and everything else as Some. * * @template S * * @param callable $callback The callback to evaluate. * @param array $arguments The arguments for the callback. * @param S $noneValue The value which should be considered "None"; * null by default. * * @return LazyOption<S> */ public static function fromReturn($callback, array $arguments = [], $noneValue = null) { return new LazyOption(static function () use ($callback, $arguments, $noneValue) { /** @var mixed */ $return = call_user_func_array($callback, $arguments); if ($return === $noneValue) { return None::create(); } return new Some($return); }); } /** * Option factory, which creates new option based on passed value. * * If value is already an option, it simply returns. If value is callable, * LazyOption with passed callback created and returned. If Option * returned from callback, it returns directly. On other case value passed * to Option::fromValue() method. * * @template S * * @param Option<S>|callable|S $value * @param S $noneValue Used when $value is mixed or * callable, for None-check. * * @return Option<S>|LazyOption<S> */ public static function ensure($value, $noneValue = null) { if ($value instanceof self) { return $value; } elseif (is_callable($value)) { return new LazyOption(static function () use ($value, $noneValue) { /** @var mixed */ $return = $value(); if ($return instanceof self) { return $return; } else { return self::fromValue($return, $noneValue); } }); } else { return self::fromValue($value, $noneValue); } } /** * Lift a function so that it accepts Option as parameters. * * We return a new closure that wraps the original callback. If any of the * parameters passed to the lifted function is empty, the function will * return a value of None. Otherwise, we will pass all parameters to the * original callback and return the value inside a new Option, unless an * Option is returned from the function, in which case, we use that. * * @template S * * @param callable $callback * @param mixed $noneValue * * @return callable */ public static function lift($callback, $noneValue = null) { return static function () use ($callback, $noneValue) { /** @var array<int, mixed> */ $args = func_get_args(); $reduced_args = array_reduce( $args, /** @param bool $status */ static function ($status, self $o) { return $o->isEmpty() ? true : $status; }, false ); // if at least one parameter is empty, return None if ($reduced_args) { return None::create(); } $args = array_map( /** @return T */ static function (self $o) { // it is safe to do so because the fold above checked // that all arguments are of type Some /** @var T */ return $o->get(); }, $args ); return self::ensure(call_user_func_array($callback, $args), $noneValue); }; } /** * Returns the value if available, or throws an exception otherwise. * * @throws \RuntimeException If value is not available. * * @return T */ abstract public function get(); /** * Returns the value if available, or the default value if not. * * @template S * * @param S $default * * @return T|S */ abstract public function getOrElse($default); /** * Returns the value if available, or the results of the callable. * * This is preferable over ``getOrElse`` if the computation of the default * value is expensive. * * @template S * * @param callable():S $callable * * @return T|S */ abstract public function getOrCall($callable); /** * Returns the value if available, or throws the passed exception. * * @param \Exception $ex * * @return T */ abstract public function getOrThrow(\Exception $ex); /** * Returns true if no value is available, false otherwise. * * @return bool */ abstract public function isEmpty(); /** * Returns true if a value is available, false otherwise. * * @return bool */ abstract public function isDefined(); /** * Returns this option if non-empty, or the passed option otherwise. * * This can be used to try multiple alternatives, and is especially useful * with lazy evaluating options: * * ```php * $repo->findSomething() * ->orElse(new LazyOption(array($repo, 'findSomethingElse'))) * ->orElse(new LazyOption(array($repo, 'createSomething'))); * ``` * * @param Option<T> $else * * @return Option<T> */ abstract public function orElse(self $else); /** * This is similar to map() below except that the return value has no meaning; * the passed callable is simply executed if the option is non-empty, and * ignored if the option is empty. * * In all cases, the return value of the callable is discarded. * * ```php * $comment->getMaybeFile()->ifDefined(function($file) { * // Do something with $file here. * }); * ``` * * If you're looking for something like ``ifEmpty``, you can use ``getOrCall`` * and ``getOrElse`` in these cases. * * @deprecated Use forAll() instead. * * @param callable(T):mixed $callable * * @return void */ abstract public function ifDefined($callable); /** * This is similar to map() except that the return value of the callable has no meaning. * * The passed callable is simply executed if the option is non-empty, and ignored if the * option is empty. This method is preferred for callables with side-effects, while map() * is intended for callables without side-effects. * * @param callable(T):mixed $callable * * @return Option<T> */ abstract public function forAll($callable); /** * Applies the callable to the value of the option if it is non-empty, * and returns the return value of the callable wrapped in Some(). * * If the option is empty, then the callable is not applied. * * ```php * (new Some("foo"))->map('strtoupper')->get(); // "FOO" * ``` * * @template S * * @param callable(T):S $callable * * @return Option<S> */ abstract public function map($callable); /** * Applies the callable to the value of the option if it is non-empty, and * returns the return value of the callable directly. * * In contrast to ``map``, the return value of the callable is expected to * be an Option itself; it is not automatically wrapped in Some(). * * @template S * * @param callable(T):Option<S> $callable must return an Option * * @return Option<S> */ abstract public function flatMap($callable); /** * If the option is empty, it is returned immediately without applying the callable. * * If the option is non-empty, the callable is applied, and if it returns true, * the option itself is returned; otherwise, None is returned. * * @param callable(T):bool $callable * * @return Option<T> */ abstract public function filter($callable); /** * If the option is empty, it is returned immediately without applying the callable. * * If the option is non-empty, the callable is applied, and if it returns false, * the option itself is returned; otherwise, None is returned. * * @param callable(T):bool $callable * * @return Option<T> */ abstract public function filterNot($callable); /** * If the option is empty, it is returned immediately. * * If the option is non-empty, and its value does not equal the passed value * (via a shallow comparison ===), then None is returned. Otherwise, the * Option is returned. * * In other words, this will filter all but the passed value. * * @param T $value * * @return Option<T> */ abstract public function select($value); /** * If the option is empty, it is returned immediately. * * If the option is non-empty, and its value does equal the passed value (via * a shallow comparison ===), then None is returned; otherwise, the Option is * returned. * * In other words, this will let all values through except the passed value. * * @param T $value * * @return Option<T> */ abstract public function reject($value); /** * Binary operator for the initial value and the option's value. * * If empty, the initial value is returned. If non-empty, the callable * receives the initial value and the option's value as arguments. * * ```php * * $some = new Some(5); * $none = None::create(); * $result = $some->foldLeft(1, function($a, $b) { return $a + $b; }); // int(6) * $result = $none->foldLeft(1, function($a, $b) { return $a + $b; }); // int(1) * * // This can be used instead of something like the following: * $option = Option::fromValue($integerOrNull); * $result = 1; * if ( ! $option->isEmpty()) { * $result += $option->get(); * } * ``` * * @template S * * @param S $initialValue * @param callable(S, T):S $callable * * @return S */ abstract public function foldLeft($initialValue, $callable); /** * foldLeft() but with reversed arguments for the callable. * * @template S * * @param S $initialValue * @param callable(T, S):S $callable * * @return S */ abstract public function foldRight($initialValue, $callable); } src/PhpOption/None.php 0000604 00000004722 15224667653 0010704 0 ustar 00 <?php /* * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace PhpOption; use EmptyIterator; /** * @extends Option<mixed> */ final class None extends Option { /** @var None|null */ private static $instance; /** * @return None */ public static function create(): self { if (null === self::$instance) { self::$instance = new self(); } return self::$instance; } public function get() { throw new \RuntimeException('None has no value.'); } public function getOrCall($callable) { return $callable(); } public function getOrElse($default) { return $default; } public function getOrThrow(\Exception $ex) { throw $ex; } public function isEmpty(): bool { return true; } public function isDefined(): bool { return false; } public function orElse(Option $else) { return $else; } public function ifDefined($callable) { // Just do nothing in that case. } public function forAll($callable) { return $this; } public function map($callable) { return $this; } public function flatMap($callable) { return $this; } public function filter($callable) { return $this; } public function filterNot($callable) { return $this; } public function select($value) { return $this; } public function reject($value) { return $this; } public function getIterator(): EmptyIterator { return new EmptyIterator(); } public function foldLeft($initialValue, $callable) { return $initialValue; } public function foldRight($initialValue, $callable) { return $initialValue; } private function __construct() { } } src/PhpOption/Some.php 0000604 00000006302 15224667653 0010704 0 ustar 00 <?php /* * Copyright 2012 Johannes M. Schmitt <schmittjoh@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace PhpOption; use ArrayIterator; /** * @template T * * @extends Option<T> */ final class Some extends Option { /** @var T */ private $value; /** * @param T $value */ public function __construct($value) { $this->value = $value; } /** * @template U * * @param U $value * * @return Some<U> */ public static function create($value): self { return new self($value); } public function isDefined(): bool { return true; } public function isEmpty(): bool { return false; } public function get() { return $this->value; } public function getOrElse($default) { return $this->value; } public function getOrCall($callable) { return $this->value; } public function getOrThrow(\Exception $ex) { return $this->value; } public function orElse(Option $else) { return $this; } public function ifDefined($callable) { $this->forAll($callable); } public function forAll($callable) { $callable($this->value); return $this; } public function map($callable) { return new self($callable($this->value)); } public function flatMap($callable) { /** @var mixed */ $rs = $callable($this->value); if (!$rs instanceof Option) { throw new \RuntimeException('Callables passed to flatMap() must return an Option. Maybe you should use map() instead?'); } return $rs; } public function filter($callable) { if (true === $callable($this->value)) { return $this; } return None::create(); } public function filterNot($callable) { if (false === $callable($this->value)) { return $this; } return None::create(); } public function select($value) { if ($this->value === $value) { return $this; } return None::create(); } public function reject($value) { if ($this->value === $value) { return None::create(); } return $this; } public function getIterator(): ArrayIterator { return new ArrayIterator([$this->value]); } public function foldLeft($initialValue, $callable) { return $callable($initialValue, $this->value); } public function foldRight($initialValue, $callable) { return $callable($this->value, $initialValue); } } Makefile 0000604 00000002647 15224677527 0006232 0 ustar 00 install: @docker run -it -w /data -v ${PWD}:/data:delegated -v ~/.composer:/root/.composer:delegated --entrypoint composer --rm registry.gitlab.com/grahamcampbell/php:7.4-base update @docker run -it -w /data -v ${PWD}:/data:delegated -v ~/.composer:/root/.composer:delegated --entrypoint composer --rm registry.gitlab.com/grahamcampbell/php:7.4-base bin all update phpunit: @rm -f bootstrap/cache/*.php && docker run -it -w /data -v ${PWD}:/data:delegated --entrypoint vendor/bin/phpunit --rm registry.gitlab.com/grahamcampbell/php:7.4-cli phpstan-analyze-src: @docker run -it -w /data -v ${PWD}:/data:delegated --entrypoint vendor/bin/phpstan --rm registry.gitlab.com/grahamcampbell/php:7.4-cli analyze src -c phpstan.src.neon.dist phpstan-analyze-tests: @docker run -it -w /data -v ${PWD}:/data:delegated --entrypoint vendor/bin/phpstan --rm registry.gitlab.com/grahamcampbell/php:7.4-cli analyze tests -c phpstan.tests.neon.dist psalm-analyze: @docker run -it -w /data -v ${PWD}:/data:delegated --entrypoint vendor/bin/psalm.phar --rm registry.gitlab.com/grahamcampbell/php:7.4-cli psalm-show-info: @docker run -it -w /data -v ${PWD}:/data:delegated --entrypoint vendor/bin/psalm .phar--rm registry.gitlab.com/grahamcampbell/php:7.4-cli --show-info=true test: phpunit phpstan-analyze-src phpstan-analyze-tests psalm-analyze clean: @rm -rf .phpunit.result.cache composer.lock vendor vendor-bin/*/composer.lock vendor-bin/*/vendor