Skip to content

Commit

Permalink
Merge pull request #93 from maxbeckers/feature/code_optimization
Browse files Browse the repository at this point in the history
Feature/code optimization
  • Loading branch information
maxbeckers authored Jul 28, 2022
2 parents c819684 + 2aa467c commit b18996e
Show file tree
Hide file tree
Showing 38 changed files with 329 additions and 173 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ composer.lock
.php_cs.cache
/.idea/
.phpunit.result.cache
.phpunit.cache/
2 changes: 1 addition & 1 deletion .php-cs-fixer.cache

Large diffs are not rendered by default.

20 changes: 6 additions & 14 deletions src/Helper/DeviceAddressInformationHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,23 +92,15 @@ private function apiCall(string $url, string $token): DeviceAddressInformation

/*
* Api Call response codes:
* 200 OK Successfully got the address associated with this deviceId.
* 204 No Content The query did not return any results.
* 200 OK Successfully got the address associated with this deviceId.
* 204 No Content The query did not return any results.
* 403 Forbidden The authentication token is invalid or doesn’t have access to the resource.
* 405 Method Not Allowed The method is not supported.
* 405 Method Not Allowed The method is not supported.
* 429 Too Many Requests The skill has been throttled due to an excessive number of requests.
* 500 Internal Error An unexpected error occurred.
* 500 Internal Error An unexpected error occurred.
*/
switch ($response->getStatusCode()) {
case 200:
break;
case 204:
case 403:
case 405:
case 429:
case 500:
default:
throw new DeviceApiCallException(sprintf('Error in api call (status code:"%s")', $response->getStatusCode()));
if (200 !== $response->getStatusCode()) {
throw new DeviceApiCallException(sprintf('Error in api call (status code:"%s")', $response->getStatusCode()));
}

return DeviceAddressInformation::fromApiResponse(json_decode($response->getBody()->getContents(), true));
Expand Down
33 changes: 33 additions & 0 deletions src/Helper/PropertyHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace MaxBeckers\AmazonAlexa\Helper;

/**
* This helper class simplifies the property handling.
*
* @author Maximilian Beckers <[email protected]>
*/
class PropertyHelper
{
/**
* @param array $data
* @param string $key
*
* @return string|null
*/
public static function checkNullValueString(array $data, string $key)
{
return isset($data[$key]) ? $data[$key] : null;
}

/**
* @param array $data
* @param string $key
*
* @return int|null
*/
public static function checkNullValueInt(array $data, string $key)
{
return isset($data[$key]) ? $data[$key] : null;
}
}
22 changes: 22 additions & 0 deletions src/Helper/SerializeValueMapper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace MaxBeckers\AmazonAlexa\Helper;

/**
* This trait is helpful for the property to ArrayObject mapping.
*
* @author Maximilian Beckers <[email protected]>
*/
trait SerializeValueMapper
{
/**
* @param \ArrayObject $data
* @param string $property
*/
protected function valueToArrayIfSet(\ArrayObject $data, string $property)
{
if (null !== $this->{$property}) {
$data[$property] = $this->{$property};
}
}
}
4 changes: 3 additions & 1 deletion src/Request/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace MaxBeckers\AmazonAlexa\Request;

use MaxBeckers\AmazonAlexa\Helper\PropertyHelper;

/**
* Represents the current Skill.
*
Expand All @@ -23,7 +25,7 @@ public static function fromAmazonRequest(array $amazonRequest): self
{
$application = new self();

$application->applicationId = isset($amazonRequest['applicationId']) ? $amazonRequest['applicationId'] : null;
$application->applicationId = PropertyHelper::checkNullValueString($amazonRequest, 'applicationId');

return $application;
}
Expand Down
8 changes: 5 additions & 3 deletions src/Request/AudioPlayer.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace MaxBeckers\AmazonAlexa\Request;

use MaxBeckers\AmazonAlexa\Helper\PropertyHelper;

/**
* @author Maximilian Beckers <[email protected]>
*/
Expand Down Expand Up @@ -38,9 +40,9 @@ public static function fromAmazonRequest(array $amazonRequest): self
{
$audioPlayer = new self();

$audioPlayer->token = isset($amazonRequest['token']) ? $amazonRequest['token'] : null;
$audioPlayer->offsetInMilliseconds = isset($amazonRequest['offsetInMilliseconds']) ? (int) $amazonRequest['offsetInMilliseconds'] : null;
$audioPlayer->playerActivity = isset($amazonRequest['playerActivity']) ? $amazonRequest['playerActivity'] : null;
$audioPlayer->token = PropertyHelper::checkNullValueString($amazonRequest, 'token');
$audioPlayer->offsetInMilliseconds = PropertyHelper::checkNullValueInt($amazonRequest, 'offsetInMilliseconds');
$audioPlayer->playerActivity = PropertyHelper::checkNullValueString($amazonRequest, 'playerActivity');

return $audioPlayer;
}
Expand Down
6 changes: 4 additions & 2 deletions src/Request/Device.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace MaxBeckers\AmazonAlexa\Request;

use MaxBeckers\AmazonAlexa\Helper\PropertyHelper;

/**
* @author Maximilian Beckers <[email protected]>
*/
Expand Down Expand Up @@ -31,9 +33,9 @@ public static function fromAmazonRequest(array $amazonRequest): self
{
$device = new self();

$device->deviceId = isset($amazonRequest['deviceId']) ? $amazonRequest['deviceId'] : null;
$device->deviceId = PropertyHelper::checkNullValueString($amazonRequest, 'deviceId');
$device->supportedInterfaces = isset($amazonRequest['supportedInterfaces']) ? (array) $amazonRequest['supportedInterfaces'] : [];
$device->accessToken = isset($amazonRequest['accessToken']) ? $amazonRequest['accessToken'] : null;
$device->accessToken = PropertyHelper::checkNullValueString($amazonRequest, 'accessToken');

return $device;
}
Expand Down
18 changes: 10 additions & 8 deletions src/Request/Device/DeviceAddressInformation.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace MaxBeckers\AmazonAlexa\Request\Device;

use MaxBeckers\AmazonAlexa\Helper\PropertyHelper;

/**
* @author Maximilian Beckers <[email protected]>
*/
Expand Down Expand Up @@ -56,14 +58,14 @@ public static function fromApiResponse(array $amazonApiResponse): self
{
$deviceAddressInformation = new self();

$deviceAddressInformation->stateOrRegion = isset($amazonApiResponse['stateOrRegion']) ? $amazonApiResponse['stateOrRegion'] : null;
$deviceAddressInformation->city = isset($amazonApiResponse['city']) ? $amazonApiResponse['city'] : null;
$deviceAddressInformation->countryCode = isset($amazonApiResponse['countryCode']) ? $amazonApiResponse['countryCode'] : null;
$deviceAddressInformation->postalCode = isset($amazonApiResponse['postalCode']) ? $amazonApiResponse['postalCode'] : null;
$deviceAddressInformation->addressLine1 = isset($amazonApiResponse['addressLine1']) ? $amazonApiResponse['addressLine1'] : null;
$deviceAddressInformation->addressLine2 = isset($amazonApiResponse['addressLine2']) ? $amazonApiResponse['addressLine2'] : null;
$deviceAddressInformation->addressLine3 = isset($amazonApiResponse['addressLine3']) ? $amazonApiResponse['addressLine3'] : null;
$deviceAddressInformation->districtOrCounty = isset($amazonApiResponse['districtOrCounty']) ? $amazonApiResponse['districtOrCounty'] : null;
$deviceAddressInformation->stateOrRegion = PropertyHelper::checkNullValueString($amazonApiResponse, 'stateOrRegion');
$deviceAddressInformation->city = PropertyHelper::checkNullValueString($amazonApiResponse, 'city');
$deviceAddressInformation->countryCode = PropertyHelper::checkNullValueString($amazonApiResponse, 'countryCode');
$deviceAddressInformation->postalCode = PropertyHelper::checkNullValueString($amazonApiResponse, 'postalCode');
$deviceAddressInformation->addressLine1 = PropertyHelper::checkNullValueString($amazonApiResponse, 'addressLine1');
$deviceAddressInformation->addressLine2 = PropertyHelper::checkNullValueString($amazonApiResponse, 'addressLine2');
$deviceAddressInformation->addressLine3 = PropertyHelper::checkNullValueString($amazonApiResponse, 'addressLine3');
$deviceAddressInformation->districtOrCounty = PropertyHelper::checkNullValueString($amazonApiResponse, 'districtOrCounty');

return $deviceAddressInformation;
}
Expand Down
77 changes: 46 additions & 31 deletions src/Request/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use MaxBeckers\AmazonAlexa\Exception\MissingRequestDataException;
use MaxBeckers\AmazonAlexa\Exception\MissingRequiredHeaderException;
use MaxBeckers\AmazonAlexa\Helper\PropertyHelper;
use MaxBeckers\AmazonAlexa\Request\Request\AbstractRequest;
use MaxBeckers\AmazonAlexa\Request\Request\AlexaSkillEvent\SkillAccountLinkedRequest;
use MaxBeckers\AmazonAlexa\Request\Request\AlexaSkillEvent\SkillDisabledRequest;
Expand Down Expand Up @@ -38,30 +39,30 @@ class Request
*/
const REQUEST_TYPES = [
// Standard types
IntentRequest::TYPE => IntentRequest::class,
LaunchRequest::TYPE => LaunchRequest::class,
SessionEndedRequest::TYPE => SessionEndedRequest::class,
IntentRequest::TYPE => IntentRequest::class,
LaunchRequest::TYPE => LaunchRequest::class,
SessionEndedRequest::TYPE => SessionEndedRequest::class,
// AudioPlayer types
PlaybackStartedRequest::TYPE => PlaybackStartedRequest::class,
PlaybackNearlyFinishedRequest::TYPE => PlaybackNearlyFinishedRequest::class,
PlaybackFinishedRequest::TYPE => PlaybackFinishedRequest::class,
PlaybackStoppedRequest::TYPE => PlaybackStoppedRequest::class,
PlaybackFailedRequest::TYPE => PlaybackFailedRequest::class,
PlaybackStartedRequest::TYPE => PlaybackStartedRequest::class,
PlaybackNearlyFinishedRequest::TYPE => PlaybackNearlyFinishedRequest::class,
PlaybackFinishedRequest::TYPE => PlaybackFinishedRequest::class,
PlaybackStoppedRequest::TYPE => PlaybackStoppedRequest::class,
PlaybackFailedRequest::TYPE => PlaybackFailedRequest::class,
// PlaybackController types
NextCommandIssued::TYPE => NextCommandIssued::class,
PauseCommandIssued::TYPE => PauseCommandIssued::class,
PlayCommandIssued::TYPE => PlayCommandIssued::class,
PreviousCommandIssued::TYPE => PreviousCommandIssued::class,
NextCommandIssued::TYPE => NextCommandIssued::class,
PauseCommandIssued::TYPE => PauseCommandIssued::class,
PlayCommandIssued::TYPE => PlayCommandIssued::class,
PreviousCommandIssued::TYPE => PreviousCommandIssued::class,
// System types
ExceptionEncounteredRequest::TYPE => ExceptionEncounteredRequest::class,
ExceptionEncounteredRequest::TYPE => ExceptionEncounteredRequest::class,
// Display types
ElementSelectedRequest::TYPE => ElementSelectedRequest::class,
ElementSelectedRequest::TYPE => ElementSelectedRequest::class,
// Game engine types
InputHandlerEvent::TYPE => InputHandlerEvent::class,
InputHandlerEvent::TYPE => InputHandlerEvent::class,
// can fulfill intent
CanFulfillIntentRequest::TYPE => CanFulfillIntentRequest::class,
CanFulfillIntentRequest::TYPE => CanFulfillIntentRequest::class,
// Connections Response Request
ConnectionsResponseRequest::TYPE => ConnectionsResponseRequest::class,
ConnectionsResponseRequest::TYPE => ConnectionsResponseRequest::class,
// Skill event types
SkillAccountLinkedRequest::TYPE => SkillAccountLinkedRequest::class,
SkillEnabledRequest::TYPE => SkillEnabledRequest::class,
Expand Down Expand Up @@ -110,8 +111,8 @@ class Request
* @param string $signatureCertChainUrl
* @param string $signature
*
* @throws MissingRequestDataException
* @throws MissingRequiredHeaderException
* @throws MissingRequestDataException
*
* @return Request
*/
Expand All @@ -122,23 +123,14 @@ public static function fromAmazonRequest(string $amazonRequestBody, string $sign
$request->signatureCertChainUrl = $signatureCertChainUrl;
$request->signature = $signature;
$request->amazonRequestBody = $amazonRequestBody;
$amazonRequest = json_decode($amazonRequestBody, true);
$amazonRequest = (array) json_decode($amazonRequestBody, true);

$request->version = isset($amazonRequest['version']) ? $amazonRequest['version'] : null;
$request->version = PropertyHelper::checkNullValueString($amazonRequest, 'version');
$request->session = isset($amazonRequest['session']) ? Session::fromAmazonRequest($amazonRequest['session']) : null;
$request->context = isset($amazonRequest['context']) ? Context::fromAmazonRequest($amazonRequest['context']) : null;

if (isset($amazonRequest['request']['type']) && isset(self::REQUEST_TYPES[$amazonRequest['request']['type']])) {
$request->request = (self::REQUEST_TYPES[$amazonRequest['request']['type']])::fromAmazonRequest($amazonRequest['request']);
} else {
throw new MissingRequestDataException();
}

if ($request->request->validateSignature()) {
if (!$request->signatureCertChainUrl || !$request->signature) {
throw new MissingRequiredHeaderException();
}
}
$request->setRequest($amazonRequest);
$request->checkSignature();

return $request;
}
Expand All @@ -157,4 +149,27 @@ public function getApplicationId()

return null;
}

/**
* @param array $amazonRequest
*
* @throws MissingRequestDataException
*/
private function setRequest(array $amazonRequest)
{
if (!isset($amazonRequest['request']['type']) || !isset(self::REQUEST_TYPES[$amazonRequest['request']['type']])) {
throw new MissingRequestDataException();
}
$this->request = (self::REQUEST_TYPES[$amazonRequest['request']['type']])::fromAmazonRequest($amazonRequest['request']);
}

/**
* @throws MissingRequiredHeaderException
*/
private function checkSignature()
{
if ($this->request->validateSignature() && (!$this->signatureCertChainUrl || !$this->signature)) {
throw new MissingRequiredHeaderException();
}
}
}
4 changes: 3 additions & 1 deletion src/Request/Request/AlexaSkillEvent/Permission.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace MaxBeckers\AmazonAlexa\Request\Request\AlexaSkillEvent;

