├── .editorconfig ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── composer.json ├── phpunit.xml ├── src ├── Bucket.php ├── Context.php ├── Events │ ├── CountEvent.php │ ├── ErrorEvent.php │ ├── PersistedEvent.php │ ├── RegisterEvent.php │ ├── SentEvent.php │ └── WarnEvent.php ├── Feature.php ├── FeatureInterface.php ├── Metrics.php ├── Repository.php ├── Storage.php ├── Strategy │ ├── ApplicationHostnameStrategy.php │ ├── DefaultStrategy.php │ ├── GradualRolloutRandomStrategy.php │ ├── GradualRolloutSessionIdStrategy.php │ ├── GradualRolloutUserIdStrategy.php │ ├── RemoteAddressStrategy.php │ ├── Strategy.php │ ├── StrategyTransportInterface.php │ └── UserWithIdStrategy.php ├── Unleash.php ├── UnleashClient.php └── Utils │ ├── data-formatters.php │ └── normalizer.php └── tests ├── .gitkeep ├── MetricsTest.php ├── Strategy ├── ApplicationHostnameStrategyTest.php ├── DefaultStrategyTest.php ├── GradualRolloutRandomStrategyTest.php ├── GradualRolloutSessionIdStrategyTest.php ├── GradualRolloutUserIdStrategyTest.php ├── RemoteAddressStrategyTest.php └── UserWithIdStrategyTest.php ├── UnleashClientTest.php ├── UnleashTest.php └── Utils └── NormalizerTest.php /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | end_of_line = lf 7 | charset = utf-8 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | 11 | [**.php] 12 | indent_style = space 13 | indent_size = 4 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | vendor/ 2 | composer.lock 3 | .DS_Store 4 | .idea -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: required 2 | language: php 3 | php: 4 | - 7.1 5 | - 7.2 6 | - 7.3 7 | 8 | matrix: 9 | include: 10 | - php: 7.1 11 | env: dependencies=lowest 12 | - php: 7.2 13 | env: dependencies=lowest 14 | - php: 7.3 15 | env: dependencies=lowest 16 | - php: 7.1 17 | env: dependencies=highest 18 | - php: 7.2 19 | env: dependencies=highest 20 | - php: 7.3 21 | env: dependencies=highest 22 | 23 | before_script: 24 | - printf "\n" | pecl install ev 25 | - composer self-update -q 26 | - if [ -z "$dependencies" ]; then composer install --no-interaction; fi; 27 | - if [ "$dependencies" = "lowest" ]; then composer update --prefer-lowest -n; fi; 28 | - if [ "$dependencies" = "highest" ]; then composer update -n; fi; 29 | 30 | script: phpunit 31 | 32 | cache: 33 | directories: 34 | - $HOME/.composer/cache/files -------------------------------------------------------------------------------- /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. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # unleash-client-php 2 | PHP client for Unleash 3 | 4 | ## Important 5 | 6 | THIS IS NOT READY TO BE USED YET! If you want to have a PHP client for Unleaseh, please contribute! 7 | 8 | This client will only happen if someone wants to contribute. Just create an issue reuest if you are interested in contributing. 9 | 10 | # Getting started 11 | 12 | ## Installation 13 | 14 | Install the library via composer (currently you need to provide the repository in the composer.json first): 15 | 16 | ```json 17 | "repositories": [ 18 | { 19 | "type": "vcs", 20 | "url": "https://github.com/Unleash/unleash-client-php.git" 21 | } 22 | ] 23 | ``` 24 | 25 | Then you can require the library via the commandline. 26 | 27 | ```bash 28 | composer require unleash/client 29 | ``` 30 | 31 | ## Code Usage 32 | 33 | ```php 34 | 35 | // initialize the client 36 | $unleashClient = new \Unleash\Unleash( 37 | $appName, 38 | $url, 39 | $instanceId = null, 40 | ); 41 | 42 | // to retrieve the current state of the feature flags 43 | $unleashClient->fetch(); 44 | 45 | // check if a feature is enabled 46 | if ($unleashClient->isEnabled('amazing_feature')) { 47 | echo 'Dude that amazing feature is enabled!'; 48 | } 49 | ``` 50 | 51 | ## Usage with Unleash 52 | 53 | See https://unleash.github.io/ for details. 54 | 55 | ## Usage with Gitlab 56 | 57 | * Get an Gitlab Premium license or the open source contract on gitlab.com 58 | * Open your Project 59 | * Head over to `Operations > Feature Flags` 60 | * Create a new feature e.g. `amazing_feature` 61 | * Retrieve the API URL and Instance ID via the configure button 62 | * Configure your client and roll out the code 63 | 64 | See https://docs.gitlab.com/ee/user/project/operations/feature_flags.html for more details. 65 | 66 | ## Running the tests 67 | 68 | We use phpunit for testing, which is installed as dev dependency. You can execute the tests by executing 69 | 70 | ```bash 71 | phpunit 72 | ``` 73 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "unleash/client", 3 | "description": "Unleash Client for PHP", 4 | "type": "library", 5 | "license": "Apache-2.0", 6 | "require": { 7 | "php": "^7.1.0", 8 | "ext-ev": "*", 9 | "ext-json": "*", 10 | "ext-pcntl": "*", 11 | "ext-posix": "*", 12 | "lastguest/murmurhash": "^2.0", 13 | "symfony/http-foundation": "^3.0 || ^4.0", 14 | "symfony/event-dispatcher": "3.0 || ^4.0", 15 | "guzzlehttp/guzzle": "~6.0" 16 | }, 17 | "autoload": { 18 | "files": [ 19 | "src/Utils/normalizer.php" 20 | ], 21 | "psr-4": { 22 | "Unleash\\": "src" 23 | } 24 | }, 25 | "autoload-dev": { 26 | "psr-4": { 27 | "Test\\": "tests/" 28 | } 29 | }, 30 | "require-dev": { 31 | "phpunit/phpunit": "7", 32 | "mockery/mockery": "^1.2" 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | ./tests/ 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/Bucket.php: -------------------------------------------------------------------------------- 1 | name = $name; 15 | $this->enabled = $enabled; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Events/ErrorEvent.php: -------------------------------------------------------------------------------- 1 | err = $err; 14 | } 15 | 16 | public function getError() 17 | { 18 | return $this->err; 19 | } 20 | 21 | public function setError(string $error) 22 | { 23 | $this->err = $error; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Events/PersistedEvent.php: -------------------------------------------------------------------------------- 1 | payload = $payload; 14 | } 15 | 16 | public function getPayload() 17 | { 18 | return $this->payload; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Events/SentEvent.php: -------------------------------------------------------------------------------- 1 | payload = $payload; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Events/WarnEvent.php: -------------------------------------------------------------------------------- 1 | msg = $msg; 14 | } 15 | 16 | public function getMessage() 17 | { 18 | return $this->msg; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/Feature.php: -------------------------------------------------------------------------------- 1 | name = $name; 10 | $this->enabled = $enabled; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/FeatureInterface.php: -------------------------------------------------------------------------------- 1 | disabled = $disableMetrics; 43 | $this->metricsInterval = $metricsInterval; 44 | $this->appName = $appName; 45 | $this->instanceId = $instanceId; 46 | $this->sdkVersion = '';//@todo: get the correct version 47 | $this->strategies = $strategies; 48 | $this->url = $url; 49 | $this->headers = $headers; 50 | $this->started = new \DateTime(); 51 | if ($client === null) { 52 | $client = new Client([ 53 | 'base_uri' => $url, 54 | ]); 55 | } 56 | $this->client = $client; 57 | 58 | $this->resetBucket(); 59 | } 60 | 61 | public function init() 62 | { 63 | if ($this->metricsInterval > 0) { 64 | $this->startTimer(); 65 | $this->registerInstance(); 66 | } 67 | } 68 | 69 | public function startTimer() 70 | { 71 | if ($this->disabled) { 72 | return false; 73 | } 74 | 75 | $this->timer = new \EvTimer($this->metricsInterval, 0, function () { 76 | $this->sendMetrics(); 77 | }); 78 | 79 | if (getenv('env') !== 'test') { 80 | \Ev::run(\Ev::RUN_NOWAIT); 81 | } else { 82 | \Ev::run(); 83 | } 84 | 85 | return true; 86 | } 87 | 88 | public function stop() 89 | { 90 | \Ev::stop(); 91 | $this->timer = null; 92 | $this->disabled = true; 93 | } 94 | 95 | public function registerInstance(): bool 96 | { 97 | if ($this->disabled) { 98 | return false; 99 | } 100 | 101 | $payload = $this->getClientData(); 102 | $options = $this->createCurlOptions($payload); 103 | $url = '/client/register'; 104 | try { 105 | $response = $this->client->request('post', $url, $options); 106 | } catch (ClientException $exception) { 107 | $response = $exception->getResponse(); 108 | } catch (ServerException $exception) { 109 | $this->dispatch('error', new ErrorEvent(['message' => $exception->getMessage()])); 110 | return false; 111 | } 112 | 113 | if (!($response->getStatusCode() >= 200 && $response->getStatusCode() < 300)) { 114 | $this->dispatch('warn', new WarnEvent($url . ' returning ' . $response->getStatusCode())); 115 | return false; 116 | } 117 | 118 | $this->dispatch('registered', new RegisterEvent($payload)); 119 | 120 | return true; 121 | } 122 | 123 | public function sendMetrics(): bool 124 | { 125 | if ($this->disabled) { 126 | return false; 127 | } 128 | if ($this->bucketIsEmpty()) { 129 | $this->resetBucket(); 130 | $this->startTimer(); 131 | return true; 132 | } 133 | 134 | $payload = $this->getPayload(); 135 | $options = $this->createCurlOptions($payload); 136 | $url = '/client/metrics'; 137 | try { 138 | $response = $this->client->request('post', $url, $options); 139 | } catch (ClientException $exception) { 140 | if ($exception->getResponse()->getStatusCode() === 404) { 141 | $this->dispatch('warn', new WarnEvent($url . ' returning 404, stopping metrics')); 142 | $this->stop(); 143 | return false; 144 | } 145 | 146 | $response = $exception->getResponse(); 147 | } catch (ServerException $exception) { 148 | $this->dispatch('error', new ErrorEvent(['message' => $exception->getMessage()])); 149 | return false; 150 | } 151 | 152 | if (!($response->getStatusCode() >= 200 && $response->getStatusCode() < 300)) { 153 | $this->dispatch('warn', new WarnEvent($url . ' returning ' . $response->getStatusCode())); 154 | return false; 155 | } 156 | 157 | $this->dispatch('sent', new SentEvent($payload)); 158 | return true; 159 | } 160 | 161 | public function count(string $name = null, bool $enabled = false): bool 162 | { 163 | if ($this->disabled) { 164 | return false; 165 | } 166 | 167 | if (!isset($this->bucket->toggles[$name])) { 168 | $this->bucket->toggles[$name] = [ 169 | 'yes' => 0, 170 | 'no' => 0, 171 | ]; 172 | } 173 | 174 | $this->bucket->toggles[$name][$enabled ? 'yes' : 'no']++; 175 | $this->dispatch('count', new CountEvent($name, $enabled)); 176 | 177 | return true; 178 | } 179 | 180 | public function bucketIsEmpty() 181 | { 182 | return count(array_keys($this->bucket->toggles)) === 0; 183 | } 184 | 185 | public function resetBucket() 186 | { 187 | $bucket = new Bucket(); 188 | $bucket->start = new \DateTime(); 189 | $bucket->stop = null; 190 | $bucket->toggles = []; 191 | $this->bucket = $bucket; 192 | } 193 | 194 | public function closeBucket() 195 | { 196 | $this->bucket->stop = new \DateTime(); 197 | } 198 | 199 | public function getPayload() 200 | { 201 | $this->closeBucket(); 202 | $payload = $this->getMetricsData(); 203 | $this->resetBucket(); 204 | return $payload; 205 | } 206 | 207 | public function getClientData() 208 | { 209 | return [ 210 | 'appName' => $this->appName, 211 | 'instanceId' => $this->instanceId, 212 | 'sdkVersion' => $this->sdkVersion, 213 | 'strategies' => $this->strategies, 214 | 'interval' => $this->metricsInterval, 215 | ]; 216 | } 217 | 218 | public function getMetricsData() 219 | { 220 | return [ 221 | 'appName' => $this->appName, 222 | 'instanceId' => $this->instanceId, 223 | 'bucket' => (array)$this->bucket, 224 | ]; 225 | } 226 | 227 | /** 228 | * @param array $payload JSON data 229 | * 230 | * @param int $timeout Connection timeout in seconds. 231 | * 232 | * @return array 233 | */ 234 | public function createCurlOptions(array $payload, $timeout = 10) 235 | { 236 | return [ 237 | 'connect_timeout' => $timeout, 238 | 'headers' => array_merge( 239 | [ 240 | 'UNLEASH-APPNAME' => $this->appName, 241 | 'UNLEASH-INSTANCEID' => $this->instanceId, 242 | 'User-Agent' => $this->appName, 243 | ], 244 | $this->headers 245 | ), 246 | 'json' => $payload, 247 | ]; 248 | } 249 | } 250 | -------------------------------------------------------------------------------- /src/Repository.php: -------------------------------------------------------------------------------- 1 | client = new Client([ 36 | 'base_uri' => $url, 37 | ]); 38 | } else { 39 | $this->client = $client; 40 | } 41 | $this->url = $url; 42 | $this->refreshInterval = $refreshInterval; 43 | $this->instanceId = $instanceId; 44 | $this->appName = $appName; 45 | $this->headers = $headers; 46 | 47 | if ($storageImpl === null) { 48 | $this->storage = new Storage($backupPath, $appName); 49 | } else { 50 | $this->storage = $storageImpl; 51 | } 52 | 53 | $this->storage->addListener('error', function (ErrorEvent $event) { 54 | $this->dispatch('error', $event); 55 | }); 56 | $this->storage->addListener('ready', function () { 57 | $this->dispatch('ready'); 58 | }); 59 | } 60 | 61 | public function timedFetch() 62 | { 63 | if ($this->refreshInterval !== null && $this->refreshInterval > 0) { 64 | $this->timer = new \EvTimer($this->refreshInterval, 0, function () { 65 | $this->fetch(); 66 | }); 67 | if (getenv('env') !== 'test') { 68 | \Ev::run(\Ev::RUN_NOWAIT); 69 | } else { 70 | \Ev::run(); 71 | } 72 | } 73 | } 74 | 75 | public function fetch() 76 | { 77 | $url = './client/features'; 78 | $options = $this->createOptions(); 79 | try { 80 | $response = $this->client->get($url, $options); 81 | } catch (ClientException $exception) { 82 | $response = $exception->getResponse(); 83 | } catch (ServerException $exception) { 84 | $this->dispatch('error', new ErrorEvent(['message' => $exception->getMessage()])); 85 | return false; 86 | } 87 | 88 | $this->timedFetch(); 89 | if ($response->getStatusCode() === 304) { 90 | return; 91 | } 92 | 93 | if (!($response->getStatusCode() >= 200 && $response->getStatusCode() < 300)) { 94 | return $this->dispatch( 95 | 'error', 96 | new ErrorEvent(['message' => 'Response was not statusCode 2XX, but was ' . $response->getStatusCode()]) 97 | ); 98 | } 99 | 100 | $payload = json_decode($response->getBody()->getContents(), true); 101 | $features = $this->pickData($payload)['features']; 102 | 103 | $this->storage->reset($features); 104 | $this->etag = $response->getHeader('etag'); 105 | $this->dispatch('data'); 106 | } 107 | 108 | public function pickData(array $data): array 109 | { 110 | $features = []; 111 | foreach ($data['features'] as $row) { 112 | $feature = new Feature(); 113 | $feature->name = $row['name']; 114 | $feature->enabled = $row['enabled']; 115 | $feature->strategies = [new StrategyTransportInterface($row['strategy'], $row['parameters'] ?? null)]; 116 | $features[$row['name']] = $feature; 117 | } 118 | 119 | return [ 120 | 'version' => 1, 121 | 'features' => $features, 122 | ]; 123 | } 124 | 125 | public function getToggle(string $name): ?FeatureInterface 126 | { 127 | return $this->storage->get($name); 128 | } 129 | 130 | public function stop() 131 | { 132 | //@todo: implement 133 | } 134 | 135 | public function createOptions(int $timeout = 10) 136 | { 137 | return [ 138 | 'connect_timeout' => $timeout, 139 | 'headers' => array_merge( 140 | [ 141 | 'UNLEASH-APPNAME' => $this->appName, 142 | 'UNLEASH-INSTANCEID' => $this->instanceId, 143 | 'User-Agent' => $this->appName, 144 | ], 145 | $this->headers 146 | ), 147 | 'If-None-match' => $this->etag, 148 | ]; 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/Storage.php: -------------------------------------------------------------------------------- 1 | path = $backupPath . '/unleash/repo/schema-v1-' . $this->safeAppName($appName) . '.json'; 18 | $this->load(); 19 | } 20 | 21 | public function safeAppName(string $appName) 22 | { 23 | return str_replace('/', '_', $appName); 24 | } 25 | 26 | public function reset(array $features, bool $doPersist = true) 27 | { 28 | $doEmitReady = $this->ready === false; 29 | $this->ready = true; 30 | $this->data = $features; 31 | if ($doEmitReady) { 32 | $this->dispatch('ready'); 33 | } 34 | 35 | if ($doPersist) { 36 | $this->persist(); 37 | } 38 | } 39 | 40 | public function get(string $key): ?FeatureInterface 41 | { 42 | return $this->data[$key] ?? null; 43 | } 44 | 45 | public function persist() 46 | { 47 | $file = @fopen($this->path, "w"); 48 | if ($file === false) { 49 | $this->dispatch('error', new ErrorEvent(error_get_last())); 50 | return; 51 | } 52 | 53 | fwrite($file, json_encode($this->data)); 54 | fclose($file); 55 | 56 | $this->dispatch('persisted', new PersistedEvent()); 57 | } 58 | 59 | public function load() 60 | { 61 | if ($this->ready) { 62 | return; 63 | } 64 | 65 | $data = @file_get_contents($this->path); 66 | if ($data === false) { 67 | $error = error_get_last(); 68 | if (!strpos($error['message'], 'failed to open stream: No such file or directory') !== false) { 69 | $this->dispatch('error', new ErrorEvent($error)); 70 | } 71 | 72 | return; 73 | } 74 | 75 | $this->reset(json_decode($data, true), false); 76 | //@todo: do something with json_last_error 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/Strategy/ApplicationHostnameStrategy.php: -------------------------------------------------------------------------------- 1 | hostname = strtolower($_SERVER['host_name'] ?? 'undefined'); 16 | } 17 | 18 | public function isEnabled(array $parameters = null, Context $context = null): bool 19 | { 20 | if (!isset($parameters['hostNames'])) { 21 | return false; 22 | } 23 | 24 | return in_array($this->hostname, array_map('trim', explode(',', strtolower($parameters['hostNames'])))); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Strategy/DefaultStrategy.php: -------------------------------------------------------------------------------- 1 | = $random; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Strategy/GradualRolloutSessionIdStrategy.php: -------------------------------------------------------------------------------- 1 | sessionId || !isset($parameters['percentage'])) { 17 | return false; 18 | } 19 | 20 | $percentage = (int)$parameters['percentage']; 21 | $groupId = $parameters['groupId'] ?? ''; 22 | $normalizedId = normalizeValue($context->sessionId, $groupId); 23 | 24 | return $percentage > 0 && $normalizedId <= $percentage; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/Strategy/GradualRolloutUserIdStrategy.php: -------------------------------------------------------------------------------- 1 | userId) || !isset($parameters['percentage'])) { 17 | return false; 18 | } 19 | 20 | $percentage = (int)$parameters['percentage']; 21 | $groupId = $parameters['groupId'] ?? ''; 22 | $normalizedUserId = normalizeValue($context->userId, $groupId); 23 | return $percentage > 0 && $normalizedUserId <= $percentage; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/Strategy/RemoteAddressStrategy.php: -------------------------------------------------------------------------------- 1 | remoteAddress) { 25 | return true; 26 | } elseif (!filter_var($range, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) { 27 | if (IpUtils::checkIp($context->remoteAddress, $range)) { 28 | return true; 29 | } 30 | } 31 | } catch (\Exception $e) { 32 | continue; 33 | } 34 | } 35 | 36 | return false; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Strategy/Strategy.php: -------------------------------------------------------------------------------- 1 | name = $name; 16 | $this->returnValue = $returnValue; 17 | } 18 | 19 | public function isEnabled(array $parameters = null, Context $context = null): bool 20 | { 21 | return $this->returnValue; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Strategy/StrategyTransportInterface.php: -------------------------------------------------------------------------------- 1 | name = $name; 13 | $this->parameters = $parameters; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Strategy/UserWithIdStrategy.php: -------------------------------------------------------------------------------- 1 | userId, $userIds); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/Unleash.php: -------------------------------------------------------------------------------- 1 | 'Unleash server URL ' . $oldUrl . ' should no longer link directly to /features']; 59 | $event = new WarnEvent($err); 60 | $this->dispatch('warn', $event); 61 | $url = str_replace('/features', '', $url); 62 | } 63 | 64 | if (substr($url, -1) !== '/') { 65 | $url .= '/'; 66 | } 67 | 68 | if ($instanceId === null) { 69 | $info = posix_getpwuid(posix_geteuid()); 70 | 71 | $prefix = $info['username'] ?? 'generated-' . round((mt_rand() / mt_getrandmax() * 1000000)) . '-' . getmypid(); 72 | $instanceId = $prefix . '-' . $_SERVER['host_name']; 73 | } 74 | 75 | $this->repository = new Repository( 76 | $backupPath, 77 | $url, 78 | $appName, 79 | $instanceId, 80 | $refreshInterval, 81 | $customHeaders, 82 | null, 83 | $client 84 | ); 85 | 86 | $defaultStrategies = [ 87 | new DefaultStrategy(), 88 | new ApplicationHostnameStrategy(), 89 | new GradualRolloutRandomStrategy(), 90 | new GradualRolloutUserIdStrategy(), 91 | new GradualRolloutSessionIdStrategy(), 92 | new UserWithIdStrategy(), 93 | new RemoteAddressStrategy(), 94 | ]; 95 | 96 | $strategies = array_merge($defaultStrategies, $strategies); 97 | $this->repository->addListener('ready', function () use ($strategies) { 98 | $this->client = new UnleashClient($this->repository, $strategies); 99 | $this->client->addListener('error', function (ErrorEvent $event) { 100 | $this->dispatch('error', $event); 101 | }); 102 | $this->client->addListener('warn', function (WarnEvent $event) { 103 | $this->dispatch('warn', $event); 104 | }); 105 | $this->dispatch('ready'); 106 | }); 107 | 108 | $this->repository->addListener('error', function (ErrorEvent $event) { 109 | $event->getError()['message'] = 'Unleash Repository error: ' . $event->getError()['message']; 110 | $this->dispatch('error', $event); 111 | }); 112 | 113 | $this->repository->addListener('warn', function (WarnEvent $event) { 114 | $this->dispatch('warn', $event); 115 | }); 116 | 117 | $this->metrics = new Metrics( 118 | $appName, 119 | $instanceId, 120 | $strategies, 121 | $url, 122 | $customHeaders, 123 | $metricsInterval, 124 | $disableMetrics, 125 | $this->client 126 | ); 127 | 128 | $this->metrics->addListener('error', function (ErrorEvent $event) { 129 | $event->setError('Unleash Metrics error: ' . $event->getError()['message']); 130 | $this->dispatch('error', $event); 131 | }); 132 | 133 | $this->metrics->addListener('warn', function (WarnEvent $event) { 134 | $this->dispatch('warn', $event); 135 | }); 136 | 137 | $this->metrics->addListener('count', function (CountEvent $event) { 138 | $this->dispatch('count', $event); 139 | }); 140 | 141 | $this->metrics->addListener('sent', function (SentEvent $event) { 142 | $this->dispatch('sent', $event); 143 | }); 144 | 145 | $this->metrics->addListener('registered', function (RegisterEvent $event) { 146 | $this->dispatch('registered', $event); 147 | }); 148 | } 149 | 150 | public function fetch() 151 | { 152 | $this->repository->fetch(); 153 | } 154 | 155 | public function isEnabled(string $name, Context $context = null, bool $fallbackValue = null) 156 | { 157 | $result = null; 158 | if ($this->client !== null) { 159 | $result = $this->client->isEnabled($name, $context, $fallbackValue); 160 | } else { 161 | $result = is_bool($fallbackValue) ? $fallbackValue : false; 162 | $this->dispatch( 163 | 'warn', 164 | new WarnEvent('Unleash has not been initialized yet. isEnabled(' . $name . ') defaulted to ' . $fallbackValue) 165 | ); 166 | } 167 | $this->count($name, $result); 168 | return $result; 169 | } 170 | 171 | public function count(string $toggleName, bool $enabled) 172 | { 173 | $this->metrics->count($toggleName, $enabled); 174 | } 175 | 176 | public function destroy() 177 | { 178 | $this->repository->stop(); 179 | $this->metrics->stop(); 180 | $this->client = null; 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /src/UnleashClient.php: -------------------------------------------------------------------------------- 1 | repository = $repository; 24 | $this->strategies = $strategies; 25 | 26 | foreach ($strategies as $strategy) { 27 | if (!$strategy instanceof Strategy) { 28 | throw new \Exception('Invalid strategy data / interface'); 29 | } 30 | } 31 | } 32 | 33 | private function getStrategy(string $name): ?Strategy 34 | { 35 | $match = null; 36 | foreach ($this->strategies as $strategy) { 37 | if ($strategy->name === $name) { 38 | $match = $strategy; 39 | break; 40 | } 41 | } 42 | 43 | return $match; 44 | } 45 | 46 | /** 47 | * @param string $missingStrategy 48 | * @param string $name 49 | * @param StrategyTransportInterface[] $strategies 50 | */ 51 | public function warnOnce(string $missingStrategy, string $name, array $strategies) 52 | { 53 | if (!isset($this->warned[$missingStrategy . $name])) { 54 | $this->warned[$missingStrategy . $name] = true; 55 | 56 | $strategyNames = implode( 57 | ", ", 58 | array_map( 59 | function (StrategyTransportInterface $strategy) { 60 | return $strategy->name; 61 | }, 62 | $strategies 63 | ) 64 | ); 65 | $this->dispatch('warn', new WarnEvent("Missing strategy " . $missingStrategy . " for toggle " . $name . ". Ensure that " . $strategyNames . " are supported before using this toggle")); 66 | } 67 | } 68 | 69 | public function isEnabled(string $name, Context $context = null, bool $fallbackValue = null): bool 70 | { 71 | $feature = $this->repository->getToggle($name); 72 | 73 | if ($feature === null && is_bool($fallbackValue)) { 74 | return $fallbackValue; 75 | } 76 | 77 | if ($feature === null || !$feature->enabled) { 78 | return false; 79 | } 80 | 81 | if (count($feature->strategies) === 0) { 82 | return $feature->enabled; 83 | } 84 | 85 | foreach ($feature->strategies as $strategySelector) { 86 | $strategy = $this->getStrategy($strategySelector->name); 87 | if ($strategy === null) { 88 | $this->warnOnce($strategySelector->name, $name, $feature->strategies); 89 | continue; 90 | } 91 | 92 | return $strategy->isEnabled($strategySelector->parameters, $context); 93 | } 94 | 95 | return false; 96 | } 97 | 98 | public function initialize(array $options) 99 | { 100 | $instance = new Unleash(); 101 | $instance->addListener('error', function () { 102 | }); 103 | 104 | $instance->initialize( 105 | $options['appName'], 106 | $options['url'], 107 | $options['instanceId'], 108 | $options['refreshInterval'], 109 | $options['metricsInterval'], 110 | $options['disableMetrics'], 111 | $options['backupPath'], 112 | $options['stategies'], 113 | $options['customHeaders'] 114 | ); 115 | 116 | return $instance; 117 | } 118 | 119 | public function destroy() 120 | { 121 | throw new \Exception("Not implemented", 1); 122 | } 123 | 124 | public function getFeatureToggleDefinition($toggleName) 125 | { 126 | throw new \Exception("Not implemented", 1); 127 | } 128 | 129 | public function count($toggleName, $enabled) 130 | { 131 | throw new \Exception("Not implemented", 1); 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/Utils/data-formatters.php: -------------------------------------------------------------------------------- 1 | name = $row['name']; 15 | $feature->enabled = $row['enabled']; 16 | $feature->strategies = [new StrategyTransportInterface($row['strategy'], $row['parameters'])]; 17 | } 18 | 19 | return [ 20 | 'version' => 1, 21 | 'features' => $features, 22 | ]; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/Utils/normalizer.php: -------------------------------------------------------------------------------- 1 | HandlerStack::create($mock)]); 25 | return $client; 26 | } 27 | 28 | public function testShouldBeDisabledByFlagDisableMetrics() 29 | { 30 | $metrics = new Metrics('', '', [], '', [], 0, true); 31 | $metrics->count('foo', true); 32 | /** @var Bucket $bucket */ 33 | $bucket = Assert::readAttribute($metrics, 'bucket'); 34 | 35 | $this->assertEquals(0, count($bucket->toggles)); 36 | } 37 | 38 | public function testFunctionsShouldRespectDisabled() 39 | { 40 | $metrics = new Metrics('', '', [], '', [], 0, true); 41 | $this->assertFalse($metrics->startTimer()); 42 | $this->assertFalse($metrics->registerInstance()); 43 | $this->assertFalse($metrics->count()); 44 | $this->assertFalse($metrics->sendMetrics()); 45 | } 46 | 47 | public function testShouldNotStartOrRegisterWhenMetricsIntervalIs0() 48 | { 49 | $metrics = new Metrics('', '', [], '', [], 0, true); 50 | $timer = Assert::readAttribute($metrics, 'timer'); 51 | $this->assertNull($timer); 52 | } 53 | 54 | public function testSendMetricsAndRegisterWhenMetricsIntervalIsAPositiveNumber() 55 | { 56 | $this->markTestSkipped('broken, needs fix'); 57 | $client = $this->mockNetwork(); 58 | $metrics = new Metrics('', '', [], '', [], 0.05, false, $client); 59 | $metrics->count('toggle-x', true); 60 | $metrics->count('toggle-x', false); 61 | $metrics->count('toggle-y', true); 62 | 63 | $eventCount = 0; 64 | $metrics->addListener('registered', function () use (&$eventCount) { 65 | $eventCount++; 66 | }); 67 | $metrics->addListener('sent', function () use (&$eventCount) { 68 | $eventCount++; 69 | }); 70 | 71 | $metrics->init(); 72 | $this->assertEquals(2, $eventCount); 73 | } 74 | 75 | public function testShouldSendMetrics() 76 | { 77 | $this->markTestSkipped('broken, needs fix'); 78 | $client = \Mockery::mock(Client::class); 79 | $client->shouldReceive('request') 80 | ->withArgs(function ($method, $url, $options){ 81 | if($url === '/client/metrics'){ 82 | $this->assertNotNull($options['json']['bucket']['start']); 83 | $this->assertNotNull($options['json']['bucket']['stop']); 84 | $this->assertEquals([ 85 | 'toggle-x' => ['yes' => 1, 'no' => 1], 86 | 'toggle-y' => ['yes' => 1, 'no' => 0] 87 | ],$options['json']['bucket']['toggles']); 88 | } 89 | 90 | return true; 91 | }) 92 | ->andReturn(new Response()); 93 | $metrics = new Metrics('', '', [], '', [], 0.05, false, $client); 94 | $metrics->count('toggle-x', true); 95 | $metrics->count('toggle-x', false); 96 | $metrics->count('toggle-y', true); 97 | 98 | $eventCount = 0; 99 | $metrics->addListener('registered', function () use (&$eventCount) { 100 | $eventCount++; 101 | }); 102 | $metrics->addListener('sent', function () use (&$eventCount) { 103 | $eventCount++; 104 | }); 105 | 106 | $metrics->init(); 107 | $this->assertEquals(2, $eventCount); 108 | } 109 | 110 | public function testShouldSendCustomHeaders() 111 | { 112 | $this->markTestSkipped('broken, needs fix'); 113 | $randomKey = 'value-' . mt_rand(1,100); 114 | 115 | $client = \Mockery::mock(Client::class); 116 | $client->shouldReceive('request') 117 | ->withArgs(function ($method, $url, $options) use ($randomKey){ 118 | $this->assertEquals($randomKey, $options['headers']['randomKey']); 119 | return isset($options['headers']['randomKey']) ? true : false; 120 | }) 121 | ->andReturn(new Response()); 122 | $metrics = new Metrics('', '', [], '', [ 123 | 'randomKey' => $randomKey 124 | ], 0.05, false, $client); 125 | $metrics->count('toggle-x', true); 126 | $metrics->count('toggle-x', false); 127 | $metrics->count('toggle-y', true); 128 | 129 | $eventCount = 0; 130 | $metrics->addListener('sent', function () use (&$eventCount) { 131 | $eventCount++; 132 | }); 133 | 134 | $metrics->init(); 135 | $this->assertEquals(1, $eventCount); 136 | } 137 | 138 | public function testRegisterInstanceShouldWarnWhenNon200StatusCode() 139 | { 140 | $client = $this->mockNetwork(500); 141 | $metrics = new Metrics('', '', [], '', [], 0, false, $client); 142 | $eventCount = 0; 143 | $metrics->addListener('error', function (ErrorEvent $event) use (&$eventCount){ 144 | $this->assertNotNull($event); 145 | $eventCount++; 146 | }); 147 | 148 | $metrics->init(); 149 | 150 | //@todo: This test might not be correct 151 | $this->assertFalse($metrics->registerInstance()); 152 | $this->assertEquals(1, $eventCount); 153 | } 154 | 155 | public function testSendMatricsShouldStopDisableMetricsIfEndpointReturn404() 156 | { 157 | $client = $this->mockNetwork(404); 158 | $metrics = new Metrics('', '', [], '', [], 0, false, $client); 159 | $eventCount = 0; 160 | $metrics->addListener('warn', function () use (&$eventCount, $metrics){ 161 | $metrics->stop(); 162 | $this->assertTrue(Assert::readAttribute($metrics, 'disabled')); 163 | $eventCount++; 164 | }); 165 | $metrics->init(); 166 | 167 | $metrics->count('x-y-z', true); 168 | $metrics->sendMetrics(); 169 | //@todo: This test might not be correct 170 | $this->assertTrue(Assert::readAttribute($metrics, 'disabled')); 171 | } 172 | 173 | public function testSendMetricsShouldEmitWarnOnNon200StatusCode() 174 | { 175 | $client = $this->mockNetwork(406); 176 | $metrics = new Metrics('', '', [], '', [], 0, false, $client); 177 | $eventCount = 0; 178 | $metrics->addListener('warn', function () use (&$eventCount, $metrics){ 179 | $eventCount++; 180 | }); 181 | $metrics->init(); 182 | 183 | $metrics->count('x-y-z', true); 184 | $metrics->sendMetrics(); 185 | $this->assertEquals(1, $eventCount); 186 | } 187 | 188 | public function testSendMetricsShouldNotSendEmptyBuckets() 189 | { 190 | $this->markTestSkipped('Test is broken atm, needs fix'); 191 | 192 | $client = $this->mockNetwork(200); 193 | $metrics = new Metrics('', '', [], '', [], 0, false, $client); 194 | $metrics->init(); 195 | 196 | //@todo: 197 | $this->assertTrue($metrics->sendMetrics()); 198 | } 199 | 200 | public function testCountShouldIncrementYesAndNoCounters() 201 | { 202 | $client = $this->mockNetwork(); 203 | $metrics = new Metrics('', '', [], '', [], 0, false, $client); 204 | $metrics->init(); 205 | 206 | $name = 'name' . mt_rand(0,10000); 207 | $this->assertFalse(isset(Assert::readAttribute($metrics, 'bucket')->toggles[$name])); 208 | 209 | $metrics->count($name, true); 210 | 211 | $this->assertEquals(1,Assert::readAttribute($metrics, 'bucket')->toggles[$name]['yes']); 212 | $this->assertEquals(0,Assert::readAttribute($metrics, 'bucket')->toggles[$name]['no']); 213 | 214 | $metrics->count($name, true); 215 | $metrics->count($name, true); 216 | $metrics->count($name, false); 217 | $metrics->count($name, false); 218 | $metrics->count($name, false); 219 | $metrics->count($name, false); 220 | 221 | $this->assertEquals(3,Assert::readAttribute($metrics, 'bucket')->toggles[$name]['yes']); 222 | $this->assertEquals(4,Assert::readAttribute($metrics, 'bucket')->toggles[$name]['no']); 223 | } 224 | } -------------------------------------------------------------------------------- /tests/Strategy/ApplicationHostnameStrategyTest.php: -------------------------------------------------------------------------------- 1 | assertEquals('applicationHostname', $strategy->name); 13 | } 14 | 15 | public function testShouldBeDisabledWhenNoHostnameDefined() 16 | { 17 | $strategy = new \Unleash\Strategy\ApplicationHostnameStrategy(); 18 | $this->assertFalse($strategy->isEnabled(['hostNames' => ''])); 19 | } 20 | 21 | public function testShouldBeEnabledWhenHostnameIsDefined() 22 | { 23 | $_SERVER['host_name'] = ''; 24 | $strategy = new \Unleash\Strategy\ApplicationHostnameStrategy(); 25 | $this->assertTrue($strategy->isEnabled(['hostNames' => $_SERVER['host_name']])); 26 | } 27 | 28 | public function testShouldBeEnabledWhenHostnameIsDefinedInList() 29 | { 30 | $_SERVER['host_name'] = ''; 31 | $strategy = new \Unleash\Strategy\ApplicationHostnameStrategy(); 32 | $this->assertTrue($strategy->isEnabled(['hostNames' => 'localhost, ' . $_SERVER['host_name']])); 33 | } 34 | 35 | public function testShouldBeEnabledWhenHostnameIsDefinedViaServerGlobal() 36 | { 37 | $_SERVER['host_name'] = 'some-random-name'; 38 | $strategy = new \Unleash\Strategy\ApplicationHostnameStrategy(); 39 | $this->assertTrue($strategy->isEnabled(['hostNames' => 'localhost, some-random-name'])); 40 | } 41 | 42 | public function testShouldBeHandleWierdCasting() 43 | { 44 | $_SERVER['host_name'] = 'some-random-NAME'; 45 | $strategy = new \Unleash\Strategy\ApplicationHostnameStrategy(); 46 | $this->assertTrue($strategy->isEnabled(['hostNames' => 'localhost, some-random-name'])); 47 | } 48 | } -------------------------------------------------------------------------------- /tests/Strategy/DefaultStrategyTest.php: -------------------------------------------------------------------------------- 1 | assertTrue($strategy->isEnabled()); 13 | } 14 | 15 | public function testShouldHaveCorrectName() 16 | { 17 | $strategy = new \Unleash\Strategy\ApplicationHostnameStrategy(); 18 | $this->assertEquals('applicationHostname', $strategy->name); 19 | } 20 | } -------------------------------------------------------------------------------- /tests/Strategy/GradualRolloutRandomStrategyTest.php: -------------------------------------------------------------------------------- 1 | $percentage, 'groupId' => $groupId]; 21 | $context = new \Unleash\Context(); 22 | $context->sessionId = $i; 23 | if ($strategy->isEnabled($params, $context)) { 24 | $enabledCount++; 25 | } 26 | } 27 | 28 | $actualPercentage = round($enabledCount / $rounds * 100); 29 | $highMark = $percentage + 1; 30 | $lowMark = $percentage - 1; 31 | 32 | $this->assertTrue($lowMark <= $actualPercentage); 33 | $this->assertTrue($highMark >= $actualPercentage); 34 | } 35 | } -------------------------------------------------------------------------------- /tests/Strategy/GradualRolloutSessionIdStrategyTest.php: -------------------------------------------------------------------------------- 1 | assertEquals('gradualRolloutSessionId', $strategy->name); 13 | } 14 | 15 | public function testAlways100Percentage() 16 | { 17 | $strategy = new GradualRolloutSessionIdStrategy(); 18 | $context = new \Unleash\Context(); 19 | $context->sessionId = '123'; 20 | $parameters = ['percentage' => 100, 'groupId' => 'gr1']; 21 | $this->assertTrue($strategy->isEnabled($parameters, $context)); 22 | } 23 | 24 | public function testAlways0Percentage() 25 | { 26 | $strategy = new GradualRolloutSessionIdStrategy(); 27 | $context = new \Unleash\Context(); 28 | $context->sessionId = '123'; 29 | $parameters = ['percentage' => 0, 'groupId' => 'gr1']; 30 | $this->assertFalse($strategy->isEnabled($parameters, $context)); 31 | } 32 | 33 | public function testShouldBeEnabledWhenPercentageIsExactlySame() 34 | { 35 | $strategy = new GradualRolloutSessionIdStrategy(); 36 | $context = new \Unleash\Context(); 37 | 38 | $sessionId = '123123'; 39 | $groupId = 'group1'; 40 | 41 | $percentage = normalizeValue($sessionId, $groupId); 42 | $context->sessionId = $sessionId; 43 | $parameters = ['percentage' => $percentage, 'groupId' => $groupId]; 44 | $this->assertTrue($strategy->isEnabled($parameters, $context)); 45 | } 46 | 47 | public function testShouldBeDisabledWhenPercentageIsJustBelowRequiredValue() 48 | { 49 | $strategy = new GradualRolloutSessionIdStrategy(); 50 | $context = new \Unleash\Context(); 51 | 52 | $sessionId = '123123'; 53 | $groupId = 'group1'; 54 | 55 | $percentage = normalizeValue($sessionId, $groupId) - 1; 56 | $context->sessionId = $sessionId; 57 | $parameters = ['percentage' => $percentage, 'groupId' => $groupId]; 58 | $this->assertFalse($strategy->isEnabled($parameters, $context)); 59 | } 60 | 61 | public function testShouldOlyAtMostMissByOnePercent() 62 | { 63 | $strategy = new GradualRolloutSessionIdStrategy(); 64 | 65 | $percentage = 25; 66 | $groupId = 'groupId'; 67 | 68 | $rounds = 200000; 69 | $enabledCount = 0; 70 | 71 | for ($i = 0; $i < $rounds; $i++) { 72 | $params = ['percentage' => $percentage, 'groupId' => $groupId]; 73 | $context = new \Unleash\Context(); 74 | $context->sessionId = $i; 75 | if ($strategy->isEnabled($params, $context)) { 76 | $enabledCount++; 77 | } 78 | } 79 | 80 | $actualPercentage = round($enabledCount / $rounds * 100); 81 | $highMark = $percentage + 1; 82 | $lowMark = $percentage - 1; 83 | 84 | $this->assertTrue($lowMark <= $actualPercentage); 85 | $this->assertTrue($highMark >= $actualPercentage); 86 | } 87 | } -------------------------------------------------------------------------------- /tests/Strategy/GradualRolloutUserIdStrategyTest.php: -------------------------------------------------------------------------------- 1 | assertEquals('gradualRolloutUserId', $strategy->name); 14 | } 15 | 16 | public function testAlways100Percentage() 17 | { 18 | $strategy = new GradualRolloutUserIdStrategy(); 19 | $context = new \Unleash\Context(); 20 | $context->userId = '123'; 21 | $parameters = ['percentage' => 100, 'groupId' => 'gr1']; 22 | $this->assertTrue($strategy->isEnabled($parameters, $context)); 23 | } 24 | 25 | public function testAlways0Percentage() 26 | { 27 | $strategy = new GradualRolloutUserIdStrategy(); 28 | $context = new \Unleash\Context(); 29 | $context->userId = '123'; 30 | $parameters = ['percentage' => 0, 'groupId' => 'gr1']; 31 | $this->assertFalse($strategy->isEnabled($parameters, $context)); 32 | } 33 | 34 | public function testShouldBeEnabledWhenPercentageIsExactlySame() 35 | { 36 | $strategy = new GradualRolloutUserIdStrategy(); 37 | $context = new \Unleash\Context(); 38 | 39 | $userId = '123123'; 40 | $groupId = 'group1'; 41 | 42 | $percentage = normalizeValue($userId, $groupId); 43 | $context->userId = $userId; 44 | $parameters = ['percentage' => $percentage, 'groupId' => $groupId]; 45 | $this->assertTrue($strategy->isEnabled($parameters, $context)); 46 | } 47 | 48 | public function testShouldBeDisabledWhenPercentageIsJustBelowRequiredValue() 49 | { 50 | $strategy = new GradualRolloutUserIdStrategy(); 51 | $context = new \Unleash\Context(); 52 | 53 | $userId = '123123'; 54 | $groupId = 'group1'; 55 | 56 | $percentage = normalizeValue($userId, $groupId) - 1; 57 | $parameters = ['percentage' => $percentage, 'groupId' => $groupId]; 58 | $context->userId = $userId; 59 | $this->assertFalse($strategy->isEnabled($parameters, $context)); 60 | } 61 | 62 | public function testShouldOlyAtMostMissByOnePercent() 63 | { 64 | $strategy = new GradualRolloutUserIdStrategy(); 65 | 66 | $percentage = 25; 67 | $groupId = 'groupId'; 68 | 69 | $rounds = 200000; 70 | $enabledCount = 0; 71 | 72 | for ($i = 0; $i < $rounds; $i++) { 73 | $params = ['percentage' => $percentage, 'groupId' => $groupId]; 74 | $context = new \Unleash\Context(); 75 | $context->userId = $i; 76 | if ($strategy->isEnabled($params, $context)) { 77 | $enabledCount++; 78 | } 79 | } 80 | 81 | $actualPercentage = round($enabledCount / $rounds * 100); 82 | $highMark = $percentage + 1; 83 | $lowMark = $percentage - 1; 84 | 85 | $this->assertTrue($lowMark <= $actualPercentage); 86 | $this->assertTrue($highMark >= $actualPercentage); 87 | } 88 | } -------------------------------------------------------------------------------- /tests/Strategy/RemoteAddressStrategyTest.php: -------------------------------------------------------------------------------- 1 | assertEquals('remoteAddress', $strategy->name); 15 | } 16 | 17 | public function testNotCrashForMissingParams() 18 | { 19 | $strategy = new RemoteAddressStrategy(); 20 | $context = new Context(); 21 | $context->remoteAddress = '123'; 22 | 23 | $this->assertFalse($strategy->isEnabled([], $context)); 24 | } 25 | 26 | public function testEnabledForIpInSingleList() 27 | { 28 | $strategy = new RemoteAddressStrategy(); 29 | $params = ['IPs' => '127.0.0.1']; 30 | $context = new Context(); 31 | $context->remoteAddress = '127.0.0.1'; 32 | 33 | $this->assertTrue($strategy->isEnabled($params, $context)); 34 | } 35 | 36 | public function testNotEnabledForIpNotInList() 37 | { 38 | $strategy = new RemoteAddressStrategy(); 39 | $params = ['IPs' => '127.0.1.1, 127.0.1.2, 127.0.1.3']; 40 | $context = new Context(); 41 | $context->remoteAddress = '127.0.1.5'; 42 | 43 | $this->assertFalse($strategy->isEnabled($params, $context)); 44 | } 45 | 46 | public function testEnabledForIpInList() 47 | { 48 | $strategy = new RemoteAddressStrategy(); 49 | $params = ['IPs' => '127.0.1.1, 127.0.1.2,127.0.1.3']; 50 | $context = new Context(); 51 | $context->remoteAddress = '127.0.1.2'; 52 | 53 | $this->assertTrue($strategy->isEnabled($params, $context)); 54 | } 55 | 56 | public function testEnabledForIpInsideRangeInAList() 57 | { 58 | $strategy = new RemoteAddressStrategy(); 59 | $params = ['IPs' => '127.0.1.1, 127.0.1.2,127.0.1.3, 160.33.0.0/16']; 60 | $context = new Context(); 61 | $context->remoteAddress = '160.33.0.33'; 62 | 63 | $this->assertTrue($strategy->isEnabled($params, $context)); 64 | } 65 | 66 | public function testInvalidIp() 67 | { 68 | $strategy = new RemoteAddressStrategy(); 69 | $params = ['IPs' => '127.invalid']; 70 | $context = new Context(); 71 | $context->remoteAddress = '127.0.0.1'; 72 | 73 | $this->assertFalse($strategy->isEnabled($params, $context)); 74 | } 75 | 76 | public function testInvalidIps() 77 | { 78 | $strategy = new RemoteAddressStrategy(); 79 | $params = ['IPs' => '127.0.0.2, 127.invalid, 127.0.0.1']; 80 | $context = new Context(); 81 | $context->remoteAddress = '127.0.0.1'; 82 | 83 | $this->assertTrue($strategy->isEnabled($params, $context)); 84 | } 85 | } -------------------------------------------------------------------------------- /tests/Strategy/UserWithIdStrategyTest.php: -------------------------------------------------------------------------------- 1 | assertEquals('userWithId', $strategy->name); 15 | } 16 | 17 | public function testEnabledForUserId() 18 | { 19 | $strategy = new UserWithIdStrategy(); 20 | $params = ['userIds' => '123']; 21 | $context = new Context(); 22 | $context->userId = '123'; 23 | 24 | $this->assertTrue($strategy->isEnabled($params, $context)); 25 | } 26 | 27 | public function testEnabledForUserIdInList() 28 | { 29 | $strategy = new UserWithIdStrategy(); 30 | $params = ['userIds' => '123, 122, 12312312']; 31 | $context = new Context(); 32 | $context->userId = '12312312'; 33 | 34 | $this->assertTrue($strategy->isEnabled($params, $context)); 35 | } 36 | 37 | public function testNotEnabledForUserIdNotInList() 38 | { 39 | $strategy = new UserWithIdStrategy(); 40 | $params = ['userIds' => '123, 122, 122']; 41 | $context = new Context(); 42 | $context->userId = '12'; 43 | 44 | $this->assertFalse($strategy->isEnabled($params, $context)); 45 | } 46 | 47 | public function testEnabledForUserIdInListNoSpaces() 48 | { 49 | $strategy = new UserWithIdStrategy(); 50 | $params = ['userIds' => '123, 122, 12312312']; 51 | $context = new Context(); 52 | $context->userId = '122'; 53 | 54 | $this->assertTrue($strategy->isEnabled($params, $context)); 55 | } 56 | } -------------------------------------------------------------------------------- /tests/UnleashClientTest.php: -------------------------------------------------------------------------------- 1 | assertEquals(2, $amountOfExceptions); 32 | } 33 | 34 | public function testShouldUseProvideRepository() 35 | { 36 | $repo = $this->createMock(Repository::class); 37 | $repo->method('getToggle') 38 | ->willReturn($this->createFeature('feature', true)); 39 | $client = new UnleashClient($repo, [new Strategy('default', true)]); 40 | $result = $client->isEnabled('feature'); 41 | 42 | $this->assertTrue($result); 43 | } 44 | 45 | public function testShouldFallbackWhenMissingFeature() 46 | { 47 | $repo = $this->createMock(Repository::class); 48 | $repo->method('getToggle') 49 | ->willReturn(null); 50 | $client = new UnleashClient($repo, [new Strategy('default', true)]); 51 | $result = $client->isEnabled('feature-x', null); 52 | $this->assertFalse($result); 53 | $result = $client->isEnabled('feature-x', null, true); 54 | $this->assertTrue($result); 55 | } 56 | 57 | public function testShouldConsiderToggleNotActive() 58 | { 59 | $repo = $this->createMock(Repository::class); 60 | $repo->method('getToggle') 61 | ->willReturn($this->createFeature('feature', false)); 62 | $client = new UnleashClient($repo, [new Strategy('default', true)]); 63 | $result = $client->isEnabled('feature'); 64 | $this->assertFalse($result); 65 | } 66 | 67 | public function testShouldUserCustomStrategy() 68 | { 69 | $repo = $this->createMock(Repository::class); 70 | $repo->method('getToggle') 71 | ->willReturn($this->createFeature('feature', true, [new Strategy('custom')])); 72 | $client = new UnleashClient($repo, [new Strategy('default', true), new CustomStrategy()]); 73 | $result = $client->isEnabled('feature'); 74 | $this->assertTrue($result); 75 | } 76 | 77 | public function testShouldUseASetOfCustomStrategies() 78 | { 79 | $this->markTestSkipped('Broken, needs fix'); 80 | $repo = $this->createMock(Repository::class); 81 | $repo->method('getToggle') 82 | ->willReturn($this->createFeature('feature', true, [new Strategy('custom-false'), new Strategy('custom')])); 83 | $strategies = [new CustomFalseStrategy(), new CustomStrategy()]; 84 | $client = new UnleashClient($repo, $strategies); 85 | $result = $client->isEnabled('feature'); 86 | 87 | $this->assertTrue($result); 88 | } 89 | 90 | public function testShouldReturnFalseASetOfCustomFalseStrategies() 91 | { 92 | $repo = $this->createMock(Repository::class); 93 | $repo->method('getToggle') 94 | ->willReturn($this->createFeature('feature', true, [ 95 | new Strategy('custom-false'), 96 | new Strategy('custom-false'), 97 | ])); 98 | 99 | $strategies = [new CustomFalseStrategy(), new CustomStrategy()]; 100 | $client = new UnleashClient($repo, $strategies); 101 | $result = $client->isEnabled('feature'); 102 | 103 | $this->assertFalse($result); 104 | } 105 | 106 | public function testShouldEmitErrorWhenInvalidFeatureRuntime() 107 | { 108 | $repo = $this->createMock(Repository::class); 109 | $repo->method('getToggle') 110 | ->willReturn($this->createFeature('feature-wrong-strategy', true, [new Strategy('non-existent')])); 111 | $client = new UnleashClient($repo, []); 112 | $amountOfEvents = 0; 113 | $client->addListener('warn', function (WarnEvent $warnEvent) use (&$amountOfEvents){ 114 | $this->assertContains('Missing strategy', $warnEvent->getMessage()); 115 | $amountOfEvents++; 116 | }); 117 | 118 | $this->assertFalse($client->isEnabled('feature-strong-strategy')); 119 | $this->assertEquals(1, $amountOfEvents); 120 | } 121 | 122 | public function createFeature(string $name, bool $enabled, array $strategies = []) 123 | { 124 | if (empty($strategies)) { 125 | $strategies = [ 126 | new Strategy('default'), 127 | ]; 128 | } 129 | 130 | $feature = new Feature($name, $enabled); 131 | $feature->strategies = $strategies; 132 | 133 | return $feature; 134 | } 135 | } 136 | 137 | class CustomStrategy extends Strategy 138 | { 139 | public function __construct(string $name = 'unknown', bool $returnValue = false) 140 | { 141 | parent::__construct('custom'); 142 | } 143 | 144 | public function isEnabled(array $parameters = null, Context $context = null): bool 145 | { 146 | return true; 147 | } 148 | } 149 | 150 | class CustomFalseStrategy extends Strategy 151 | { 152 | public function __construct(string $name = 'unknown', bool $returnValue = false) 153 | { 154 | parent::__construct('custom-false'); 155 | } 156 | 157 | public function isEnabled(array $parameters = null, Context $context = null): bool 158 | { 159 | return false; 160 | } 161 | } -------------------------------------------------------------------------------- /tests/UnleashTest.php: -------------------------------------------------------------------------------- 1 | 'feature', 25 | 'enabled' => true, 26 | 'strategy' => 'default' 27 | ]; 28 | } 29 | 30 | $mock = new MockHandler([ 31 | new Response(200, [], json_encode(['features' => $toggles])) 32 | ]); 33 | 34 | $client = new Client(['handler' => HandlerStack::create($mock)]); 35 | return $client; 36 | } 37 | 38 | public function testShouldHandleOldUrl() 39 | { 40 | $instance = new \Unleash\Unleash(); 41 | $instance->addListener('warn', function (WarnEvent $event) { 42 | $this->assertNotNull($event); 43 | }); 44 | 45 | $instance->initialize('foo', 46 | 'http://test.nl/client/features', 47 | null, 48 | 0, 49 | 0, 50 | true 51 | ); 52 | 53 | 54 | $instance->destroy(); 55 | } 56 | 57 | public function testShouldHandleUrlWithoutEndingSlash() 58 | { 59 | $baseUrl = 'http://ttest.app/api'; 60 | $instance = new \Unleash\Unleash(); 61 | $instance->addListener('warn', function (WarnEvent $event) { 62 | $this->assertNotNull($event); 63 | }); 64 | 65 | $instance->initialize('foo', 66 | $baseUrl, 67 | null, 68 | 0, 69 | 0, 70 | true 71 | ); 72 | 73 | $this->assertAttributeEquals($baseUrl . '/', 'url', Assert::readAttribute($instance, 'repository')); 74 | } 75 | 76 | public function testReEmitErrorForRepoStorageAndMetrics() 77 | { 78 | $baseUrl = 'http://ttest.app/api'; 79 | $instance = new \Unleash\Unleash(); 80 | $amountOfErrors = 0; 81 | $instance->addListener('error', function (ErrorEvent $event) use (&$amountOfErrors) { 82 | $this->assertNotNull($event); 83 | $amountOfErrors++; 84 | }); 85 | 86 | $instance->initialize('foo', 87 | $baseUrl, 88 | null, 89 | 0, 90 | 0, 91 | true 92 | ); 93 | Assert::readAttribute($instance, 'repository')->dispatch('error', new ErrorEvent(['message' => 'error'])); 94 | Assert::readAttribute($instance, 'metrics')->dispatch('error', new ErrorEvent(['message' => 'error'])); 95 | Assert::readAttribute(Assert::readAttribute($instance, 'repository'), 'storage')->dispatch('error', new ErrorEvent(['message' => 'error'])); 96 | 97 | 98 | $this->assertEquals(3, $amountOfErrors); 99 | } 100 | 101 | public function testReEmitEventsFromRepositoryAndMetrics() 102 | { 103 | $baseUrl = 'http://ttest.app/api'; 104 | $instance = new \Unleash\Unleash(); 105 | $amountOfEvents = 0; 106 | $instance->addListener('warn', function (WarnEvent $event) use (&$amountOfEvents) { 107 | $this->assertNotNull($event); 108 | $amountOfEvents++; 109 | }); 110 | $instance->addListener('sent', function (SentEvent $event) use (&$amountOfEvents) { 111 | $this->assertNotNull($event); 112 | $amountOfEvents++; 113 | }); 114 | $instance->addListener('registered', function (RegisterEvent $event) use (&$amountOfEvents) { 115 | $this->assertNotNull($event); 116 | $amountOfEvents++; 117 | }); 118 | $instance->addListener('count', function (CountEvent $event) use (&$amountOfEvents) { 119 | $this->assertNotNull($event); 120 | $amountOfEvents++; 121 | }); 122 | 123 | $instance->initialize('foo', 124 | $baseUrl, 125 | null, 126 | 0, 127 | 0, 128 | true 129 | ); 130 | Assert::readAttribute($instance, 'repository')->dispatch('warn', new WarnEvent([])); 131 | Assert::readAttribute($instance, 'metrics')->dispatch('warn', new WarnEvent([])); 132 | Assert::readAttribute($instance, 'metrics')->dispatch('sent', new SentEvent([])); 133 | Assert::readAttribute($instance, 'metrics')->dispatch('registered', new RegisterEvent([])); 134 | Assert::readAttribute($instance, 'metrics')->dispatch('count', new CountEvent('test', true)); 135 | 136 | 137 | $this->assertEquals(5, $amountOfEvents); 138 | } 139 | 140 | public function testRepositoryShouldSurfaceErrorWhenInvalidBasePath() 141 | { 142 | $baseUrl = 'http://unleash-surface.app//client/features'; 143 | $instance = new \Unleash\Unleash(); 144 | 145 | $amountOfEvents = 0; 146 | $instance->addListener('error', function (ErrorEvent $event) use (&$amountOfEvents){ 147 | $this->assertContains('failed to open stream: No such file or directory', $event->getError()['message']); 148 | $amountOfEvents++; 149 | }); 150 | 151 | $mock = new MockHandler([ 152 | new Response(200, [], json_encode(['features' => []])) 153 | ]); 154 | 155 | $client = new Client(['handler' => HandlerStack::create($mock)]); 156 | $backupPath = sys_get_temp_dir() . '/test-tmp'; 157 | 158 | $instance->initialize('foo', 159 | $baseUrl, 160 | null, 161 | 0, 162 | 0, 163 | true, 164 | $backupPath, 165 | [], 166 | [], 167 | $client 168 | ); 169 | $instance->fetch(); 170 | 171 | $this->assertEquals(1, $amountOfEvents); 172 | } 173 | 174 | public function testShouldAllowRequestEvenBeforeUnleashIsInitialized() 175 | { 176 | $client = $this->mockNetwork(); 177 | $instance = new Unleash(); 178 | $instance->initialize( 179 | 'foo', 180 | 'http://testurl.com', 181 | null, 182 | 0, 183 | 0, 184 | true, 185 | '', 186 | [], 187 | [], 188 | $client 189 | ); 190 | $instance->fetch(); 191 | $this->assertFalse($instance->isEnabled('unknown')); 192 | $instance->destroy(); 193 | } 194 | 195 | public function testShouldConsiderKnownFeatureToggleAsActive() 196 | { 197 | $client = $this->mockNetwork(); 198 | $instance = new Unleash(); 199 | $amountOfEvents = 0; 200 | $instance->addListener('ready', function () use ($instance, &$amountOfEvents){ 201 | $this->assertTrue($instance->isEnabled('feature')); 202 | $instance->destroy(); 203 | $amountOfEvents++; 204 | }); 205 | $instance->initialize( 206 | 'foo', 207 | 'url', 208 | null, 209 | 0, 210 | 0, 211 | true, 212 | '', 213 | [], 214 | [], 215 | $client 216 | ); 217 | $instance->fetch(); 218 | 219 | $this->assertEquals(1, $amountOfEvents); 220 | } 221 | 222 | public function testShouldConsiderUnknownFeatureToggleAsDisabled() 223 | { 224 | $client = $this->mockNetwork(); 225 | $instance = new Unleash(); 226 | $amountOfEvents = 0; 227 | $instance->addListener('ready', function () use($instance, &$amountOfEvents){ 228 | $this->assertFalse($instance->isEnabled('unknown')); 229 | $instance->destroy(); 230 | $amountOfEvents++; 231 | }); 232 | 233 | $instance->initialize( 234 | 'foo', 235 | 'url', 236 | null, 237 | 0, 238 | 0, 239 | true, 240 | '', 241 | [], 242 | [], 243 | $client 244 | ); 245 | $instance->fetch(); 246 | 247 | $this->assertEquals(1, $amountOfEvents); 248 | } 249 | 250 | public function testShouldReturnFallbackValueUntilOnline() 251 | { 252 | $client = $this->mockNetwork(); 253 | $instance = new Unleash(); 254 | $amountOfEvents = 0; 255 | $amountOfWarnings = 0; 256 | $instance->addListener('warn', function (WarnEvent $event) use (&$amountOfEvents, &$amountOfWarnings){ 257 | var_dump($event); 258 | $amountOfEvents++; 259 | $amountOfWarnings++; 260 | }); 261 | $instance->addListener('ready', function () use (&$amountOfEvents, $instance){ 262 | $amountOfEvents++; 263 | $this->assertTrue($instance->isEnabled('feature')); 264 | $this->assertTrue($instance->isEnabled('feature', null, false)); 265 | $instance->destroy(); 266 | }); 267 | 268 | $instance->initialize( 269 | 'foo', 270 | 'http://url.com', 271 | null, 272 | 0, 273 | 0, 274 | true, 275 | '', 276 | [], 277 | [], 278 | $client 279 | ); 280 | 281 | 282 | $this->assertFalse($instance->isEnabled('feature')); 283 | $this->assertEquals(1, $amountOfWarnings); 284 | $this->assertFalse($instance->isEnabled('feature', null, false)); 285 | $this->assertTrue($instance->isEnabled('feature', null, true)); 286 | $this->assertEquals(3, $amountOfWarnings); 287 | 288 | $instance->fetch(); 289 | 290 | $this->assertEquals(4, $amountOfEvents); 291 | } 292 | } 293 | -------------------------------------------------------------------------------- /tests/Utils/NormalizerTest.php: -------------------------------------------------------------------------------- 1 | assertEquals(73, normalizeValue('123','gr1')); 11 | $this->assertEquals(25, normalizeValue('999','groupX')); 12 | } 13 | } --------------------------------------------------------------------------------