diff --git a/.travis.yml b/.travis.yml index dbace1c1..559b709b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -6,29 +6,34 @@ php: - '7.1' - '7.2' - '7.3' -before_install: -- composer install --dev +install: "composer install" addons: srcclr: true script: - mkdir -p build/logs - ./vendor/bin/phpunit --coverage-clover build/logs/clover.xml -after_script: -- vendor/bin/php-coveralls -v +after_script: "vendor/bin/php-coveralls -v" -# Integration tests need to run first to reset the PR build status to pending +# Linting and integration tests need to run first to reset the PR build status to pending stages: + - 'Linting' - 'Integration tests' - 'Test' jobs: include: + - stage: 'Linting' + language: php + php: '7.0' + install: 'composer require "squizlabs/php_codesniffer=*"' + script: 'composer lint' + after_script: skip + after_success: travis_terminate 0 - stage: 'Integration tests' merge_mode: replace env: SDK=php cache: false language: python - before_install: skip install: - "pip install awscli" before_script: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 29b5b27e..a5cee8eb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -17,6 +17,11 @@ We welcome contributions and feedback! All contributors must sign our [Contribut * **All code must have test coverage.** We use PHPUnit. Changes in functionality should have accompanying unit tests. Bug fixes should have accompanying regression tests. * Tests are located in `tests` with one file per class. +* Lint your code with PHP CodeSniffer before submitting. + +## Style +We enforce [PSR-2](https://www.php-fig.org/psr/psr-2/) rules with some minor [deviations](phpcs.xml). Run linter by executing `composer lint` and autocorrect lint errors by executing `composer beautify`. + ## License diff --git a/composer.json b/composer.json index 1e43c5e0..2e8dc56b 100644 --- a/composer.json +++ b/composer.json @@ -9,6 +9,11 @@ "email": "developers@optimizely.com" } ], + "scripts": { + "test": "phpunit", + "lint": "phpcs", + "beautify": "phpcbf" + }, "require": { "php": ">=5.5", "justinrainbow/json-schema": "^1.6 || ^2.0 || ^4.0 || ^5.0", @@ -19,7 +24,8 @@ }, "require-dev": { "phpunit/phpunit": "^4.8|^5.0", - "php-coveralls/php-coveralls": "v2.0.0" + "php-coveralls/php-coveralls": "v2.0.0", + "squizlabs/php_codesniffer": "3.*" }, "autoload": { "psr-4": { diff --git a/phpcs.xml b/phpcs.xml new file mode 100644 index 00000000..bcb3deb4 --- /dev/null +++ b/phpcs.xml @@ -0,0 +1,23 @@ +<?xml version="1.0"?> +<ruleset name="OptimizelyPSR2"> + <!-- description for custom ruleset --> + <description>A custom coding standard for Optimizely PHP-SDK based on PSR2</description> + + <!-- If no files or directories are specified on commandline, these files will be sniffed --> + <file>./src</file> + <file>./tests</file> + + <!-- Exclude patterns for files to be excluded from sniffing --> + <!-- <exclude-pattern>./tests/EventTests/*</exclude-pattern> --> + + <!-- Embed command line arguments in config file. --> + <arg name="tab-width" value="4"/> + + <!-- To exclude any rule sniff, get sniff name by running phpcs with -s switch --> + <rule ref="PSR2"> + <exclude name="Generic.Files.LineLength.TooLong"/> + <exclude name="PSR2.Classes.PropertyDeclaration.Underscore"/> + <exclude name="PSR1.Classes.ClassDeclaration.MultipleClasses"/> + <exclude name="PSR1.Files.SideEffects.FoundWithSymbols"/> + </rule > +</ruleset> diff --git a/src/Optimizely/Bucketer.php b/src/Optimizely/Bucketer.php index 64f9292c..c73b2093 100644 --- a/src/Optimizely/Bucketer.php +++ b/src/Optimizely/Bucketer.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2016-2018, Optimizely + * Copyright 2016-2019, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -90,9 +90,9 @@ protected function generateBucketValue($bucketingKey) /* murmurhash3_int returns both positive and negative integers for PHP x86 versions it returns negative integers when it tries to create 2^32 integers while PHP doesn't support - unsigned integers and can store integers only upto 2^31. + unsigned integers and can store integers only upto 2^31. Observing generated hashcodes and their corresponding bucket values after normalization - indicates that a negative bucket number on x86 is exactly 10,000 less than it's + indicates that a negative bucket number on x86 is exactly 10,000 less than it's corresponding bucket number on x64. Hence we can safely add 10,000 to a negative number to make it consistent across both of the PHP variants. */ diff --git a/src/Optimizely/DecisionService/DecisionService.php b/src/Optimizely/DecisionService/DecisionService.php index 568e4c19..f674f2a8 100644 --- a/src/Optimizely/DecisionService/DecisionService.php +++ b/src/Optimizely/DecisionService/DecisionService.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2017-2018, Optimizely Inc and Contributors + * Copyright 2017-2019, Optimizely Inc and Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -93,8 +93,8 @@ protected function getBucketingId($userId, $userAttributes) { $bucketingIdKey = ControlAttributes::BUCKETING_ID; - if (isset($userAttributes[$bucketingIdKey])){ - if (is_string($userAttributes[$bucketingIdKey])){ + if (isset($userAttributes[$bucketingIdKey])) { + if (is_string($userAttributes[$bucketingIdKey])) { return $userAttributes[$bucketingIdKey]; } $this->_logger->log(Logger::WARNING, 'Bucketing ID attribute is not a string. Defaulted to user ID.'); @@ -308,7 +308,7 @@ public function getVariationForFeatureRollout(FeatureFlag $featureFlag, $userId, break; } // Evaluate Everyone Else Rule / Last Rule now - $experiment = $rolloutRules[sizeof($rolloutRules)-1]; + $experiment = $rolloutRules[sizeof($rolloutRules)-1]; // Evaluate if user meets the audience condition of Everyone Else Rule / Last Rule now if (!Validator::isUserInExperiment($this->_projectConfig, $experiment, $userAttributes)) { diff --git a/src/Optimizely/Entity/Experiment.php b/src/Optimizely/Entity/Experiment.php index 32671a25..0099aeec 100644 --- a/src/Optimizely/Entity/Experiment.php +++ b/src/Optimizely/Entity/Experiment.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2016, 2018, Optimizely + * Copyright 2016, 2018-2019, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -78,7 +78,7 @@ class Experiment /** * @var array/string Single audience ID the experiment is attached to or - * hierarchical conditions array of audience IDs related by AND/OR/NOT operators. + * hierarchical conditions array of audience IDs related by AND/OR/NOT operators. */ private $_audienceConditions; diff --git a/src/Optimizely/Entity/FeatureVariable.php b/src/Optimizely/Entity/FeatureVariable.php index 05546ed0..e41e4d9a 100644 --- a/src/Optimizely/Entity/FeatureVariable.php +++ b/src/Optimizely/Entity/FeatureVariable.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2017, Optimizely + * Copyright 2017, 2019, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,7 +61,7 @@ class FeatureVariable private $_defaultValue; - public function __construct($id =null, $key = null, $type = null, $defaultValue = null) + public function __construct($id = null, $key = null, $type = null, $defaultValue = null) { $this->_id = $id; $this->_key = $key; diff --git a/src/Optimizely/Entity/Variation.php b/src/Optimizely/Entity/Variation.php index 53f5fa1f..4e338450 100644 --- a/src/Optimizely/Entity/Variation.php +++ b/src/Optimizely/Entity/Variation.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2016-2018, Optimizely + * Copyright 2016-2019, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -115,7 +115,7 @@ public function getVariables() } /** - * @param string Variable ID + * @param string Variable ID * * @return VariableUsage Variable usage instance corresponding to given variable ID */ diff --git a/src/Optimizely/Event/Builder/EventBuilder.php b/src/Optimizely/Event/Builder/EventBuilder.php index c8fbdcd5..f2c56de8 100644 --- a/src/Optimizely/Event/Builder/EventBuilder.php +++ b/src/Optimizely/Event/Builder/EventBuilder.php @@ -100,7 +100,7 @@ private function getCommonParams($config, $userId, $attributes) ENRICH_DECISIONS => true ]; - if(!is_null($attributes)) { + if (!is_null($attributes)) { foreach ($attributes as $attributeKey => $attributeValue) { // Omit attributes that are not supported by the log endpoint. if (Validator::isAttributeValid($attributeKey, $attributeValue)) { @@ -199,7 +199,7 @@ private function getConversionParams($eventEntity, $eventTags) $eventDict[EventTagUtils::NUMERIC_EVENT_METRIC_NAME] = $eventValue; } - if(count($eventTags) > 0) { + if (count($eventTags) > 0) { $eventDict['tags'] = $eventTags; } } diff --git a/src/Optimizely/Event/Builder/Params.php b/src/Optimizely/Event/Builder/Params.php index 2db3926a..dd66c56c 100644 --- a/src/Optimizely/Event/Builder/Params.php +++ b/src/Optimizely/Event/Builder/Params.php @@ -26,7 +26,7 @@ define('DECISIONS', 'decisions'); define('ENRICH_DECISIONS', 'enrich_decisions'); define('ENTITY_ID', 'entity_id'); -define('EVENTS', 'events');; +define('EVENTS', 'events'); define('EXPERIMENT_ID', 'experiment_id'); define('KEY', 'key'); define('PROJECT_ID', 'project_id'); diff --git a/src/Optimizely/Logger/DefaultLogger.php b/src/Optimizely/Logger/DefaultLogger.php index ea7b2b62..945d8265 100644 --- a/src/Optimizely/Logger/DefaultLogger.php +++ b/src/Optimizely/Logger/DefaultLogger.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2016,2018 Optimizely + * Copyright 2016, 2018-2019 Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,8 +35,8 @@ class DefaultLogger implements LoggerInterface /** * DefaultLogger constructor. * - * @param int $minLevel Minimum level of messages to be logged. - * @param string $stream The PHP stream to log output. + * @param int $minLevel Minimum level of messages to be logged. + * @param string $stream The PHP stream to log output. */ public function __construct($minLevel = Logger::INFO, $stream = "stdout") { diff --git a/src/Optimizely/Notification/NotificationCenter.php b/src/Optimizely/Notification/NotificationCenter.php index ede0a1d7..6a01451a 100644 --- a/src/Optimizely/Notification/NotificationCenter.php +++ b/src/Optimizely/Notification/NotificationCenter.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2017-2018, Optimizely Inc and Contributors + * Copyright 2017-2019, Optimizely Inc and Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,7 +58,7 @@ public function getNotifications() /** * Adds a notification callback for a notification type to the notification center * - * @param string $notification_type One of the constants defined in NotificationType + * @param string $notification_type One of the constants defined in NotificationType * @param callable $notification_callback A valid PHP callback * * @return null Given invalid notification type/callback @@ -122,12 +122,13 @@ public function removeNotificationListener($notification_id) * * @deprecated Use 'clearNotificationListeners' instead. */ - public function clearNotifications($notification_type){ - $this->_logger->log( - Logger::WARNING, - "'clearNotifications' is deprecated. Call 'clearNotificationListeners' instead." - ); - $this->clearNotificationListeners($notification_type); + public function clearNotifications($notification_type) + { + $this->_logger->log( + Logger::WARNING, + "'clearNotifications' is deprecated. Call 'clearNotificationListeners' instead." + ); + $this->clearNotificationListeners($notification_type); } /** @@ -152,12 +153,13 @@ public function clearNotificationListeners($notification_type) * * @deprecated Use 'clearAllNotificationListeners' instead. */ - public function cleanAllNotifications(){ - $this->_logger->log( - Logger::WARNING, - "'cleanAllNotifications' is deprecated. Call 'clearAllNotificationListeners' instead." - ); - $this->clearAllNotificationListeners(); + public function cleanAllNotifications() + { + $this->_logger->log( + Logger::WARNING, + "'cleanAllNotifications' is deprecated. Call 'clearAllNotificationListeners' instead." + ); + $this->clearAllNotificationListeners(); } /** diff --git a/src/Optimizely/Optimizely.php b/src/Optimizely/Optimizely.php index 0fd3c8a8..58251f4b 100644 --- a/src/Optimizely/Optimizely.php +++ b/src/Optimizely/Optimizely.php @@ -265,7 +265,7 @@ public function activate($experimentKey, $userId, $attributes = null) self::EXPERIMENT_KEY =>$experimentKey, self::USER_ID => $userId ] - ) + ) ) { return null; } @@ -301,7 +301,7 @@ public function track($eventKey, $userId, $attributes = null, $eventTags = null) self::EVENT_KEY =>$eventKey, self::USER_ID => $userId ] - ) + ) ) { return null; } @@ -389,7 +389,7 @@ public function getVariation($experimentKey, $userId, $attributes = null) self::EXPERIMENT_KEY =>$experimentKey, self::USER_ID => $userId ] - ) + ) ) { return null; } @@ -484,7 +484,7 @@ public function isFeatureEnabled($featureFlagKey, $userId, $attributes = null) self::FEATURE_FLAG_KEY =>$featureFlagKey, self::USER_ID => $userId ] - ) + ) ) { return false; } @@ -539,7 +539,7 @@ public function getEnabledFeatures($userId, $attributes = null) [ self::USER_ID => $userId ] - ) + ) ) { return $enabledFeatureKeys; } @@ -584,7 +584,7 @@ public function getFeatureVariableValueForType( self::VARIABLE_KEY => $variableKey, self::USER_ID => $userId ] - ) + ) ) { return null; } diff --git a/src/Optimizely/ProjectConfig.php b/src/Optimizely/ProjectConfig.php index 4ae69616..927c483a 100644 --- a/src/Optimizely/ProjectConfig.php +++ b/src/Optimizely/ProjectConfig.php @@ -196,7 +196,7 @@ public function __construct($datafile, $logger, $errorHandler) $this->_logger = $logger; $this->_errorHandler = $errorHandler; $this->_version = $config['version']; - if(!in_array($this->_version, $supportedVersions)){ + if (!in_array($this->_version, $supportedVersions)) { throw new InvalidDatafileVersionException( "This version of the PHP SDK does not support the given datafile version: {$this->_version}." ); @@ -256,7 +256,7 @@ public function __construct($datafile, $logger, $errorHandler) } // Conditions in typedAudiences are not expected to be string-encoded so they don't need - // to be decoded unlike audiences. + // to be decoded unlike audiences. foreach (array_values($typedAudienceIdMap) as $typedAudience) { $typedAudience->setConditionsList($typedAudience->getConditions()); } @@ -402,7 +402,7 @@ public function getExperimentFromId($experimentId) } /** - * @param String $featureKey Key of the feature flag + * @param String $featureKey Key of the feature flag * * @return FeatureFlag Entity corresponding to the key. */ @@ -418,7 +418,7 @@ public function getFeatureFlagFromKey($featureKey) } /** - * @param String $rolloutId + * @param String $rolloutId * * @return Rollout */ @@ -577,8 +577,6 @@ public function getFeatureVariableFromKey($featureFlagKey, $variableKey) $this->_logger->log( Logger::ERROR, - - sprintf( 'No variable key "%s" defined in datafile for feature flag "%s".', $variableKey, diff --git a/src/Optimizely/Utils/ConditionTreeEvaluator.php b/src/Optimizely/Utils/ConditionTreeEvaluator.php index 311f8239..32406a08 100644 --- a/src/Optimizely/Utils/ConditionTreeEvaluator.php +++ b/src/Optimizely/Utils/ConditionTreeEvaluator.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2018, Optimizely + * Copyright 2018-2019, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,7 @@ class ConditionTreeEvaluator /** * Returns an array of supported operators. - * + * * @return array List of operators. */ protected function getOperators() @@ -35,9 +35,9 @@ protected function getOperators() /** * Returns corresponding evaluator method name for the given operator. - * - * @param mixed $operator Operator to get relevant evaluator method. - * + * + * @param mixed $operator Operator to get relevant evaluator method. + * * @return string Corresponding method to the given operator. */ protected function getEvaluatorByOperatorType($operator) @@ -53,9 +53,9 @@ protected function getEvaluatorByOperatorType($operator) /** * Evaluates an array of conditions as if the evaluator had been applied * to each entry and the results AND-ed together. - * - * @param array $conditions Audience conditions list. - * @param callable $leafEvaluator Method to evaluate leaf condition. + * + * @param array $conditions Audience conditions list. + * @param callable $leafEvaluator Method to evaluate leaf condition. * * @return null|boolean True if all the operands evaluate to true. * False if a single operand evaluates to false. @@ -67,11 +67,11 @@ protected function andEvaluator(array $conditions, callable $leafEvaluator) foreach ($conditions as $condition) { $result = $this->evaluate($condition, $leafEvaluator); - if($result === false) { + if ($result === false) { return false; } - if($result === null) { + if ($result === null) { $sawNullResult = true; } } @@ -82,9 +82,9 @@ protected function andEvaluator(array $conditions, callable $leafEvaluator) /** * Evaluates an array of conditions as if the evaluator had been applied * to each entry and the results OR-ed together. - * - * @param array $conditions Audience conditions list. - * @param callable $leafEvaluator Method to evaluate leaf condition. + * + * @param array $conditions Audience conditions list. + * @param callable $leafEvaluator Method to evaluate leaf condition. * * @return null|boolean True if any operand evaluates to true. * False if all operands evaluate to false. @@ -96,11 +96,11 @@ protected function orEvaluator(array $conditions, callable $leafEvaluator) foreach ($conditions as $condition) { $result = $this->evaluate($condition, $leafEvaluator); - if($result === true) { + if ($result === true) { return true; } - if($result === null) { + if ($result === null) { $sawNullResult = true; } } @@ -111,9 +111,9 @@ protected function orEvaluator(array $conditions, callable $leafEvaluator) /** * Evaluates an array of conditions as if the evaluator had been applied * to a single entry and NOT was applied to the result. - * - * @param array $conditions Audience conditions list. - * @param callable $leafEvaluator Method to evaluate leaf condition. + * + * @param array $conditions Audience conditions list. + * @param callable $leafEvaluator Method to evaluate leaf condition. * * @return null|boolean True if the operand evaluates to false. * False if the operand evaluates to true. @@ -132,8 +132,8 @@ protected function notEvaluator(array $condition, callable $leafEvaluator) /** * Function to evaluate audience conditions against user's attributes. * - * @param array $conditions Nested array of and/or/not conditions representing the audience conditions. - * @param callable $leafEvaluator Method to evaluate leaf condition. + * @param array $conditions Nested array of and/or/not conditions representing the audience conditions. + * @param callable $leafEvaluator Method to evaluate leaf condition. * * @return null|boolean Result of evaluating the conditions using the operator rules. * and the leaf evaluator. Null if conditions couldn't be evaluated. @@ -141,14 +141,13 @@ protected function notEvaluator(array $condition, callable $leafEvaluator) public function evaluate($conditions, callable $leafEvaluator) { // When parsing audiences tree the leaf node is a string representing an audience ID. - // When parsing conditions of a single audience the leaf node is an associative array with all keys of type string. + // When parsing conditions of a single audience the leaf node is an associative array with all keys of type string. if (is_string($conditions) || Validator::doesArrayContainOnlyStringKeys($conditions)) { - $leafCondition = $conditions; return $leafEvaluator($leafCondition); } - if(in_array($conditions[0], $this->getOperators())) { + if (in_array($conditions[0], $this->getOperators())) { $operator = array_shift($conditions); } else { $operator = self::OR_OPERATOR; diff --git a/src/Optimizely/Utils/CustomAttributeConditionEvaluator.php b/src/Optimizely/Utils/CustomAttributeConditionEvaluator.php index 1ead3749..ed5a4b53 100644 --- a/src/Optimizely/Utils/CustomAttributeConditionEvaluator.php +++ b/src/Optimizely/Utils/CustomAttributeConditionEvaluator.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2018, Optimizely + * Copyright 2018-2019, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,12 +31,12 @@ class CustomAttributeConditionEvaluator /** * @var UserAttributes - */ + */ protected $userAttributes; /** * CustomAttributeConditionEvaluator constructor - * + * * @param array $userAttributes Associative array of user attributes to values. */ public function __construct(array $userAttributes) @@ -46,13 +46,13 @@ public function __construct(array $userAttributes) /** * Sets null for missing keys in a leaf condition. - * + * * @param array $leafCondition The leaf condition node of an audience. */ protected function setNullForMissingKeys(array $leafCondition) { $keys = ['type', 'match', 'value']; - foreach($keys as $key) { + foreach ($keys as $key) { $leafCondition[$key] = isset($leafCondition[$key]) ? $leafCondition[$key]: null; } @@ -61,7 +61,7 @@ protected function setNullForMissingKeys(array $leafCondition) /** * Gets the supported match types for condition evaluation. - * + * * @return array List of supported match types. */ protected function getMatchTypes() @@ -72,9 +72,9 @@ protected function getMatchTypes() /** * Gets the evaluator method name for the given match type. - * - * @param string $matchType Match type for which to get evaluator. - * + * + * @param string $matchType Match type for which to get evaluator. + * * @return string Corresponding evaluator method name. */ protected function getEvaluatorByMatchType($matchType) @@ -91,14 +91,14 @@ protected function getEvaluatorByMatchType($matchType) /** * Checks if the given input is a valid value for exact condition evaluation. - * - * @param $value Input to check. - * + * + * @param $value Input to check. + * * @return boolean true if given input is a string/boolean/finite number, false otherwise. */ protected function isValueValidForExactConditions($value) { - if(is_string($value) || is_bool($value) || Validator::isFiniteNumber($value)) { + if (is_string($value) || is_bool($value) || Validator::isFiniteNumber($value)) { return true; } @@ -107,9 +107,9 @@ protected function isValueValidForExactConditions($value) /** * Evaluate the given exact match condition for the given user attributes. - * - * @param object $condition - * + * + * @param object $condition + * * @return null|boolean true if the user attribute value is equal (===) to the condition value, * false if the user attribute value is not equal (!==) to the condition value, * null if the condition value or user attribute value has an invalid type, or @@ -122,26 +122,27 @@ protected function exactEvaluator($condition) $conditionValue = $condition['value']; $userValue = isset($this->userAttributes[$conditionName]) ? $this->userAttributes[$conditionName]: null; - if(!$this->isValueValidForExactConditions($userValue) || - !$this->isValueValidForExactConditions($conditionValue) || - !Validator::areValuesSameType($conditionValue, $userValue)) { + if (!$this->isValueValidForExactConditions($userValue) + || !$this->isValueValidForExactConditions($conditionValue) + || !Validator::areValuesSameType($conditionValue, $userValue) + ) { return null; - } + } return $conditionValue == $userValue; } /** * Evaluate the given exists match condition for the given user attributes. - * - * @param object $condition - * + * + * @param object $condition + * * @return null|boolean true if both: * 1) the user attributes have a value for the given condition, and * 2) the user attribute value is not null. * false otherwise. */ - protected function existsEvaluator($condition) + protected function existsEvaluator($condition) { $conditionName = $condition['name']; return isset($this->userAttributes[$conditionName]); @@ -149,9 +150,9 @@ protected function existsEvaluator($condition) /** * Evaluate the given greater than match condition for the given user attributes. - * - * @param object $condition - * + * + * @param object $condition + * * @return boolean true if the user attribute value is greater than the condition value, * false if the user attribute value is less than or equal to the condition value, * null if the condition value isn't a number or the user attribute value @@ -163,7 +164,7 @@ protected function greaterThanEvaluator($condition) $conditionValue = $condition['value']; $userValue = isset($this->userAttributes[$conditionName]) ? $this->userAttributes[$conditionName]: null; - if(!Validator::isFiniteNumber($userValue) || !Validator::isFiniteNumber($conditionValue)) { + if (!Validator::isFiniteNumber($userValue) || !Validator::isFiniteNumber($conditionValue)) { return null; } @@ -172,9 +173,9 @@ protected function greaterThanEvaluator($condition) /** * Evaluate the given less than match condition for the given user attributes. - * - * @param object $condition - * + * + * @param object $condition + * * @return boolean true if the user attribute value is less than the condition value, * false if the user attribute value is greater than or equal to the condition value, * null if the condition value isn't a number or the user attribute value @@ -186,7 +187,7 @@ protected function lessThanEvaluator($condition) $conditionValue = $condition['value']; $userValue = isset($this->userAttributes[$conditionName]) ? $this->userAttributes[$conditionName]: null; - if(!Validator::isFiniteNumber($userValue) || !Validator::isFiniteNumber($conditionValue)) { + if (!Validator::isFiniteNumber($userValue) || !Validator::isFiniteNumber($conditionValue)) { return null; } @@ -194,22 +195,22 @@ protected function lessThanEvaluator($condition) } /** - * Evaluate the given substring than match condition for the given user attributes. - * - * @param object $condition - * - * @return boolean true if the condition value is a substring of the user attribute value, - * false if the condition value is not a substring of the user attribute value, - * null if the condition value isn't a string or the user attribute value - * isn't a string. - */ + * Evaluate the given substring than match condition for the given user attributes. + * + * @param object $condition + * + * @return boolean true if the condition value is a substring of the user attribute value, + * false if the condition value is not a substring of the user attribute value, + * null if the condition value isn't a string or the user attribute value + * isn't a string. + */ protected function substringEvaluator($condition) { $conditionName = $condition['name']; $conditionValue = $condition['value']; $userValue = isset($this->userAttributes[$conditionName]) ? $this->userAttributes[$conditionName]: null; - if(!is_string($userValue) || !is_string($conditionValue)) { + if (!is_string($userValue) || !is_string($conditionValue)) { return null; } @@ -219,26 +220,26 @@ protected function substringEvaluator($condition) /** * Function to evaluate audience conditions against user's attributes. * - * @param array $leafCondition Condition to be evaluated. + * @param array $leafCondition Condition to be evaluated. * - * @return null|boolean true/false if the given user attributes match/don't match the given conditions, + * @return null|boolean true/false if the given user attributes match/don't match the given conditions, * null if the given user attributes and conditions can't be evaluated. */ public function evaluate($leafCondition) { $leafCondition = $this->setNullForMissingKeys($leafCondition); - if($leafCondition['type'] !== self::CUSTOM_ATTRIBUTE_CONDITION_TYPE) { + if ($leafCondition['type'] !== self::CUSTOM_ATTRIBUTE_CONDITION_TYPE) { return null; } - if(($leafCondition['match']) === null) { + if (($leafCondition['match']) === null) { $conditionMatch = self::EXACT_MATCH_TYPE; } else { $conditionMatch = $leafCondition['match']; } - if(!in_array($conditionMatch, $this->getMatchTypes())) { + if (!in_array($conditionMatch, $this->getMatchTypes())) { return null; } diff --git a/src/Optimizely/Utils/EventTagUtils.php b/src/Optimizely/Utils/EventTagUtils.php index 80526efd..e9a8b54e 100644 --- a/src/Optimizely/Utils/EventTagUtils.php +++ b/src/Optimizely/Utils/EventTagUtils.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2017-2018, Optimizely + * Copyright 2017-2019, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,7 +77,7 @@ public static function getRevenueValue($eventTags, $logger) * Grab the numeric event value from the event tags. "value" is a reserved keyword. * The value of 'value' can be a float or a numeric string * - * @param $eventTags array Representing metadata associated with the event. + * @param $eventTags array Representing metadata associated with the event. * @param $logger instance of LoggerInterface * * @return float value of 'value' or null diff --git a/src/Optimizely/Utils/Validator.php b/src/Optimizely/Utils/Validator.php index dd6f8eeb..a7aeb169 100644 --- a/src/Optimizely/Utils/Validator.php +++ b/src/Optimizely/Utils/Validator.php @@ -61,11 +61,11 @@ public static function validateJsonSchema($datafile, LoggerInterface $logger = n */ public static function areAttributesValid($attributes) { - if(!is_array($attributes)){ + if (!is_array($attributes)) { return false; } - if (empty($attributes)){ + if (empty($attributes)) { return true; } // At least one key string to be an associative array. @@ -86,7 +86,7 @@ public static function isFiniteNumber($value) if (is_nan($value) || is_infinite($value)) { return false; - } + } if (abs($value) > pow(2, 53)) { return false; @@ -154,11 +154,11 @@ public static function isUserInExperiment($config, $experiment, $userAttributes) } $customAttrCondEval = new CustomAttributeConditionEvaluator($userAttributes); - $evaluateCustomAttr = function($leafCondition) use ($customAttrCondEval) { + $evaluateCustomAttr = function ($leafCondition) use ($customAttrCondEval) { return $customAttrCondEval->evaluate($leafCondition); }; - $evaluateAudience = function($audienceId) use ($config, $evaluateCustomAttr) { + $evaluateAudience = function ($audienceId) use ($config, $evaluateCustomAttr) { $conditionTreeEvaluator = new ConditionTreeEvaluator(); $audience = $config->getAudience($audienceId); @@ -224,12 +224,12 @@ public static function validateNonEmptyString($value) } /** - * Method to verify that both values belong to same type. + * Method to verify that both values belong to same type. * Float/Double and Integer are considered similar. - * - * @param mixed $firstVal - * @param mixed $secondVal - * + * + * @param mixed $firstVal + * @param mixed $secondVal + * * @return bool True if values belong to similar types. Otherwise, False. */ public static function areValuesSameType($firstVal, $secondVal) @@ -238,8 +238,8 @@ public static function areValuesSameType($firstVal, $secondVal) $secondValType = gettype($secondVal); $numberTypes = array('double', 'integer'); - if(in_array($firstValType, $numberTypes) && in_array($secondValType, $numberTypes)) { - return True; + if (in_array($firstValType, $numberTypes) && in_array($secondValType, $numberTypes)) { + return true; } return $firstValType == $secondValType; @@ -247,12 +247,13 @@ public static function areValuesSameType($firstVal, $secondVal) /** * Returns true only if given input is an array with all of it's keys of type string. + * * @param mixed $arr * @return bool True if array contains all string keys. Otherwise, false. */ public static function doesArrayContainOnlyStringKeys($arr) { - if(!is_array($arr) || empty($arr)) { + if (!is_array($arr) || empty($arr)) { return false; } diff --git a/src/Optimizely/Utils/VariableTypeUtils.php b/src/Optimizely/Utils/VariableTypeUtils.php index 1acf442f..c29c12e9 100644 --- a/src/Optimizely/Utils/VariableTypeUtils.php +++ b/src/Optimizely/Utils/VariableTypeUtils.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2017, Optimizely + * Copyright 2017, 2019, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,21 +33,21 @@ public static function castStringToType($value, $variableType, LoggerInterface $ $return_value = null; switch ($variableType) { - case FeatureVariable::BOOLEAN_TYPE: - $return_value = strtolower($value) == "true"; - break; - - case FeatureVariable::INTEGER_TYPE: - if (ctype_digit($value)) { - $return_value = (int) $value; - } - break; - - case FeatureVariable::DOUBLE_TYPE: - if (is_numeric($value)) { - $return_value = (float) $value; - } - break; + case FeatureVariable::BOOLEAN_TYPE: + $return_value = strtolower($value) == "true"; + break; + + case FeatureVariable::INTEGER_TYPE: + if (ctype_digit($value)) { + $return_value = (int) $value; + } + break; + + case FeatureVariable::DOUBLE_TYPE: + if (is_numeric($value)) { + $return_value = (float) $value; + } + break; } if (is_null($return_value) && $logger) { diff --git a/tests/DecisionServiceTests/DecisionServiceTest.php b/tests/DecisionServiceTests/DecisionServiceTest.php index eb0e349c..a1d3a47f 100644 --- a/tests/DecisionServiceTests/DecisionServiceTest.php +++ b/tests/DecisionServiceTests/DecisionServiceTest.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2017-2018, Optimizely + * Copyright 2017-2019, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -1070,7 +1070,8 @@ public function testGetVariationForFeatureRolloutWhenUserIsNeitherBucketedInTheT ->method('log'); $this->assertNull( - $this->decisionService->getVariationForFeatureRollout($featureFlag, 'user_1', $user_attributes)); + $this->decisionService->getVariationForFeatureRollout($featureFlag, 'user_1', $user_attributes) + ); } // ============== END of tests - when the user qualifies for targeting rule (audience match) ====================== @@ -1171,7 +1172,7 @@ public function testGetVariationForFeatureRolloutWhenUserDoesNotQualifyForAnyTar ->with( Logger::DEBUG, "User 'user_1' did not meet the audience conditions to be in rollout rule '{$experiment2->getKey()}'." - ); + ); $this->assertNull($this->decisionService->getVariationForFeatureRollout($featureFlag, 'user_1', $user_attributes)); } diff --git a/tests/EventTests/EventBuilderTest.php b/tests/EventTests/EventBuilderTest.php index 371b8880..5d9dba10 100644 --- a/tests/EventTests/EventBuilderTest.php +++ b/tests/EventTests/EventBuilderTest.php @@ -148,28 +148,33 @@ public function testCreateImpressionEventNoAttributesNoValue() public function testCreateImpressionEventWithAttributesNoValue() { - array_unshift($this->expectedImpressionEventParams['visitors'][0]['attributes'], + array_unshift( + $this->expectedImpressionEventParams['visitors'][0]['attributes'], [ 'entity_id' => '7723280020', 'key' => 'device_type', 'type' => 'custom', 'value' => 'iPhone', - ],[ + ], + [ 'entity_id' => '7723340007', 'key' => 'boolean_key', 'type' => 'custom', 'value' => true - ],[ + ], + [ 'entity_id' => '7723340008', 'key' => 'double_key', 'type' => 'custom', 'value' => 5.5 - ],[ + ], + [ 'entity_id' => '7723340009', 'key' => 'integer_key', 'type' => 'custom', 'value' => 5 - ]); + ] + ); $this->expectedLogEvent = new LogEvent( $this->expectedEventUrl, @@ -202,12 +207,14 @@ public function testCreateImpressionEventWithAttributesNoValue() */ public function testCreateImpressionEventWithFalseAttributesNoValue() { - array_unshift($this->expectedImpressionEventParams['visitors'][0]['attributes'], - [ 'entity_id' => '7723280020', + array_unshift( + $this->expectedImpressionEventParams['visitors'][0]['attributes'], + [ 'entity_id' => '7723280020', 'key' => 'device_type', 'type' => 'custom', 'value' => 'false', - ]); + ] + ); $expectedLogEvent = new LogEvent( $this->expectedEventUrl, @@ -237,12 +244,14 @@ public function testCreateImpressionEventWithFalseAttributesNoValue() */ public function testCreateImpressionEventWithZeroAttributesNoValue() { - array_unshift($this->expectedImpressionEventParams['visitors'][0]['attributes'], - [ 'entity_id' => '7723280020', + array_unshift( + $this->expectedImpressionEventParams['visitors'][0]['attributes'], + [ 'entity_id' => '7723280020', 'key' => 'device_type', 'type' => 'custom', 'value' => 0, - ]); + ] + ); $expectedLogEvent = new LogEvent( $this->expectedEventUrl, @@ -335,13 +344,15 @@ public function testCreateImpressionEventWithUserAgentWhenBotFilteringIsEnabled( public function testCreateImpressionEventWithInvalidAttributeTypes() { - array_unshift($this->expectedImpressionEventParams['visitors'][0]['attributes'], + array_unshift( + $this->expectedImpressionEventParams['visitors'][0]['attributes'], [ 'entity_id' => '7723280020', 'key' => 'device_type', 'type' => 'custom', 'value' => 'iPhone', - ],[ + ], + [ 'entity_id' => '7723340008', 'key' => 'double_key', 'type' => 'custom', @@ -495,12 +506,14 @@ public function testCreateConversionEventNoAttributesNoValue() public function testCreateConversionEventWithAttributesNoValue() { - array_unshift($this->expectedEventParams['visitors'][0]['attributes'], - [ 'entity_id' => '7723280020', + array_unshift( + $this->expectedEventParams['visitors'][0]['attributes'], + [ 'entity_id' => '7723280020', 'key' => 'device_type', 'type' => 'custom', 'value' => 'iPhone', - ]); + ] + ); $this->expectedEventParams['visitors'][0]['snapshots'][0]['events'][0] = [ @@ -605,12 +618,14 @@ public function testCreateConversionEventNoAttributesWithValue() public function testCreateConversionEventWithAttributesWithValue() { - array_unshift($this->expectedEventParams['visitors'][0]['attributes'], - [ 'entity_id' => '7723280020', + array_unshift( + $this->expectedEventParams['visitors'][0]['attributes'], + [ 'entity_id' => '7723280020', 'key' => 'device_type', 'type' => 'custom', 'value' => 'iPhone', - ]); + ] + ); $this->expectedEventParams['visitors'][0]['snapshots'][0]['events'][0] = [ @@ -657,12 +672,14 @@ public function testCreateConversionEventWithAttributesWithValue() public function testCreateConversionEventWithAttributesWithNumericTag() { - array_unshift($this->expectedEventParams['visitors'][0]['attributes'], - [ 'entity_id' => '7723280020', + array_unshift( + $this->expectedEventParams['visitors'][0]['attributes'], + [ 'entity_id' => '7723280020', 'key' => 'device_type', 'type' => 'custom', 'value' => 'iPhone', - ]); + ] + ); $this->expectedEventParams['visitors'][0]['snapshots'][0]['events'][0] = [ @@ -744,18 +761,21 @@ public function testCreateConversionEventNoAttributesWithInvalidValue() // (since this custom attribute entity is not generated by GAE) public function testCreateImpressionEventWithBucketingIDAttribute() { - array_unshift($this->expectedImpressionEventParams['visitors'][0]['attributes'], - [ + array_unshift( + $this->expectedImpressionEventParams['visitors'][0]['attributes'], + [ 'entity_id' => '7723280020', 'key' => 'device_type', 'type' => 'custom', 'value' => 'iPhone' - ],[ + ], + [ 'entity_id' => '$opt_bucketing_id', 'key' => '$opt_bucketing_id', 'type' => 'custom', 'value' => 'variation' - ]); + ] + ); $expectedLogEvent = new LogEvent( $this->expectedEventUrl, @@ -785,18 +805,21 @@ public function testCreateImpressionEventWithBucketingIDAttribute() public function testCreateConversionEventWithBucketingIDAttribute() { - array_unshift($this->expectedEventParams['visitors'][0]['attributes'], - [ + array_unshift( + $this->expectedEventParams['visitors'][0]['attributes'], + [ 'entity_id' => '7723280020', 'key' => 'device_type', 'type' => 'custom', 'value' => 'iPhone', - ],[ + ], + [ 'entity_id' => '$opt_bucketing_id', 'key' => '$opt_bucketing_id', 'type' => 'custom', 'value' => 'variation', - ]); + ] + ); $this->expectedEventParams['visitors'][0]['snapshots'][0]['events'][0] = [ @@ -834,14 +857,16 @@ public function testCreateConversionEventWithBucketingIDAttribute() public function testCreateConversionEventWithUserAgentAttribute() { - array_unshift($this->expectedEventParams['visitors'][0]['attributes'], - [ 'entity_id' => '$opt_user_agent', + array_unshift( + $this->expectedEventParams['visitors'][0]['attributes'], + [ 'entity_id' => '$opt_user_agent', 'key' => '$opt_user_agent', 'type' => 'custom', 'value' => 'Firefox', - ]); + ] + ); - $this->expectedEventParams['visitors'][0]['snapshots'][0]['events'][0] = + $this->expectedEventParams['visitors'][0]['snapshots'][0]['events'][0] = [ 'entity_id'=> '7718020063', 'timestamp'=> $this->timestamp, @@ -849,27 +874,27 @@ public function testCreateConversionEventWithUserAgentAttribute() 'key'=> 'purchase' ]; - $expectedLogEvent = new LogEvent( - $this->expectedEventUrl, - $this->expectedEventParams, - $this->expectedEventHttpVerb, - $this->expectedEventHeaders - ); + $expectedLogEvent = new LogEvent( + $this->expectedEventUrl, + $this->expectedEventParams, + $this->expectedEventHttpVerb, + $this->expectedEventHeaders + ); - $userAttributes = [ + $userAttributes = [ '$opt_user_agent' => 'Firefox' - ]; - $logEvent = $this->eventBuilder->createConversionEvent( - $this->config, - 'purchase', - $this->testUserId, - $userAttributes, - null - ); - - $logEvent = $this->fakeParamsToReconcile($logEvent); - $result = $this->areLogEventsEqual($expectedLogEvent, $logEvent); - $this->assertTrue($result[0], $result[1]); + ]; + $logEvent = $this->eventBuilder->createConversionEvent( + $this->config, + 'purchase', + $this->testUserId, + $userAttributes, + null + ); + + $logEvent = $this->fakeParamsToReconcile($logEvent); + $result = $this->areLogEventsEqual($expectedLogEvent, $logEvent); + $this->assertTrue($result[0], $result[1]); } public function testCreateConversionEventWhenEventUsedInMultipleExp() @@ -890,18 +915,21 @@ public function testCreateConversionEventWhenEventUsedInMultipleExp() 'tags' => $eventTags, ]; - array_unshift($this->expectedEventParams['visitors'][0]['attributes'], + array_unshift( + $this->expectedEventParams['visitors'][0]['attributes'], [ 'entity_id' => '7723280020', 'key' => 'device_type', 'type' => 'custom', 'value' => 'iPhone' - ],[ + ], + [ 'entity_id' => '7723340004', 'key' => 'location', 'type' => 'custom', 'value' => 'SF' - ]); + ] + ); $userAttributes = [ 'device_type' => 'iPhone', @@ -909,22 +937,21 @@ public function testCreateConversionEventWhenEventUsedInMultipleExp() ]; $logEvent = $this->eventBuilder->createConversionEvent( - $this->config, - 'multi_exp_event', - $this->testUserId, - $userAttributes, - $eventTags - ); + $this->config, + 'multi_exp_event', + $this->testUserId, + $userAttributes, + $eventTags + ); $expectedLogEvent = new LogEvent( - $this->expectedEventUrl, - $this->expectedEventParams, - $this->expectedEventHttpVerb, - $this->expectedEventHeaders + $this->expectedEventUrl, + $this->expectedEventParams, + $this->expectedEventHttpVerb, + $this->expectedEventHeaders ); $logEvent = $this->fakeParamsToReconcile($logEvent); $result = $this->areLogEventsEqual($expectedLogEvent, $logEvent); $this->assertTrue($result[0], $result[1]); - } } diff --git a/tests/LoggerTests/NoOpLoggerTest.php b/tests/LoggerTests/NoOpLoggerTest.php index d0cc07a8..13dfbda8 100644 --- a/tests/LoggerTests/NoOpLoggerTest.php +++ b/tests/LoggerTests/NoOpLoggerTest.php @@ -14,11 +14,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +namespace Optimizely\Tests; use Monolog\Logger; use Optimizely\Logger\NoOpLogger; -class NoOpLoggerTest extends PHPUnit_Framework_TestCase +class NoOpLoggerTest extends \PHPUnit_Framework_TestCase { public function testNoOpLogger() { diff --git a/tests/NotificationTests/NotificationCenterTest.php b/tests/NotificationTests/NotificationCenterTest.php index b5774bde..8f3f51bb 100644 --- a/tests/NotificationTests/NotificationCenterTest.php +++ b/tests/NotificationTests/NotificationCenterTest.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2017-2018, Optimizely + * Copyright 2017-2019, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -240,7 +240,7 @@ public function testAddNotificationThatAlreadyAddedCallbackIsNotReAdded() { // Note: anonymous methods sent with the same body will be re-added. // Only variable and object methods can be checked for duplication - + $functionToSend = function () { }; $this->notificationCenterObj->clearAllNotificationListeners(); @@ -276,7 +276,7 @@ public function testAddNotificationThatAlreadyAddedCallbackIsNotReAdded() 2, $this->notificationCenterObj->addNotificationListener(NotificationType::TRACK, $functionToSend) ); - + ///////////////////////////////////////////////////////////////////////// // ===== verify that an object method with same body isn't re-added ===== // ///////////////////////////////////////////////////////////////////////// @@ -368,7 +368,7 @@ function () { ///////////////////////////////////////////////////////////////////// // === Verify that callback is removed for a valid notification ID // ///////////////////////////////////////////////////////////////////// - + $valid_id = 3; $this->loggerMock->expects($this->at(0)) ->method('log') @@ -410,33 +410,33 @@ function () { public function testClearNotificationsAndVerifyThatClearNotificationListenersWithArgsIsCalled() { # Mock NotificationCenter - $this->notificationCenterMock = $this->getMockBuilder(NotificationCenter::class) + $this->notificationCenterMock = $this->getMockBuilder(NotificationCenter::class) ->setConstructorArgs(array($this->loggerMock, $this->errorHandlerMock)) ->setMethods(array('clearNotificationListeners')) ->getMock(); # Log deprecation message - $this->loggerMock->expects($this->at(0)) + $this->loggerMock->expects($this->at(0)) ->method('log') ->with( - Logger::WARNING, - sprintf("'clearNotifications' is deprecated. Call 'clearNotificationListeners' instead.") + Logger::WARNING, + sprintf("'clearNotifications' is deprecated. Call 'clearNotificationListeners' instead.") ); - $this->notificationCenterMock->expects($this->once()) + $this->notificationCenterMock->expects($this->once()) ->method('clearNotificationListeners') ->with( - NotificationType::ACTIVATE + NotificationType::ACTIVATE ); - $this->notificationCenterMock->clearNotifications(NotificationType::ACTIVATE); + $this->notificationCenterMock->clearNotifications(NotificationType::ACTIVATE); } public function testClearNotificationListeners() { // ensure that notifications length is zero for each notification type $this->notificationCenterObj->clearAllNotificationListeners(); - + // add a callback for multiple notification types $this->notificationCenterObj->addNotificationListener( NotificationType::ACTIVATE, @@ -499,7 +499,7 @@ function () { /////////////////////////////////////////////////////////////////////////////////////// // === Verify that all notifications are removed given a valid notification type === // /////////////////////////////////////////////////////////////////////////////////////// - + $this->loggerMock->expects($this->at(0)) ->method('log') ->with( @@ -607,34 +607,34 @@ function () { public function testCleanAllNotificationsAndVerifyThatClearAllNotificationListenersIsCalled() { # Mock NotificationCenter - $this->notificationCenterMock = $this->getMockBuilder(NotificationCenter::class) + $this->notificationCenterMock = $this->getMockBuilder(NotificationCenter::class) ->setConstructorArgs(array($this->loggerMock, $this->errorHandlerMock)) ->setMethods(array('clearAllNotificationListeners')) ->getMock(); # Log deprecation message - $this->loggerMock->expects($this->at(0)) + $this->loggerMock->expects($this->at(0)) ->method('log') ->with( - Logger::WARNING, - sprintf("'cleanAllNotifications' is deprecated. Call 'clearAllNotificationListeners' instead.") + Logger::WARNING, + sprintf("'cleanAllNotifications' is deprecated. Call 'clearAllNotificationListeners' instead.") ); - $this->notificationCenterMock->expects($this->once()) + $this->notificationCenterMock->expects($this->once()) ->method('clearAllNotificationListeners'); - $this->notificationCenterMock->cleanAllNotifications(); + $this->notificationCenterMock->cleanAllNotifications(); } public function testSendNotificationsGivenLessThanExpectedNumberOfArguments() { $clientObj = new FireNotificationTester; $this->notificationCenterObj->clearAllNotificationListeners(); - + // add a notification callback with arguments $this->notificationCenterObj->addNotificationListener( NotificationType::ACTIVATE, - array($clientObj, 'decision_callback_with_args') + array($clientObj, 'decisionCallbackWithArgs') ); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -654,7 +654,7 @@ public function testSendNotificationsGivenLessThanExpectedNumberOfArguments() public function testSendNotificationsAndVerifyThatAllCallbacksWithoutArgsAreCalled() { $clientMock = $this->getMockBuilder(FireNotificationTester::class) - ->setMethods(array('decision_callback_no_args', 'decision_callback_no_args_2', 'track_callback_no_args')) + ->setMethods(array('decisionCallbackNoArgs', 'decisionCallbackNoArgs2', 'trackCallbackNoArgs')) ->getMock(); $this->notificationCenterObj->clearAllNotificationListeners(); @@ -662,15 +662,15 @@ public function testSendNotificationsAndVerifyThatAllCallbacksWithoutArgsAreCall //add notification callbacks $this->notificationCenterObj->addNotificationListener( NotificationType::ACTIVATE, - array($clientMock, 'decision_callback_no_args') + array($clientMock, 'decisionCallbackNoArgs') ); $this->notificationCenterObj->addNotificationListener( NotificationType::ACTIVATE, - array($clientMock, 'decision_callback_no_args_2') + array($clientMock, 'decisionCallbackNoArgs2') ); $this->notificationCenterObj->addNotificationListener( NotificationType::TRACK, - array($clientMock, 'track_callback_no_args') + array($clientMock, 'trackCallbackNoArgs') ); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -678,26 +678,26 @@ public function testSendNotificationsAndVerifyThatAllCallbacksWithoutArgsAreCall ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// $clientMock->expects($this->exactly(1)) - ->method('decision_callback_no_args'); + ->method('decisionCallbackNoArgs'); $clientMock->expects($this->exactly(1)) - ->method('decision_callback_no_args_2'); + ->method('decisionCallbackNoArgs2'); $clientMock->expects($this->never()) - ->method('track_callback_no_args'); + ->method('trackCallbackNoArgs'); $this->notificationCenterObj->sendNotifications(NotificationType::ACTIVATE); //////////////////////////////////////////////////////////////////////////////////////////// // === Verify that none of the callbacks are called given an invalid NotificationType === // //////////////////////////////////////////////////////////////////////////////////////////// - + $clientMock->expects($this->never()) - ->method('decision_callback_no_args'); + ->method('decisionCallbackNoArgs'); $clientMock->expects($this->never()) - ->method('decision_callback_no_args_2'); + ->method('decisionCallbackNoArgs2'); $clientMock->expects($this->never()) - ->method('track_callback_no_args'); + ->method('trackCallbackNoArgs'); $this->notificationCenterObj->sendNotifications("abacada"); } @@ -705,7 +705,7 @@ public function testSendNotificationsAndVerifyThatAllCallbacksWithoutArgsAreCall public function testSendNotificationsAndVerifyThatAllCallbacksWithArgsAreCalled() { $clientMock = $this->getMockBuilder(FireNotificationTester::class) - ->setMethods(array('decision_callback_with_args', 'decision_callback_with_args_2', 'track_callback_no_args')) + ->setMethods(array('decisionCallbackWithArgs', 'decisionCallbackWithArgs2', 'trackCallbackNoArgs')) ->getMock(); $this->notificationCenterObj->clearAllNotificationListeners(); @@ -713,15 +713,15 @@ public function testSendNotificationsAndVerifyThatAllCallbacksWithArgsAreCalled( //add notification callbacks with args $this->notificationCenterObj->addNotificationListener( NotificationType::ACTIVATE, - array($clientMock, 'decision_callback_with_args') + array($clientMock, 'decisionCallbackWithArgs') ); $this->notificationCenterObj->addNotificationListener( NotificationType::ACTIVATE, - array($clientMock, 'decision_callback_with_args_2') + array($clientMock, 'decisionCallbackWithArgs2') ); $this->notificationCenterObj->addNotificationListener( NotificationType::TRACK, - array($clientMock, 'track_callback_no_args') + array($clientMock, 'trackCallbackNoArgs') ); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -729,7 +729,7 @@ public function testSendNotificationsAndVerifyThatAllCallbacksWithArgsAreCalled( ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// $clientMock->expects($this->exactly(1)) - ->method('decision_callback_with_args') + ->method('decisionCallbackWithArgs') ->with( 5, 5.5, @@ -739,7 +739,7 @@ function () { } ); $clientMock->expects($this->exactly(1)) - ->method('decision_callback_with_args_2') + ->method('decisionCallbackWithArgs2') ->with( 5, 5.5, @@ -749,7 +749,7 @@ function () { } ); $clientMock->expects($this->never()) - ->method('track_callback_no_args'); + ->method('trackCallbackNoArgs'); $this->notificationCenterObj->sendNotifications( NotificationType::ACTIVATE, diff --git a/tests/OptimizelyTest.php b/tests/OptimizelyTest.php index 5308e10c..37efef56 100644 --- a/tests/OptimizelyTest.php +++ b/tests/OptimizelyTest.php @@ -41,6 +41,7 @@ class OptimizelyTest extends \PHPUnit_Framework_TestCase const OUTPUT_STREAM = 'output'; private $datafile; + private $eventBuilderMock; private $loggerMock; private $optimizelyObject; @@ -63,7 +64,9 @@ public function setUp() ->getMock(); $this->optimizelyObject = new Optimizely($this->datafile, null, $this->loggerMock); $this->optimizelyTypedAudienceObject = new Optimizely( - $this->typedAudiencesDataFile, null, $this->loggerMock + $this->typedAudiencesDataFile, + null, + $this->loggerMock ); $this->projectConfig = new ProjectConfig($this->datafile, $this->loggerMock, new NoOpErrorHandler()); @@ -637,7 +640,6 @@ public function testActivateWithAttributesTypedAudienceMatch() //Should be included via exact match number audience with id '3468206646' $this->assertEquals('A', $optimizelyMock->activate('typed_audience_experiment', 'test_user', $userAttributes)); - } public function testActivateWithAttributesTypedAudienceMismatch() @@ -1174,7 +1176,7 @@ public function testTrackGivenEventKeyWithNoExperiments() public function testTrackGivenEventKeyWithPausedExperiment() { $pausedExpEvent = $this->projectConfig->getEvent('purchase'); - // Experiment with ID 7716830585 is paused. + // Experiment with ID 7716830585 is paused. $pausedExpEvent->setExperimentIds(['7716830585']); $config = new \ReflectionProperty(Optimizely::class, '_config'); diff --git a/tests/ProjectConfigTest.php b/tests/ProjectConfigTest.php index 82de415f..76b7f238 100644 --- a/tests/ProjectConfigTest.php +++ b/tests/ProjectConfigTest.php @@ -511,7 +511,9 @@ public function testGetAudienceValidId() public function testGetAudiencePrefersTypedAudiencesOverAudiences() { $projectConfig = new ProjectConfig( - DATAFILE_WITH_TYPED_AUDIENCES, $this->loggerMock, $this->errorHandlerMock + DATAFILE_WITH_TYPED_AUDIENCES, + $this->loggerMock, + $this->errorHandlerMock ); // test that typedAudience is returned when an audience exists with the same ID. @@ -560,7 +562,8 @@ public function testGetAttributeValidKeyWithReservedPrefix() { $this->loggerMock->expects($this->once()) ->method('log') - ->with(Logger::WARNING, + ->with( + Logger::WARNING, 'Attribute $opt_xyz unexpectedly has reserved prefix $opt_; using attribute ID instead of reserved attribute name.' ); @@ -690,7 +693,7 @@ public function testSetGetForcedVariation() $variationKey = 'control'; $variationKey2 = 'group_exp_1_var_1'; $invalidVariationKey = 'invalid_variation'; - + $optlyObject = new Optimizely(DATAFILE, new ValidEventDispatcher(), $this->loggerMock); $userAttributes = [ 'device_type' => 'iPhone', diff --git a/tests/TestData.php b/tests/TestData.php index d3bd0f76..5a439eb9 100644 --- a/tests/TestData.php +++ b/tests/TestData.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2016-2018, Optimizely + * Copyright 2016-2019, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -81,7 +81,7 @@ } ], "audienceIds": [ - + ], "variations": [ { @@ -94,7 +94,7 @@ } ], "forcedVariations": { - + }, "id": "7716830585" }, @@ -107,7 +107,7 @@ ], "id": "122230", "forcedVariations": { - + }, "trafficAllocation": [ { @@ -195,11 +195,11 @@ "status": "Running", "layerId": "5", "audienceIds": [ - + ], "id": "122235", "forcedVariations": { - + }, "trafficAllocation": [ { @@ -241,11 +241,11 @@ "status": "Running", "layerId": "5", "audienceIds": [ - + ], "id": "122238", "forcedVariations": { - + }, "trafficAllocation": [ { @@ -287,11 +287,11 @@ "status": "Running", "layerId": "6", "audienceIds": [ - + ], "id": "122241", "forcedVariations": { - + }, "trafficAllocation": [ { @@ -375,7 +375,7 @@ } ], "audienceIds": [ - + ], "variations": [ { @@ -421,7 +421,7 @@ } ], "audienceIds": [ - + ], "variations": [ { @@ -448,7 +448,7 @@ } ], "forcedVariations": { - + }, "id": "7718750065" } @@ -522,7 +522,7 @@ "7718750065" ], "variables": [ - + ] }, { @@ -562,7 +562,7 @@ "key": "boolean_single_variable_feature", "rolloutId": "166660", "experimentIds": [ - + ], "variables": [ { @@ -633,10 +633,10 @@ "key": "empty_feature", "rolloutId": "", "experimentIds": [ - + ], "variables": [ - + ] } ], @@ -706,7 +706,7 @@ "status": "Running", "layerId": "166660", "audienceIds": [ - + ], "variations": [ { @@ -746,7 +746,7 @@ "id": "177775", "key": "177775", "variables": [ - + ], "featureEnabled": true } @@ -764,14 +764,14 @@ "status": "Running", "layerId": "166661", "audienceIds": [ - + ], "variations": [ { "id": "177780", "key": "177780", "variables": [ - + ], "featureEnabled": true } @@ -844,8 +844,8 @@ ); define( - 'DATAFILE_WITH_TYPED_AUDIENCES', - '{ + 'DATAFILE_WITH_TYPED_AUDIENCES', + '{ "version": "4", "rollouts": [ { @@ -1285,23 +1285,23 @@ public function validateInputs(array $values, $logLevel = Logger::ERROR) class FireNotificationTester { - public function decision_callback_no_args() + public function decisionCallbackNoArgs() { } - public function decision_callback_no_args_2() + public function decisionCallbackNoArgs2() { } - public function decision_callback_with_args($anInt, $aDouble, $aString, $anArray, $aFunction) + public function decisionCallbackWithArgs($anInt, $aDouble, $aString, $anArray, $aFunction) { } - public function decision_callback_with_args_2($anInt, $aDouble, $aString, $anArray, $aFunction) + public function decisionCallbackWithArgs2($anInt, $aDouble, $aString, $anArray, $aFunction) { } - public function track_callback_no_args() + public function trackCallbackNoArgs() { } } diff --git a/tests/UtilsTests/ConditionTreeEvaluatorTest.php b/tests/UtilsTests/ConditionTreeEvaluatorTest.php index e9c5d3de..94e77543 100644 --- a/tests/UtilsTests/ConditionTreeEvaluatorTest.php +++ b/tests/UtilsTests/ConditionTreeEvaluatorTest.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2018, Optimizely + * Copyright 2018-2019, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -47,24 +47,28 @@ public function setUp() /** * Helper method to create a callback that returns passed arguments on consecutive calls. - * + * * @param mixed $a * @param mixed $b * @param mixed $c - * - * @return callable + * + * @return callable */ - protected function getLeafEvaluator($a, $b = null, $c = null) { + protected function getLeafEvaluator($a, $b = null, $c = null) + { $numOfCalls = 0; $leafEvaluator = function ($some_arg) use (&$numOfCalls, $a, $b, $c) { $numOfCalls++; - if($numOfCalls == 1) + if ($numOfCalls == 1) { return $a; - if($numOfCalls == 2) + } + if ($numOfCalls == 2) { return $b; - if($numOfCalls == 3) + } + if ($numOfCalls == 3) { return $c; + } return null; }; @@ -336,5 +340,4 @@ public function testEvaluateAssumesOrOperatorWhenFirstArrayItemUnrecognizedOpera ) ); } - } diff --git a/tests/UtilsTests/CustomAttributeConditionEvaluatorTest.php b/tests/UtilsTests/CustomAttributeConditionEvaluatorTest.php index 2577d8f0..3aa75b44 100644 --- a/tests/UtilsTests/CustomAttributeConditionEvaluatorTest.php +++ b/tests/UtilsTests/CustomAttributeConditionEvaluatorTest.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2018, Optimizely + * Copyright 2018-2019, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -117,7 +117,7 @@ public function testEvaluateReturnsTrueWhenAttrsPassAudienceCondition() $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->browserConditionSafari + $this->browserConditionSafari ) ); } @@ -130,7 +130,7 @@ public function testEvaluateReturnsFalseWhenAttrsFailAudienceConditions() $this->assertFalse( $customAttrConditionEvaluator->evaluate( - $this->browserConditionSafari + $this->browserConditionSafari ) ); } @@ -150,25 +150,25 @@ public function testEvaluateForDifferentTypedAttributes() $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->browserConditionSafari + $this->browserConditionSafari ) ); $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->booleanCondition + $this->booleanCondition ) ); $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->integerCondition + $this->integerCondition ) ); $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->doubleCondition + $this->doubleCondition ) ); } @@ -189,7 +189,6 @@ public function testEvaluateReturnsNullForInvalidMatchProperty() ] ) ); - } public function testEvaluateAssumesExactWhenConditionMatchPropertyIsNull() @@ -288,7 +287,6 @@ public function testExistsReturnsTrueWhenUserProvidedValueIsNumber() $this->existsCondition ) ); - } public function testExistsReturnsTrueWhenUserProvidedValueIsBoolean() @@ -312,7 +310,7 @@ public function testExactStringReturnsTrueWhenAttrsEqualToConditionValue() $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->exactStringCondition + $this->exactStringCondition ) ); } @@ -325,7 +323,7 @@ public function testExactStringReturnsFalseWhenAttrsNotEqualToConditionValue() $this->assertFalse( $customAttrConditionEvaluator->evaluate( - $this->exactStringCondition + $this->exactStringCondition ) ); } @@ -338,7 +336,7 @@ public function testExactStringReturnsNullWhenAttrsIsDifferentTypeFromConditionV $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->exactStringCondition + $this->exactStringCondition ) ); } @@ -364,7 +362,7 @@ public function testExactIntReturnsTrueWhenAttrsEqualToConditionValue() $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->exactIntCondition + $this->exactIntCondition ) ); } @@ -377,7 +375,7 @@ public function testExactFloatReturnsTrueWhenAttrsEqualToConditionValue() $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->exactFloatCondition + $this->exactFloatCondition ) ); } @@ -390,7 +388,7 @@ public function testExactIntReturnsFalseWhenAttrsNotEqualToConditionValue() $this->assertFalse( $customAttrConditionEvaluator->evaluate( - $this->exactIntCondition + $this->exactIntCondition ) ); } @@ -403,7 +401,7 @@ public function testExactFloatReturnsFalseWhenAttrsNotEqualToConditionValue() $this->assertFalse( $customAttrConditionEvaluator->evaluate( - $this->exactFloatCondition + $this->exactFloatCondition ) ); } @@ -416,7 +414,7 @@ public function testExactIntReturnsNullWhenAttrsIsDifferentTypeFromConditionValu $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->exactIntCondition + $this->exactIntCondition ) ); @@ -426,7 +424,7 @@ public function testExactIntReturnsNullWhenAttrsIsDifferentTypeFromConditionValu $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->exactIntCondition + $this->exactIntCondition ) ); } @@ -434,23 +432,23 @@ public function testExactIntReturnsNullWhenAttrsIsDifferentTypeFromConditionValu public function testExactFloatReturnsNullWhenAttrsIsDifferentTypeFromConditionValue() { $customAttrConditionEvaluator = new CustomAttributeConditionEvaluator( - ['lasers_count' => 'hi'] + ['lasers_count' => 'hi'] ); $this->assertNull( - $customAttrConditionEvaluator->evaluate( + $customAttrConditionEvaluator->evaluate( $this->exactFloatCondition - ) + ) ); $customAttrConditionEvaluator = new CustomAttributeConditionEvaluator( - ['lasers_count' => true] + ['lasers_count' => true] ); $this->assertNull( - $customAttrConditionEvaluator->evaluate( + $customAttrConditionEvaluator->evaluate( $this->exactFloatCondition - ) + ) ); } @@ -488,7 +486,7 @@ public function testExactBoolReturnsTrueWhenAttrsEqualToConditionValue() $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->exactBoolCondition + $this->exactBoolCondition ) ); } @@ -501,7 +499,7 @@ public function testExactBoolReturnsFalseWhenAttrsNotEqualToConditionValue() $this->assertFalse( $customAttrConditionEvaluator->evaluate( - $this->exactBoolCondition + $this->exactBoolCondition ) ); } @@ -514,7 +512,7 @@ public function testExactBoolReturnsNullWhenAttrsIsDifferentTypeFromConditionVal $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->exactBoolCondition + $this->exactBoolCondition ) ); } @@ -527,7 +525,7 @@ public function testExactBoolReturnsNullWhenWhenNoUserProvidedValue() $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->exactBoolCondition + $this->exactBoolCondition ) ); } @@ -540,7 +538,7 @@ public function testSubstringReturnsTrueWhenConditionValueIsSubstringOfUserValue $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->substringCondition + $this->substringCondition ) ); } @@ -553,7 +551,7 @@ public function testSubstringReturnsFalseWhenConditionValueIsNotSubstringOfUserV $this->assertFalse( $customAttrConditionEvaluator->evaluate( - $this->substringCondition + $this->substringCondition ) ); } @@ -566,7 +564,7 @@ public function testSubstringReturnsNullWhenUserProvidedvalueNotAString() $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->substringCondition + $this->substringCondition ) ); } @@ -579,7 +577,7 @@ public function testSubstringReturnsNullWhenNoUserProvidedValue() $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->substringCondition + $this->substringCondition ) ); } @@ -592,7 +590,7 @@ public function testGreaterThanIntReturnsTrueWhenUserValueGreaterThanConditionVa $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->gtIntCondition + $this->gtIntCondition ) ); $customAttrConditionEvaluator = new CustomAttributeConditionEvaluator( @@ -601,7 +599,7 @@ public function testGreaterThanIntReturnsTrueWhenUserValueGreaterThanConditionVa $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->gtIntCondition + $this->gtIntCondition ) ); } @@ -614,7 +612,7 @@ public function testGreaterThanFloatReturnsTrueWhenUserValueGreaterThanCondition $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->gtFloatCondition + $this->gtFloatCondition ) ); $customAttrConditionEvaluator = new CustomAttributeConditionEvaluator( @@ -623,7 +621,7 @@ public function testGreaterThanFloatReturnsTrueWhenUserValueGreaterThanCondition $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->gtFloatCondition + $this->gtFloatCondition ) ); } @@ -636,7 +634,7 @@ public function testGreaterThanIntReturnsFalseWhenUserValueNotGreaterThanConditi $this->assertFalse( $customAttrConditionEvaluator->evaluate( - $this->gtIntCondition + $this->gtIntCondition ) ); $customAttrConditionEvaluator = new CustomAttributeConditionEvaluator( @@ -645,7 +643,7 @@ public function testGreaterThanIntReturnsFalseWhenUserValueNotGreaterThanConditi $this->assertFalse( $customAttrConditionEvaluator->evaluate( - $this->gtIntCondition + $this->gtIntCondition ) ); } @@ -658,7 +656,7 @@ public function testGreaterThanFloatReturnsFalseWhenUserValueNotGreaterThanCondi $this->assertFalse( $customAttrConditionEvaluator->evaluate( - $this->gtFloatCondition + $this->gtFloatCondition ) ); $customAttrConditionEvaluator = new CustomAttributeConditionEvaluator( @@ -667,7 +665,7 @@ public function testGreaterThanFloatReturnsFalseWhenUserValueNotGreaterThanCondi $this->assertFalse( $customAttrConditionEvaluator->evaluate( - $this->gtFloatCondition + $this->gtFloatCondition ) ); } @@ -680,7 +678,7 @@ public function testGreaterThanIntReturnsNullWhenUserValueIsNotANumber() $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->gtIntCondition + $this->gtIntCondition ) ); $customAttrConditionEvaluator = new CustomAttributeConditionEvaluator( @@ -689,7 +687,7 @@ public function testGreaterThanIntReturnsNullWhenUserValueIsNotANumber() $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->gtIntCondition + $this->gtIntCondition ) ); } @@ -702,7 +700,7 @@ public function testGreaterThanFloatReturnsNullWhenUserValueIsNotANumber() $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->gtFloatCondition + $this->gtFloatCondition ) ); $customAttrConditionEvaluator = new CustomAttributeConditionEvaluator( @@ -711,7 +709,7 @@ public function testGreaterThanFloatReturnsNullWhenUserValueIsNotANumber() $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->gtFloatCondition + $this->gtFloatCondition ) ); } @@ -724,7 +722,7 @@ public function testGreaterThanIntReturnsNullWhenNoUserProvidedValue() $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->gtIntCondition + $this->gtIntCondition ) ); } @@ -737,7 +735,7 @@ public function testGreaterThanFloatReturnsNullWhenNoUserProvidedValue() $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->gtFloatCondition + $this->gtFloatCondition ) ); } @@ -750,7 +748,7 @@ public function testLessThanIntReturnsTrueWhenUserValueLessThanConditionValue() $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->ltIntCondition + $this->ltIntCondition ) ); $customAttrConditionEvaluator = new CustomAttributeConditionEvaluator( @@ -759,7 +757,7 @@ public function testLessThanIntReturnsTrueWhenUserValueLessThanConditionValue() $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->ltIntCondition + $this->ltIntCondition ) ); } @@ -772,7 +770,7 @@ public function testLessThanFloatReturnsTrueWhenUserValueLessThanConditionValue( $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->ltFloatCondition + $this->ltFloatCondition ) ); $customAttrConditionEvaluator = new CustomAttributeConditionEvaluator( @@ -781,7 +779,7 @@ public function testLessThanFloatReturnsTrueWhenUserValueLessThanConditionValue( $this->assertTrue( $customAttrConditionEvaluator->evaluate( - $this->ltFloatCondition + $this->ltFloatCondition ) ); } @@ -794,7 +792,7 @@ public function testLessThanIntReturnsFalseWhenUserValueNotLessThanConditionValu $this->assertFalse( $customAttrConditionEvaluator->evaluate( - $this->ltIntCondition + $this->ltIntCondition ) ); $customAttrConditionEvaluator = new CustomAttributeConditionEvaluator( @@ -803,7 +801,7 @@ public function testLessThanIntReturnsFalseWhenUserValueNotLessThanConditionValu $this->assertFalse( $customAttrConditionEvaluator->evaluate( - $this->ltIntCondition + $this->ltIntCondition ) ); } @@ -816,7 +814,7 @@ public function testLessThanFloatReturnsFalseWhenUserValueNotLessThanConditionVa $this->assertFalse( $customAttrConditionEvaluator->evaluate( - $this->ltFloatCondition + $this->ltFloatCondition ) ); $customAttrConditionEvaluator = new CustomAttributeConditionEvaluator( @@ -825,7 +823,7 @@ public function testLessThanFloatReturnsFalseWhenUserValueNotLessThanConditionVa $this->assertFalse( $customAttrConditionEvaluator->evaluate( - $this->ltFloatCondition + $this->ltFloatCondition ) ); } @@ -838,7 +836,7 @@ public function testLessThanIntReturnsNullWhenUserValueIsNotANumber() $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->ltIntCondition + $this->ltIntCondition ) ); @@ -847,7 +845,7 @@ public function testLessThanIntReturnsNullWhenUserValueIsNotANumber() ); $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->ltIntCondition + $this->ltIntCondition ) ); } @@ -860,7 +858,7 @@ public function testLessThanFloatReturnsNullWhenUserValueIsNotANumber() $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->ltFloatCondition + $this->ltFloatCondition ) ); $customAttrConditionEvaluator = new CustomAttributeConditionEvaluator( @@ -869,7 +867,7 @@ public function testLessThanFloatReturnsNullWhenUserValueIsNotANumber() $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->ltFloatCondition + $this->ltFloatCondition ) ); } @@ -882,7 +880,7 @@ public function testLessThanIntReturnsNullWhenNoUserProvidedValue() $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->ltIntCondition + $this->ltIntCondition ) ); } @@ -895,7 +893,7 @@ public function testLessThanFloatReturnsNullWhenNoUserProvidedValue() $this->assertNull( $customAttrConditionEvaluator->evaluate( - $this->ltFloatCondition + $this->ltFloatCondition ) ); } diff --git a/tests/UtilsTests/EventTagUtilsTest.php b/tests/UtilsTests/EventTagUtilsTest.php index 672ab86a..5e561f5f 100644 --- a/tests/UtilsTests/EventTagUtilsTest.php +++ b/tests/UtilsTests/EventTagUtilsTest.php @@ -1,6 +1,6 @@ <?php /** - * Copyright 2017-2018, Optimizely + * Copyright 2017-2019, Optimizely * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,8 +25,8 @@ class EventTagUtilsTest extends \PHPUnit_Framework_TestCase { // The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format). http://php.net/manual/en/language.types.float.php // PHP_FLOAT_MAX - Available as of PHP7.2.0 http://php.net/manual/en/reserved.constants.php - const max_float = 1.8e307; - const min_float = -1.8e307; + const MAX_FLOAT = 1.8e307; + const MIN_FLOAT = -1.8e307; protected $loggerMock; protected function setUp() @@ -174,7 +174,7 @@ public function testGetNumericValueWithNonNumericValueTag() $this->assertNull(EventTagUtils::getNumericValue(array('value' => 'abcd'), $this->loggerMock)); $this->assertNull(EventTagUtils::getNumericValue(array('value' => true), $this->loggerMock)); - $this->assertNull(EventTagUtils::getNumericValue(array('value' => array(1, 2, 3)),$this->loggerMock)); + $this->assertNull(EventTagUtils::getNumericValue(array('value' => array(1, 2, 3)), $this->loggerMock)); $this->assertNull(EventTagUtils::getNumericValue(array('value' => false), $this->loggerMock)); $this->assertNull(EventTagUtils::getNumericValue(array('value' => array()), $this->loggerMock)); $this->assertNull(EventTagUtils::getNumericValue(array('value' => '1,234'), $this->loggerMock)); @@ -189,7 +189,7 @@ public function testGetNumericValueWithINForNANValueTag() $this->assertNull(EventTagUtils::getNumericValue(array('value' => floatval(NAN)), $this->loggerMock)); $this->assertNull(EventTagUtils::getNumericValue(array('value' => floatval(INF)), $this->loggerMock)); $this->assertNull(EventTagUtils::getNumericValue(array('value' => floatval(-INF)), $this->loggerMock)); - $this->assertNull(EventTagUtils::getNumericValue(array('value' => (self::max_float*10)), $this->loggerMock)); + $this->assertNull(EventTagUtils::getNumericValue(array('value' => (self::MAX_FLOAT*10)), $this->loggerMock)); } // Test that the correct numeric value is returned @@ -214,13 +214,13 @@ public function testGetNumericValueWithValueTag() $this->loggerMock->expects($this->at(0)) ->method('log') - ->with(Logger::INFO, "The numeric metric value ".self::max_float." will be sent to results."); - $this->assertSame(self::max_float, EventTagUtils::getNumericValue(array('value' => self::max_float), $this->loggerMock)); + ->with(Logger::INFO, "The numeric metric value ".self::MAX_FLOAT." will be sent to results."); + $this->assertSame(self::MAX_FLOAT, EventTagUtils::getNumericValue(array('value' => self::MAX_FLOAT), $this->loggerMock)); $this->loggerMock->expects($this->at(0)) ->method('log') - ->with(Logger::INFO, "The numeric metric value ".self::min_float." will be sent to results."); - $this->assertSame(self::min_float, EventTagUtils::getNumericValue(array('value' => self::min_float), $this->loggerMock)); + ->with(Logger::INFO, "The numeric metric value ".self::MIN_FLOAT." will be sent to results."); + $this->assertSame(self::MIN_FLOAT, EventTagUtils::getNumericValue(array('value' => self::MIN_FLOAT), $this->loggerMock)); $this->loggerMock->expects($this->at(0)) ->method('log') diff --git a/tests/UtilsTests/ValidatorTest.php b/tests/UtilsTests/ValidatorTest.php index be1e9769..a30ce62b 100644 --- a/tests/UtilsTests/ValidatorTest.php +++ b/tests/UtilsTests/ValidatorTest.php @@ -135,10 +135,10 @@ public function testIsFiniteNumberWithInvalidValues() $this->assertFalse(Validator::IsFiniteNumber(INF)); $this->assertFalse(Validator::IsFiniteNumber(-INF)); $this->assertFalse(Validator::IsFiniteNumber(NAN)); - $this->assertFalse(Validator::IsFiniteNumber(pow(2,53) + 1)); - $this->assertFalse(Validator::IsFiniteNumber(-pow(2,53) - 1)); - $this->assertFalse(Validator::IsFiniteNumber(pow(2,53) + 2.0)); - $this->assertFalse(Validator::IsFiniteNumber(-pow(2,53) - 2.0)); + $this->assertFalse(Validator::IsFiniteNumber(pow(2, 53) + 1)); + $this->assertFalse(Validator::IsFiniteNumber(-pow(2, 53) - 1)); + $this->assertFalse(Validator::IsFiniteNumber(pow(2, 53) + 2.0)); + $this->assertFalse(Validator::IsFiniteNumber(-pow(2, 53) - 2.0)); } public function testIsFiniteNumberWithValidValues() @@ -147,9 +147,9 @@ public function testIsFiniteNumberWithValidValues() $this->assertTrue(Validator::IsFiniteNumber(5)); $this->assertTrue(Validator::IsFiniteNumber(5.5)); // float pow(2,53) + 1.0 evaluates to float pow(2,53) - $this->assertTrue(Validator::IsFiniteNumber(pow(2,53) + 1.0)); - $this->assertTrue(Validator::IsFiniteNumber(-pow(2,53) - 1.0)); - $this->assertTrue(Validator::IsFiniteNumber(pow(2,53))); + $this->assertTrue(Validator::IsFiniteNumber(pow(2, 53) + 1.0)); + $this->assertTrue(Validator::IsFiniteNumber(-pow(2, 53) - 1.0)); + $this->assertTrue(Validator::IsFiniteNumber(pow(2, 53))); } public function testAreEventTagsValidValidEventTags() @@ -291,7 +291,6 @@ public function testIsUserInExperimentNoAudienceUsedInExperiment() [] ) ); - } // test that isUserInExperiment returns false when some audience is attached to experiment @@ -485,8 +484,8 @@ public function testDoesArrayContainOnlyStringKeys() { // Valid values $this->assertTrue(Validator::doesArrayContainOnlyStringKeys( - ["name"=> "favorite_ice_cream", "type"=> "custom_attribute", "match"=> "exists"]) - ); + ["name"=> "favorite_ice_cream", "type"=> "custom_attribute", "match"=> "exists"] + )); // Invalid values $this->assertFalse(Validator::doesArrayContainOnlyStringKeys([]));