use MaxBeckers\AmazonAlexa\Helper\PropertyHelper;

/**
* @author Maximilian Beckers <[email protected]>
*/
Expand All @@ -21,7 +23,7 @@ public static function fromAmazonRequest(array $amazonRequest): self
{
$permission = new self();

$permission->scope = isset($amazonRequest['scope']) ? $amazonRequest['scope'] : null;
$permission->scope = PropertyHelper::checkNullValueString($amazonRequest, 'scope');

return $permission;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace MaxBeckers\AmazonAlexa\Request\Request\AlexaSkillEvent;

use MaxBeckers\AmazonAlexa\Helper\PropertyHelper;

/**
* @author Maximilian Beckers <[email protected]>
*/
Expand All @@ -21,7 +23,7 @@ public static function fromAmazonRequest(array $amazonRequest): self
{
$body = new self();

$body->accessToken = isset($amazonRequest['accessToken']) ? $amazonRequest['accessToken'] : null;
$body->accessToken = PropertyHelper::checkNullValueString($amazonRequest, 'accessToken');

return $body;
}
Expand Down
4 changes: 3 additions & 1 deletion src/Request/Request/AlexaSkillEvent/SkillDisabledBody.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace MaxBeckers\AmazonAlexa\Request\Request\AlexaSkillEvent;

use MaxBeckers\AmazonAlexa\Helper\PropertyHelper;

/**
* @author Maximilian Beckers <[email protected]>
*/
Expand All @@ -24,7 +26,7 @@ public static function fromAmazonRequest(array $amazonRequest): self
{
$body = new self();

$body->userInformationPersistenceStatus = isset($amazonRequest['userInformationPersistenceStatus']) ? $amazonRequest['userInformationPersistenceStatus'] : null;
$body->userInformationPersistenceStatus = PropertyHelper::checkNullValueString($amazonRequest, 'userInformationPersistenceStatus');

return $body;
}
Expand Down
3 changes: 2 additions & 1 deletion src/Request/Request/AudioPlayer/AudioPlayerRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace MaxBeckers\AmazonAlexa\Request\Request\AudioPlayer;

use MaxBeckers\AmazonAlexa\Helper\PropertyHelper;
use MaxBeckers\AmazonAlexa\Request\Request\AbstractRequest;

/**
Expand Down Expand Up @@ -38,6 +39,6 @@ protected function setRequestData(array $amazonRequest)
$this->timestamp = (new \DateTime())->setTimestamp(intval($amazonRequest['timestamp'] / 1000));
}
$this->locale = $amazonRequest['locale'];
$this->token = isset($amazonRequest['token']) ? $amazonRequest['token'] : null;
$this->token = PropertyHelper::checkNullValueString($amazonRequest, 'token');
}
}
3 changes: 2 additions & 1 deletion src/Request/Request/AudioPlayer/PlaybackFinishedRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace MaxBeckers\AmazonAlexa\Request\Request\AudioPlayer;

use MaxBeckers\AmazonAlexa\Helper\PropertyHelper;
use MaxBeckers\AmazonAlexa\Request\Request\AbstractRequest;

/**
Expand All @@ -24,7 +25,7 @@ public static function fromAmazonRequest(array $amazonRequest): AbstractRequest
$request = new self();

$request->type = self::TYPE;
$request->offsetInMilliseconds = isset($amazonRequest['offsetInMilliseconds']) ? $amazonRequest['offsetInMilliseconds'] : null;
$request->offsetInMilliseconds = PropertyHelper::checkNullValueInt($amazonRequest, 'offsetInMilliseconds');
$request->setRequestData($amazonRequest);

return $request;
Expand Down
Loading

0 comments on commit b18996e

Please sign in to comment.