├── LICENSE ├── composer.json └── src └── PhpOption ├── LazyOption.php ├── None.php ├── Option.php └── Some.php /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "phpoption/phpoption", 3 | "description": "Option Type for PHP", 4 | "keywords": ["php", "option", "language", "type"], 5 | "license": "Apache-2.0", 6 | "authors": [ 7 | { 8 | "name": "Johannes M. Schmitt", 9 | "email": "schmittjoh@gmail.com", 10 | "homepage": "https://github.com/schmittjoh" 11 | }, 12 | { 13 | "name": "Graham Campbell", 14 | "email": "hello@gjcampbell.co.uk", 15 | "homepage": "https://github.com/GrahamCampbell" 16 | } 17 | ], 18 | "require": { 19 | "php": "^7.2.5 || ^8.0" 20 | }, 21 | "require-dev": { 22 | "bamarni/composer-bin-plugin": "^1.8.2", 23 | "phpunit/phpunit": "^8.5.39 || ^9.6.20 || ^10.5.28" 24 | }, 25 | "autoload": { 26 | "psr-4": { 27 | "PhpOption\\": "src/PhpOption/" 28 | } 29 | }, 30 | "autoload-dev": { 31 | "psr-4": { 32 | "PhpOption\\Tests\\": "tests/PhpOption/Tests/" 33 | } 34 | }, 35 | "config": { 36 | "allow-plugins": { 37 | "bamarni/composer-bin-plugin": true 38 | }, 39 | "preferred-install": "dist" 40 | }, 41 | "extra": { 42 | "bamarni-bin": { 43 | "bin-links": true, 44 | "forward-command": false 45 | }, 46 | "branch-alias": { 47 | "dev-master": "1.9-dev" 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/PhpOption/LazyOption.php: -------------------------------------------------------------------------------- 1 | 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | namespace PhpOption; 20 | 21 | use Traversable; 22 | 23 | /** 24 | * @template T 25 | * 26 | * @extends Option 27 | */ 28 | final class LazyOption extends Option 29 | { 30 | /** @var callable(mixed...):(Option) */ 31 | private $callback; 32 | 33 | /** @var array */ 34 | private $arguments; 35 | 36 | /** @var Option|null */ 37 | private $option; 38 | 39 | /** 40 | * @template S 41 | * @param callable(mixed...):(Option) $callback 42 | * @param array $arguments 43 | * 44 | * @return LazyOption 45 | */ 46 | public static function create($callback, array $arguments = []): self 47 | { 48 | return new self($callback, $arguments); 49 | } 50 | 51 | /** 52 | * @param callable(mixed...):(Option) $callback 53 | * @param array $arguments 54 | */ 55 | public function __construct($callback, array $arguments = []) 56 | { 57 | if (!is_callable($callback)) { 58 | throw new \InvalidArgumentException('Invalid callback given'); 59 | } 60 | 61 | $this->callback = $callback; 62 | $this->arguments = $arguments; 63 | } 64 | 65 | public function isDefined(): bool 66 | { 67 | return $this->option()->isDefined(); 68 | } 69 | 70 | public function isEmpty(): bool 71 | { 72 | return $this->option()->isEmpty(); 73 | } 74 | 75 | public function get() 76 | { 77 | return $this->option()->get(); 78 | } 79 | 80 | public function getOrElse($default) 81 | { 82 | return $this->option()->getOrElse($default); 83 | } 84 | 85 | public function getOrCall($callable) 86 | { 87 | return $this->option()->getOrCall($callable); 88 | } 89 | 90 | public function getOrThrow(\Exception $ex) 91 | { 92 | return $this->option()->getOrThrow($ex); 93 | } 94 | 95 | public function orElse(Option $else) 96 | { 97 | return $this->option()->orElse($else); 98 | } 99 | 100 | public function ifDefined($callable) 101 | { 102 | $this->option()->forAll($callable); 103 | } 104 | 105 | public function forAll($callable) 106 | { 107 | return $this->option()->forAll($callable); 108 | } 109 | 110 | public function map($callable) 111 | { 112 | return $this->option()->map($callable); 113 | } 114 | 115 | public function flatMap($callable) 116 | { 117 | return $this->option()->flatMap($callable); 118 | } 119 | 120 | public function filter($callable) 121 | { 122 | return $this->option()->filter($callable); 123 | } 124 | 125 | public function filterNot($callable) 126 | { 127 | return $this->option()->filterNot($callable); 128 | } 129 | 130 | public function select($value) 131 | { 132 | return $this->option()->select($value); 133 | } 134 | 135 | public function reject($value) 136 | { 137 | return $this->option()->reject($value); 138 | } 139 | 140 | /** 141 | * @return Traversable 142 | */ 143 | public function getIterator(): Traversable 144 | { 145 | return $this->option()->getIterator(); 146 | } 147 | 148 | public function foldLeft($initialValue, $callable) 149 | { 150 | return $this->option()->foldLeft($initialValue, $callable); 151 | } 152 | 153 | public function foldRight($initialValue, $callable) 154 | { 155 | return $this->option()->foldRight($initialValue, $callable); 156 | } 157 | 158 | /** 159 | * @return Option 160 | */ 161 | private function option(): Option 162 | { 163 | if (null === $this->option) { 164 | /** @var mixed */ 165 | $option = call_user_func_array($this->callback, $this->arguments); 166 | if ($option instanceof Option) { 167 | $this->option = $option; 168 | } else { 169 | throw new \RuntimeException(sprintf('Expected instance of %s', Option::class)); 170 | } 171 | } 172 | 173 | return $this->option; 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /src/PhpOption/None.php: -------------------------------------------------------------------------------- 1 | 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | namespace PhpOption; 20 | 21 | use EmptyIterator; 22 | 23 | /** 24 | * @extends Option 25 | */ 26 | final class None extends Option 27 | { 28 | /** @var None|null */ 29 | private static $instance; 30 | 31 | /** 32 | * @return None 33 | */ 34 | public static function create(): self 35 | { 36 | if (null === self::$instance) { 37 | self::$instance = new self(); 38 | } 39 | 40 | return self::$instance; 41 | } 42 | 43 | public function get() 44 | { 45 | throw new \RuntimeException('None has no value.'); 46 | } 47 | 48 | public function getOrCall($callable) 49 | { 50 | return $callable(); 51 | } 52 | 53 | public function getOrElse($default) 54 | { 55 | return $default; 56 | } 57 | 58 | public function getOrThrow(\Exception $ex) 59 | { 60 | throw $ex; 61 | } 62 | 63 | public function isEmpty(): bool 64 | { 65 | return true; 66 | } 67 | 68 | public function isDefined(): bool 69 | { 70 | return false; 71 | } 72 | 73 | public function orElse(Option $else) 74 | { 75 | return $else; 76 | } 77 | 78 | public function ifDefined($callable) 79 | { 80 | // Just do nothing in that case. 81 | } 82 | 83 | public function forAll($callable) 84 | { 85 | return $this; 86 | } 87 | 88 | public function map($callable) 89 | { 90 | return $this; 91 | } 92 | 93 | public function flatMap($callable) 94 | { 95 | return $this; 96 | } 97 | 98 | public function filter($callable) 99 | { 100 | return $this; 101 | } 102 | 103 | public function filterNot($callable) 104 | { 105 | return $this; 106 | } 107 | 108 | public function select($value) 109 | { 110 | return $this; 111 | } 112 | 113 | public function reject($value) 114 | { 115 | return $this; 116 | } 117 | 118 | public function getIterator(): EmptyIterator 119 | { 120 | return new EmptyIterator(); 121 | } 122 | 123 | public function foldLeft($initialValue, $callable) 124 | { 125 | return $initialValue; 126 | } 127 | 128 | public function foldRight($initialValue, $callable) 129 | { 130 | return $initialValue; 131 | } 132 | 133 | private function __construct() 134 | { 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/PhpOption/Option.php: -------------------------------------------------------------------------------- 1 | 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | namespace PhpOption; 20 | 21 | use ArrayAccess; 22 | use IteratorAggregate; 23 | 24 | /** 25 | * @template T 26 | * 27 | * @implements IteratorAggregate 28 | */ 29 | abstract class Option implements IteratorAggregate 30 | { 31 | /** 32 | * Creates an option given a return value. 33 | * 34 | * This is intended for consuming existing APIs and allows you to easily 35 | * convert them to an option. By default, we treat ``null`` as the None 36 | * case, and everything else as Some. 37 | * 38 | * @template S 39 | * 40 | * @param S $value The actual return value. 41 | * @param S $noneValue The value which should be considered "None"; null by 42 | * default. 43 | * 44 | * @return Option 45 | */ 46 | public static function fromValue($value, $noneValue = null) 47 | { 48 | if ($value === $noneValue) { 49 | return None::create(); 50 | } 51 | 52 | return new Some($value); 53 | } 54 | 55 | /** 56 | * Creates an option from an array's value. 57 | * 58 | * If the key does not exist in the array, the array is not actually an 59 | * array, or the array's value at the given key is null, None is returned. 60 | * Otherwise, Some is returned wrapping the value at the given key. 61 | * 62 | * @template S 63 | * 64 | * @param array|ArrayAccess|null $array A potential array or \ArrayAccess value. 65 | * @param string|int|null $key The key to check. 66 | * 67 | * @return Option 68 | */ 69 | public static function fromArraysValue($array, $key) 70 | { 71 | if ($key === null || !(is_array($array) || $array instanceof ArrayAccess) || !isset($array[$key])) { 72 | return None::create(); 73 | } 74 | 75 | return new Some($array[$key]); 76 | } 77 | 78 | /** 79 | * Creates a lazy-option with the given callback. 80 | * 81 | * This is also a helper constructor for lazy-consuming existing APIs where 82 | * the return value is not yet an option. By default, we treat ``null`` as 83 | * None case, and everything else as Some. 84 | * 85 | * @template S 86 | * 87 | * @param callable $callback The callback to evaluate. 88 | * @param array $arguments The arguments for the callback. 89 | * @param S $noneValue The value which should be considered "None"; 90 | * null by default. 91 | * 92 | * @return LazyOption 93 | */ 94 | public static function fromReturn($callback, array $arguments = [], $noneValue = null) 95 | { 96 | return new LazyOption(static function () use ($callback, $arguments, $noneValue) { 97 | /** @var mixed */ 98 | $return = call_user_func_array($callback, $arguments); 99 | 100 | if ($return === $noneValue) { 101 | return None::create(); 102 | } 103 | 104 | return new Some($return); 105 | }); 106 | } 107 | 108 | /** 109 | * Option factory, which creates new option based on passed value. 110 | * 111 | * If value is already an option, it simply returns. If value is callable, 112 | * LazyOption with passed callback created and returned. If Option 113 | * returned from callback, it returns directly. On other case value passed 114 | * to Option::fromValue() method. 115 | * 116 | * @template S 117 | * 118 | * @param Option|callable|S $value 119 | * @param S $noneValue Used when $value is mixed or 120 | * callable, for None-check. 121 | * 122 | * @return Option|LazyOption 123 | */ 124 | public static function ensure($value, $noneValue = null) 125 | { 126 | if ($value instanceof self) { 127 | return $value; 128 | } elseif (is_callable($value)) { 129 | return new LazyOption(static function () use ($value, $noneValue) { 130 | /** @var mixed */ 131 | $return = $value(); 132 | 133 | if ($return instanceof self) { 134 | return $return; 135 | } else { 136 | return self::fromValue($return, $noneValue); 137 | } 138 | }); 139 | } else { 140 | return self::fromValue($value, $noneValue); 141 | } 142 | } 143 | 144 | /** 145 | * Lift a function so that it accepts Option as parameters. 146 | * 147 | * We return a new closure that wraps the original callback. If any of the 148 | * parameters passed to the lifted function is empty, the function will 149 | * return a value of None. Otherwise, we will pass all parameters to the 150 | * original callback and return the value inside a new Option, unless an 151 | * Option is returned from the function, in which case, we use that. 152 | * 153 | * @template S 154 | * 155 | * @param callable $callback 156 | * @param mixed $noneValue 157 | * 158 | * @return callable 159 | */ 160 | public static function lift($callback, $noneValue = null) 161 | { 162 | return static function () use ($callback, $noneValue) { 163 | /** @var array */ 164 | $args = func_get_args(); 165 | 166 | $reduced_args = array_reduce( 167 | $args, 168 | /** @param bool $status */ 169 | static function ($status, self $o) { 170 | return $o->isEmpty() ? true : $status; 171 | }, 172 | false 173 | ); 174 | // if at least one parameter is empty, return None 175 | if ($reduced_args) { 176 | return None::create(); 177 | } 178 | 179 | $args = array_map( 180 | /** @return T */ 181 | static function (self $o) { 182 | // it is safe to do so because the fold above checked 183 | // that all arguments are of type Some 184 | /** @var T */ 185 | return $o->get(); 186 | }, 187 | $args 188 | ); 189 | 190 | return self::ensure(call_user_func_array($callback, $args), $noneValue); 191 | }; 192 | } 193 | 194 | /** 195 | * Returns the value if available, or throws an exception otherwise. 196 | * 197 | * @throws \RuntimeException If value is not available. 198 | * 199 | * @return T 200 | */ 201 | abstract public function get(); 202 | 203 | /** 204 | * Returns the value if available, or the default value if not. 205 | * 206 | * @template S 207 | * 208 | * @param S $default 209 | * 210 | * @return T|S 211 | */ 212 | abstract public function getOrElse($default); 213 | 214 | /** 215 | * Returns the value if available, or the results of the callable. 216 | * 217 | * This is preferable over ``getOrElse`` if the computation of the default 218 | * value is expensive. 219 | * 220 | * @template S 221 | * 222 | * @param callable():S $callable 223 | * 224 | * @return T|S 225 | */ 226 | abstract public function getOrCall($callable); 227 | 228 | /** 229 | * Returns the value if available, or throws the passed exception. 230 | * 231 | * @param \Exception $ex 232 | * 233 | * @return T 234 | */ 235 | abstract public function getOrThrow(\Exception $ex); 236 | 237 | /** 238 | * Returns true if no value is available, false otherwise. 239 | * 240 | * @return bool 241 | */ 242 | abstract public function isEmpty(); 243 | 244 | /** 245 | * Returns true if a value is available, false otherwise. 246 | * 247 | * @return bool 248 | */ 249 | abstract public function isDefined(); 250 | 251 | /** 252 | * Returns this option if non-empty, or the passed option otherwise. 253 | * 254 | * This can be used to try multiple alternatives, and is especially useful 255 | * with lazy evaluating options: 256 | * 257 | * ```php 258 | * $repo->findSomething() 259 | * ->orElse(new LazyOption(array($repo, 'findSomethingElse'))) 260 | * ->orElse(new LazyOption(array($repo, 'createSomething'))); 261 | * ``` 262 | * 263 | * @param Option $else 264 | * 265 | * @return Option 266 | */ 267 | abstract public function orElse(self $else); 268 | 269 | /** 270 | * This is similar to map() below except that the return value has no meaning; 271 | * the passed callable is simply executed if the option is non-empty, and 272 | * ignored if the option is empty. 273 | * 274 | * In all cases, the return value of the callable is discarded. 275 | * 276 | * ```php 277 | * $comment->getMaybeFile()->ifDefined(function($file) { 278 | * // Do something with $file here. 279 | * }); 280 | * ``` 281 | * 282 | * If you're looking for something like ``ifEmpty``, you can use ``getOrCall`` 283 | * and ``getOrElse`` in these cases. 284 | * 285 | * @deprecated Use forAll() instead. 286 | * 287 | * @param callable(T):mixed $callable 288 | * 289 | * @return void 290 | */ 291 | abstract public function ifDefined($callable); 292 | 293 | /** 294 | * This is similar to map() except that the return value of the callable has no meaning. 295 | * 296 | * The passed callable is simply executed if the option is non-empty, and ignored if the 297 | * option is empty. This method is preferred for callables with side-effects, while map() 298 | * is intended for callables without side-effects. 299 | * 300 | * @param callable(T):mixed $callable 301 | * 302 | * @return Option 303 | */ 304 | abstract public function forAll($callable); 305 | 306 | /** 307 | * Applies the callable to the value of the option if it is non-empty, 308 | * and returns the return value of the callable wrapped in Some(). 309 | * 310 | * If the option is empty, then the callable is not applied. 311 | * 312 | * ```php 313 | * (new Some("foo"))->map('strtoupper')->get(); // "FOO" 314 | * ``` 315 | * 316 | * @template S 317 | * 318 | * @param callable(T):S $callable 319 | * 320 | * @return Option 321 | */ 322 | abstract public function map($callable); 323 | 324 | /** 325 | * Applies the callable to the value of the option if it is non-empty, and 326 | * returns the return value of the callable directly. 327 | * 328 | * In contrast to ``map``, the return value of the callable is expected to 329 | * be an Option itself; it is not automatically wrapped in Some(). 330 | * 331 | * @template S 332 | * 333 | * @param callable(T):Option $callable must return an Option 334 | * 335 | * @return Option 336 | */ 337 | abstract public function flatMap($callable); 338 | 339 | /** 340 | * If the option is empty, it is returned immediately without applying the callable. 341 | * 342 | * If the option is non-empty, the callable is applied, and if it returns true, 343 | * the option itself is returned; otherwise, None is returned. 344 | * 345 | * @param callable(T):bool $callable 346 | * 347 | * @return Option 348 | */ 349 | abstract public function filter($callable); 350 | 351 | /** 352 | * If the option is empty, it is returned immediately without applying the callable. 353 | * 354 | * If the option is non-empty, the callable is applied, and if it returns false, 355 | * the option itself is returned; otherwise, None is returned. 356 | * 357 | * @param callable(T):bool $callable 358 | * 359 | * @return Option 360 | */ 361 | abstract public function filterNot($callable); 362 | 363 | /** 364 | * If the option is empty, it is returned immediately. 365 | * 366 | * If the option is non-empty, and its value does not equal the passed value 367 | * (via a shallow comparison ===), then None is returned. Otherwise, the 368 | * Option is returned. 369 | * 370 | * In other words, this will filter all but the passed value. 371 | * 372 | * @param T $value 373 | * 374 | * @return Option 375 | */ 376 | abstract public function select($value); 377 | 378 | /** 379 | * If the option is empty, it is returned immediately. 380 | * 381 | * If the option is non-empty, and its value does equal the passed value (via 382 | * a shallow comparison ===), then None is returned; otherwise, the Option is 383 | * returned. 384 | * 385 | * In other words, this will let all values through except the passed value. 386 | * 387 | * @param T $value 388 | * 389 | * @return Option 390 | */ 391 | abstract public function reject($value); 392 | 393 | /** 394 | * Binary operator for the initial value and the option's value. 395 | * 396 | * If empty, the initial value is returned. If non-empty, the callable 397 | * receives the initial value and the option's value as arguments. 398 | * 399 | * ```php 400 | * 401 | * $some = new Some(5); 402 | * $none = None::create(); 403 | * $result = $some->foldLeft(1, function($a, $b) { return $a + $b; }); // int(6) 404 | * $result = $none->foldLeft(1, function($a, $b) { return $a + $b; }); // int(1) 405 | * 406 | * // This can be used instead of something like the following: 407 | * $option = Option::fromValue($integerOrNull); 408 | * $result = 1; 409 | * if ( ! $option->isEmpty()) { 410 | * $result += $option->get(); 411 | * } 412 | * ``` 413 | * 414 | * @template S 415 | * 416 | * @param S $initialValue 417 | * @param callable(S, T):S $callable 418 | * 419 | * @return S 420 | */ 421 | abstract public function foldLeft($initialValue, $callable); 422 | 423 | /** 424 | * foldLeft() but with reversed arguments for the callable. 425 | * 426 | * @template S 427 | * 428 | * @param S $initialValue 429 | * @param callable(T, S):S $callable 430 | * 431 | * @return S 432 | */ 433 | abstract public function foldRight($initialValue, $callable); 434 | } 435 | -------------------------------------------------------------------------------- /src/PhpOption/Some.php: -------------------------------------------------------------------------------- 1 | 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | namespace PhpOption; 20 | 21 | use ArrayIterator; 22 | 23 | /** 24 | * @template T 25 | * 26 | * @extends Option 27 | */ 28 | final class Some extends Option 29 | { 30 | /** @var T */ 31 | private $value; 32 | 33 | /** 34 | * @param T $value 35 | */ 36 | public function __construct($value) 37 | { 38 | $this->value = $value; 39 | } 40 | 41 | /** 42 | * @template U 43 | * 44 | * @param U $value 45 | * 46 | * @return Some 47 | */ 48 | public static function create($value): self 49 | { 50 | return new self($value); 51 | } 52 | 53 | public function isDefined(): bool 54 | { 55 | return true; 56 | } 57 | 58 | public function isEmpty(): bool 59 | { 60 | return false; 61 | } 62 | 63 | public function get() 64 | { 65 | return $this->value; 66 | } 67 | 68 | public function getOrElse($default) 69 | { 70 | return $this->value; 71 | } 72 | 73 | public function getOrCall($callable) 74 | { 75 | return $this->value; 76 | } 77 | 78 | public function getOrThrow(\Exception $ex) 79 | { 80 | return $this->value; 81 | } 82 | 83 | public function orElse(Option $else) 84 | { 85 | return $this; 86 | } 87 | 88 | public function ifDefined($callable) 89 | { 90 | $this->forAll($callable); 91 | } 92 | 93 | public function forAll($callable) 94 | { 95 | $callable($this->value); 96 | 97 | return $this; 98 | } 99 | 100 | public function map($callable) 101 | { 102 | return new self($callable($this->value)); 103 | } 104 | 105 | public function flatMap($callable) 106 | { 107 | /** @var mixed */ 108 | $rs = $callable($this->value); 109 | if (!$rs instanceof Option) { 110 | throw new \RuntimeException('Callables passed to flatMap() must return an Option. Maybe you should use map() instead?'); 111 | } 112 | 113 | return $rs; 114 | } 115 | 116 | public function filter($callable) 117 | { 118 | if (true === $callable($this->value)) { 119 | return $this; 120 | } 121 | 122 | return None::create(); 123 | } 124 | 125 | public function filterNot($callable) 126 | { 127 | if (false === $callable($this->value)) { 128 | return $this; 129 | } 130 | 131 | return None::create(); 132 | } 133 | 134 | public function select($value) 135 | { 136 | if ($this->value === $value) { 137 | return $this; 138 | } 139 | 140 | return None::create(); 141 | } 142 | 143 | public function reject($value) 144 | { 145 | if ($this->value === $value) { 146 | return None::create(); 147 | } 148 | 149 | return $this; 150 | } 151 | 152 | /** 153 | * @return ArrayIterator 154 | */ 155 | public function getIterator(): ArrayIterator 156 | { 157 | return new ArrayIterator([$this->value]); 158 | } 159 | 160 | public function foldLeft($initialValue, $callable) 161 | { 162 | return $callable($initialValue, $this->value); 163 | } 164 | 165 | public function foldRight($initialValue, $callable) 166 | { 167 | return $callable($this->value, $initialValue); 168 | } 169 | } 170 | --------------------------------------------------------------------------------