Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@
],
"require": {
"php": ">=5.5",
"justinrainbow/json-schema": "^1.6 || ^2.0 || ^4.0",
"justinrainbow/json-schema": "^1.6 || ^2.0 || ^4.0 || ^5.0",
"lastguest/murmurhash": "1.3.0",
"guzzlehttp/guzzle": "~5.3|~6.2",
"monolog/monolog": "~1.21",
"icecave/parity": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "~4.8|~5.0",
"satooshi/php-coveralls": "v1.0.1"
"phpunit/phpunit": "^4.8|^5.0",
"php-coveralls/php-coveralls": "v2.0.0"
},
"autoload": {
"psr-4": {
Expand Down
59 changes: 32 additions & 27 deletions src/Optimizely/Event/Builder/EventBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -180,45 +180,50 @@ private function getImpressionParams(Experiment $experiment, $variationId)
private function getConversionParams($config, $eventKey, $experimentVariationMap, $eventTags)
{
$conversionParams = [];
$singleSnapshot = [];
$decisions = [];

foreach ($experimentVariationMap as $experimentId => $variationId) {
$singleSnapshot = [];


$experiment = $config->getExperimentFromId($experimentId);
$eventEntity = $config->getEvent($eventKey);

$singleSnapshot[DECISIONS] = [
[
CAMPAIGN_ID => $experiment->getLayerId(),
EXPERIMENT_ID => $experiment->getId(),
VARIATION_ID => $variationId
]
];

$singleSnapshot[EVENTS] = [
[
ENTITY_ID => $eventEntity->getId(),
TIMESTAMP => time()*1000,
UUID => GeneratorUtils::getRandomUuid(),
KEY => $eventKey
]
$decision = [
CAMPAIGN_ID => $experiment->getLayerId(),
EXPERIMENT_ID => $experiment->getId(),
VARIATION_ID => $variationId
];
$decisions [] = $decision;
}

if (!is_null($eventTags)) {
$revenue = EventTagUtils::getRevenueValue($eventTags, $this->_logger);
if (!is_null($revenue)) {
$singleSnapshot[EVENTS][0][EventTagUtils::REVENUE_EVENT_METRIC_NAME] = $revenue;
}
$eventDict = [
ENTITY_ID => $eventEntity->getId(),
TIMESTAMP => time()*1000,
UUID => GeneratorUtils::getRandomUuid(),
KEY => $eventKey
];

$eventValue = EventTagUtils::getNumericValue($eventTags, $this->_logger);
if (!is_null($eventValue)) {
$singleSnapshot[EVENTS][0][EventTagUtils::NUMERIC_EVENT_METRIC_NAME] = $eventValue;
}
if (!is_null($eventTags)) {
$revenue = EventTagUtils::getRevenueValue($eventTags, $this->_logger);
if (!is_null($revenue)) {
$eventDict[EventTagUtils::REVENUE_EVENT_METRIC_NAME] = $revenue;
}

$singleSnapshot[EVENTS][0]['tags'] = $eventTags;
$eventValue = EventTagUtils::getNumericValue($eventTags, $this->_logger);
if (!is_null($eventValue)) {
$eventDict[EventTagUtils::NUMERIC_EVENT_METRIC_NAME] = $eventValue;
}

$conversionParams [] = $singleSnapshot;
if(count($eventTags) > 0) {
$eventDict['tags'] = $eventTags;
}
}

$singleSnapshot[DECISIONS] = $decisions;
$singleSnapshot[EVENTS] [] = $eventDict;
$conversionParams [] = $singleSnapshot;

return $conversionParams;
}

Expand Down
22 changes: 22 additions & 0 deletions src/Optimizely/Exceptions/InvalidDatafileVersionException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php
/**
* Copyright 2018, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Optimizely\Exceptions;

class InvalidDatafileVersionException extends OptimizelyException
{
}
29 changes: 22 additions & 7 deletions src/Optimizely/Optimizely.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@

use Exception;
use Optimizely\Exceptions\InvalidAttributeException;
use Optimizely\Exceptions\InvalidDatafileVersionException;
use Optimizely\Exceptions\InvalidEventTagException;
use Optimizely\Exceptions\InvalidInputException;
use Throwable;
use Monolog\Logger;
use Optimizely\DecisionService\DecisionService;
Expand All @@ -36,6 +38,7 @@
use Optimizely\Notification\NotificationCenter;
use Optimizely\Notification\NotificationType;
use Optimizely\UserProfile\UserProfileServiceInterface;
use Optimizely\Utils\Errors;
use Optimizely\Utils\Validator;
use Optimizely\Utils\VariableTypeUtils;

Expand Down Expand Up @@ -120,15 +123,14 @@ public function __construct(

try {
$this->_config = new ProjectConfig($datafile, $this->_logger, $this->_errorHandler);
} catch (Throwable $exception) {
$this->_isValid = false;
$this->_logger = new DefaultLogger();
$this->_logger->log(Logger::ERROR, 'Provided "datafile" is in an invalid format.');
return;
} catch (Exception $exception) {
$this->_isValid = false;
$this->_logger = new DefaultLogger();
$this->_logger->log(Logger::ERROR, 'Provided "datafile" is in an invalid format.');
$defaultLogger = new DefaultLogger();
$errorMsg = $exception->getCode() == InvalidDatafileVersionException::class ? $exception->getMessage() : sprintf(Errors::INVALID_FORMAT, 'datafile');
$errorToHandle = $exception->getCode() == InvalidDatafileVersionException::class ? new InvalidDatafileVersionException($errorMsg) : new InvalidInputException($errorMsg);
$defaultLogger->log(Logger::ERROR, $errorMsg);
$this->_logger->log(Logger::ERROR, $errorMsg);
$this->_errorHandler->handleError($errorToHandle);
return;
}

Expand Down Expand Up @@ -728,4 +730,17 @@ public function getFeatureVariableString($featureFlagKey, $variableKey, $userId,

return $variableValue;
}

/**
* Determine if the instance of the Optimizely client is valid.
* An instance can be deemed invalid if it was not initialized
* properly due to an invalid datafile being passed in.
*
* @return True if the Optimizely instance is valid.
* False if the Optimizely instance is not valid.
*/
public function isValid()
{
return $this->_isValid;
}
}
11 changes: 11 additions & 0 deletions src/Optimizely/ProjectConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
use Optimizely\ErrorHandler\ErrorHandlerInterface;
use Optimizely\Exceptions\InvalidAttributeException;
use Optimizely\Exceptions\InvalidAudienceException;
use Optimizely\Exceptions\InvalidDatafileVersionException;
use Optimizely\Exceptions\InvalidEventException;
use Optimizely\Exceptions\InvalidExperimentException;
use Optimizely\Exceptions\InvalidFeatureFlagException;
Expand All @@ -50,6 +51,9 @@
class ProjectConfig
{
const RESERVED_ATTRIBUTE_PREFIX = '$opt_';
const V2 = '2';
const V3 = '3';
const V4 = '4';

/**
* @var string Version of the datafile.
Expand Down Expand Up @@ -185,10 +189,17 @@ class ProjectConfig
*/
public function __construct($datafile, $logger, $errorHandler)
{
$supportedVersions = array(self::V2, self::V3, self::V4);
$config = json_decode($datafile, true);
$this->_logger = $logger;
$this->_errorHandler = $errorHandler;
$this->_version = $config['version'];
if(!in_array($this->_version, $supportedVersions)){
throw new InvalidDatafileVersionException(
"This version of the PHP SDK does not support the given datafile version: {$this->_version}."
);
}

$this->_accountId = $config['accountId'];
$this->_projectId = $config['projectId'];
$this->_anonymizeIP = isset($config['anonymizeIP'])? $config['anonymizeIP'] : false;
Expand Down
21 changes: 21 additions & 0 deletions src/Optimizely/Utils/Errors.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<?php
/**
* Copyright 2018, Optimizely
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Optimizely\Utils;
class Errors
{
const INVALID_FORMAT = 'Provided %s is in an invalid format.';
}
66 changes: 66 additions & 0 deletions tests/EventTests/EventBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -823,4 +823,70 @@ public function testCreateConversionEventWithUserAgentAttribute()
$result = $this->areLogEventsEqual($expectedLogEvent, $logEvent);
$this->assertTrue($result[0], $result[1]);
}

public function testCreateConversionEventWhenEventUsedInMultipleExp()
{
$eventTags = [
'revenue' => 4200,
'value' => 1.234,
'non-revenue' => 'abc'
];
$this->expectedEventParams['visitors'][0]['snapshots'][0]['decisions'][] = [
'campaign_id' => '4',
'experiment_id' => '122230',
'variation_id' => '122234'
];

$this->expectedEventParams['visitors'][0]['snapshots'][0]['events'][0] = [
'entity_id' => '7718020065',
'timestamp' => $this->timestamp,
'uuid' => $this->uuid,
'key' => 'multi_exp_event',
'revenue' => 4200,
'value' => 1.234,
'tags' => $eventTags,
];

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'
]);

$decisions = [
'7716830082' => '7721010009',
'122230' => '122234'
];
$userAttributes = [
'device_type' => 'iPhone',
'location' => 'SF'
];

$logEvent = $this->eventBuilder->createConversionEvent(
$this->config,
'multi_exp_event',
$decisions,
$this->testUserId,
$userAttributes,
$eventTags
);
$expectedLogEvent = new LogEvent(
$this->expectedEventUrl,
$this->expectedEventParams,
$this->expectedEventHttpVerb,
$this->expectedEventHeaders
);

$logEvent = $this->fakeParamsToReconcile($logEvent);
$result = $this->areLogEventsEqual($expectedLogEvent, $logEvent);
$this->assertTrue($result[0], $result[1]);

}
}
50 changes: 50 additions & 0 deletions tests/OptimizelyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@
use Optimizely\ErrorHandler\NoOpErrorHandler;
use Optimizely\Event\LogEvent;
use Optimizely\Exceptions\InvalidAttributeException;
use Optimizely\Exceptions\InvalidDatafileVersionException;
use Optimizely\Exceptions\InvalidEventTagException;
use Optimizely\Exceptions\InvalidInputException;
use Optimizely\Logger\NoOpLogger;
use Optimizely\Notification\NotificationCenter;
use Optimizely\Notification\NotificationType;
Expand Down Expand Up @@ -74,6 +76,18 @@ public function setUp()
->getMock();
}

public function testIsValidForInvalidOptimizelyObject()
{
$optlyObject = new Optimizely('Random datafile');
$this->assertFalse($optlyObject->isValid());
}

public function testIsValidForValidOptimizelyObject()
{
$optlyObject = new Optimizely($this->datafile);
$this->assertTrue($optlyObject->isValid());
}

public function testInitValidEventDispatcher()
{
$validDispatcher = new ValidEventDispatcher();
Expand Down Expand Up @@ -134,6 +148,42 @@ public function testInitInvalidErrorHandler()
$this->fail('Unexpected behavior. Invalid error handler went through.');
}

public function testInitUnSupportedDatafileVersion()
{
$errorHandlerMock = $this->getMockBuilder(NoOpErrorHandler::class)
->setMethods(array('handleError'))
->getMock();
$errorHandlerMock->expects($this->once())
->method('handleError')
->with(new InvalidDatafileVersionException('This version of the PHP SDK does not support the given datafile version: 5.'));
$optlyObject = new Optimizely(
UNSUPPORTED_DATAFILE,
null,
new DefaultLogger(Logger::INFO, self::OUTPUT_STREAM),
$errorHandlerMock,
true
);
$this->expectOutputRegex("/This version of the PHP SDK does not support the given datafile version: 5./");
}

public function testInitDatafileInvalidFormat()
{
$errorHandlerMock = $this->getMockBuilder(NoOpErrorHandler::class)
->setMethods(array('handleError'))
->getMock();
$errorHandlerMock->expects($this->once())
->method('handleError')
->with(new InvalidInputException('Provided datafile is in an invalid format.'));
$optlyObject = new Optimizely(
'{"version": "2"}',
null,
new DefaultLogger(Logger::INFO, self::OUTPUT_STREAM),
$errorHandlerMock,
true
);
$this->expectOutputRegex('/Provided datafile is in an invalid format./');
}

public function testValidateDatafileInvalidFileJsonValidationNotSkipped()
{
$validateInputsMethod = new \ReflectionMethod('Optimizely\Optimizely', 'validateDatafile');
Expand Down
Loading