From 1c21b9562d2f52ad88ce217d866765236b476975 Mon Sep 17 00:00:00 2001 From: lukareihl Date: Wed, 22 Nov 2023 14:30:50 +0100 Subject: [PATCH 1/4] Add friendsofphp/php-cs-fixer as a dev dependency --- composer.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 3185b6a..4b040c1 100644 --- a/composer.json +++ b/composer.json @@ -32,7 +32,8 @@ }, "require-dev": { "kint-php/kint": "^3.3", - "phpunit/phpunit": "*" + "phpunit/phpunit": "*", + "friendsofphp/php-cs-fixer": "^3.39" }, "autoload": { "psr-4": { From da84e52974f688000c719ecee45ee1ddb557c1a9 Mon Sep 17 00:00:00 2001 From: lukareihl Date: Wed, 22 Nov 2023 14:31:09 +0100 Subject: [PATCH 2/4] Add php-cs-fixer config --- .php-cs-fixer.php | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 .php-cs-fixer.php diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php new file mode 100644 index 0000000..38e354b --- /dev/null +++ b/.php-cs-fixer.php @@ -0,0 +1,43 @@ +setRules([ + '@PER' => true, + '@PSR12' => true, + '@Symfony' => true, + '@PhpCsFixer' => true, + 'no_useless_return' => false, + 'php_unit_test_class_requires_covers' => false, + 'php_unit_internal_class' => false, + 'phpdoc_align' => false, + 'phpdoc_no_empty_return' => false, + 'phpdoc_separation' => false, + 'yoda_style' => false, + 'trailing_comma_in_multiline' => false, + 'multiline_whitespace_before_semicolons' => [ + 'strategy' => 'no_multi_line' + ], + 'concat_space' => [ + 'spacing' => 'one' + ], + 'not_operator_with_space' => false, + 'operator_linebreak' => [ + 'position' => 'end', + 'only_booleans' => true + ], + 'blank_line_before_statement' => [ + 'statements' => [ + 'return', + 'throw', + 'try', + 'declare' + ] + ] + ]) + ->setFinder(PhpCsFixer\Finder::create() + ->in([ + __DIR__ . '/src', + __DIR__ . '/tests/classes', + __DIR__ . '/examples', + ]) + ); \ No newline at end of file From bce495f2b62b1c28955e41b062a550bae666f2a6 Mon Sep 17 00:00:00 2001 From: lukareihl Date: Thu, 23 Nov 2023 10:22:57 +0100 Subject: [PATCH 3/4] Apply code style fixes --- .php-cs-fixer.php | 2 +- examples/CustomFlowElement.php | 193 ++++++++-------- examples/FlowElementsForExamples.php | 73 +++--- examples/Pipeline.php | 28 +-- src/AspectPropertyValue.php | 46 ++-- src/BasicListEvidenceKeyFilter.php | 25 ++- src/Constants.php | 11 +- src/ElementData.php | 91 ++++---- src/ElementDataDictionary.php | 37 ++-- src/Evidence.php | 102 +++++---- src/EvidenceKeyFilter.php | 53 +++-- src/FlowData.php | 178 ++++++++------- src/FlowElement.php | 90 ++++---- src/JavascriptBuilderElement.php | 144 ++++++------ src/JsonBundlerElement.php | 89 ++++---- src/Logger.php | 49 ++--- src/Messages.php | 37 ++-- src/Pipeline.php | 85 ++++--- src/PipelineBuilder.php | 190 ++++++++-------- src/SequenceElement.php | 50 ++--- src/SetHeaderElement.php | 305 ++++++++++++-------------- src/Utils.php | 29 ++- tests/CoreTests.php | 102 +++++---- tests/ExampleTests.php | 8 +- tests/FlowDataTests.php | 110 ++++------ tests/JavaScriptBundlerTests.php | 259 ++++++++++------------ tests/SetHeaderTests.php | 157 ++++++++----- tests/classes/Constants.php | 71 +++--- tests/classes/ErrorFlowData.php | 10 +- tests/classes/ExampleFlowElement1.php | 25 +-- tests/classes/ExampleFlowElement2.php | 24 +- tests/classes/MemoryLogger.php | 78 ++++--- tests/classes/StopFlowData.php | 9 +- tests/classes/TestPipeline.php | 12 +- 34 files changed, 1368 insertions(+), 1404 deletions(-) diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php index 38e354b..776bcb5 100644 --- a/.php-cs-fixer.php +++ b/.php-cs-fixer.php @@ -40,4 +40,4 @@ __DIR__ . '/tests/classes', __DIR__ . '/examples', ]) - ); \ No newline at end of file + ); diff --git a/examples/CustomFlowElement.php b/examples/CustomFlowElement.php index 363a562..385a32b 100644 --- a/examples/CustomFlowElement.php +++ b/examples/CustomFlowElement.php @@ -21,7 +21,7 @@ * such notice(s) shall fulfill the requirements of that article. * ********************************************************************* */ -/** +/* * @example CustomFlowElement.php * * This example demonstrates the creation of a custom flow element. In this case @@ -31,180 +31,173 @@ * which gets a user's geolocation and saves the latitude as a cookie. * This latitude is also then passed in to the FlowData to calculate if * a person is in the northern or southern hemispheres. - + * */ - -use fiftyone\pipeline\core\PipelineBuilder; use fiftyone\pipeline\core\BasicListEvidenceKeyFilter; -use fiftyone\pipeline\core\FlowElement; use fiftyone\pipeline\core\ElementDataDictionary; +use fiftyone\pipeline\core\FlowElement; +use fiftyone\pipeline\core\PipelineBuilder; // Function to get star sign from month and day function getStarSign($month, $day) { if (($month == 1 && $day <= 20) || ($month == 12 && $day >= 22)) { - return "capricorn"; - } elseif (($month == 1 && $day >= 21) || ($month == 2 && $day <= 18)) { - return "aquarius"; - } elseif (($month == 2 && $day >= 19) || ($month == 3 && $day <= 20)) { - return "pisces"; - } elseif (($month == 3 && $day >= 21) || ($month == 4 && $day <= 20)) { - return "aries"; - } elseif (($month == 4 && $day >= 21) || ($month == 5 && $day <= 20)) { - return "taurus"; - } elseif (($month == 5 && $day >= 21) || ($month == 6 && $day <= 20)) { - return "gemini"; - } elseif (($month == 6 && $day >= 22) || ($month == 7 && $day <= 22)) { - return "cancer"; - } elseif (($month == 7 && $day >= 23) || ($month == 8 && $day <= 23)) { - return "leo"; - } elseif (($month == 8 && $day >= 24) || ($month == 9 && $day <= 23)) { - return "virgo"; - } elseif (($month == 9 && $day >= 24) || ($month == 10 && $day <= 23)) { - return "libra"; - } elseif (($month == 10 && $day >= 24) || ($month == 11 && $day <= 22)) { - return "scorpio"; - } elseif (($month == 11 && $day >= 23) || ($month == 12 && $day <= 21)) { - return "sagittarius"; + return 'capricorn'; + } + if (($month == 1 && $day >= 21) || ($month == 2 && $day <= 18)) { + return 'aquarius'; + } + if (($month == 2 && $day >= 19) || ($month == 3 && $day <= 20)) { + return 'pisces'; + } + if (($month == 3 && $day >= 21) || ($month == 4 && $day <= 20)) { + return 'aries'; + } + if (($month == 4 && $day >= 21) || ($month == 5 && $day <= 20)) { + return 'taurus'; + } + if (($month == 5 && $day >= 21) || ($month == 6 && $day <= 20)) { + return 'gemini'; + } + if (($month == 6 && $day >= 22) || ($month == 7 && $day <= 22)) { + return 'cancer'; + } + if (($month == 7 && $day >= 23) || ($month == 8 && $day <= 23)) { + return 'leo'; + } + if (($month == 8 && $day >= 24) || ($month == 9 && $day <= 23)) { + return 'virgo'; + } + if (($month == 9 && $day >= 24) || ($month == 10 && $day <= 23)) { + return 'libra'; + } + if (($month == 10 && $day >= 24) || ($month == 11 && $day <= 22)) { + return 'scorpio'; + } + if (($month == 11 && $day >= 23) || ($month == 12 && $day <= 21)) { + return 'sagittarius'; } -}; +} -//! [class] -//! [declaration] class AstrologyFlowElement extends FlowElement { - //! [declaration] - // datakey used to categorise data coming back from this // FlowElement in a Pipeline - public $dataKey = "astrology"; + public $dataKey = 'astrology'; + + public $properties = [ + 'starSign' => [ + 'type' => 'string', + 'description' => "the user's starsign" + ], + 'hemisphere' => [ + 'type' => 'string', + 'description' => "the user's hemisphere" + ], + 'getLatitude' => [ + 'type' => 'javascript', + 'description' => "JavaScript used to get a user's latitude" + ] + ]; // The processInternal function is the core working of a FlowElement. // It takes FlowData, reads evidence and returns data. - public function processInternal($FlowData) + public function processInternal($flowData) { $result = []; - // Get the date of birth from the query string (submitted through // a form on the client side) - $dateOfBirth = $FlowData->evidence->get("query.dateOfBirth"); + $dateOfBirth = $flowData->evidence->get('query.dateOfBirth'); if ($dateOfBirth) { - $dateOfBirth = explode("-", $dateOfBirth); + $dateOfBirth = explode('-', $dateOfBirth); $month = $dateOfBirth[1]; $day = $dateOfBirth[2]; - - $result["starSign"] = getStarSign($month, $day); + $result['starSign'] = getStarSign($month, $day); } // Serve some JavaScript to the user that will be used to save // a cookie with the user's latitude in it - $result["getLatitude"] = "navigator.geolocation.getCurrentPosition(function(position) { - document.cookie = \"latitude=\" + position.coords.latitude; + $result['getLatitude'] = 'navigator.geolocation.getCurrentPosition(function(position) { + document.cookie = "latitude=" + position.coords.latitude; loadHemisphere(); - });"; + });'; // Get the latitude from the above cookie - $latitude = $FlowData->evidence->get("cookie.latitude"); + $latitude = $flowData->evidence->get('cookie.latitude'); // Calculate the hemisphere if ($latitude) { - $result["hemisphere"] = $latitude > 0 ? "Northern" : "Southern"; + $result['hemisphere'] = $latitude > 0 ? 'Northern' : 'Southern'; } - $data = new ElementDataDictionary($this, $result); - $FlowData->setElementData($data); + $flowData->setElementData($data); } - public $properties = array( - "starSign" => array( - "type" => "string", - "description" => "the user's starsign" - ), - "hemisphere" => array( - "type" => "string", - "description" => "the user's hemisphere" - ), - "getLatitude" => array( - "type" => "javascript", - "description" => "JavaScript used to get a user's latitude" - ) - ); - public function getEvidenceKeyFilter() { - // A filter (in this case a basic list) stating which evidence // the FlowElement is interested in - return new BasicListEvidenceKeyFilter(["cookie.latitude", "query.dateOfBirth"]); + return new BasicListEvidenceKeyFilter(['cookie.latitude', 'query.dateOfBirth']); } } -//! [class] -//! [usage] - -// Add some callback settings for the page to make a request with extra evidence from the client side, in this case the same url with an extra query string. - -$javascriptBuilderSettings = array( - "host" => "localhost:3000", - "protocol" => "http", - "endpoint" => "/?json" -); +// Add some callback settings for the page to make a request with extra evidence from the client side +// in this case the same url with an extra query string. +$javascriptBuilderSettings = [ + 'host' => 'localhost:3000', + 'protocol' => 'http', + 'endpoint' => '/?json' +]; // Make the Pipeline and add the element we want to it +$Pipeline = (new PipelineBuilder(['javascriptBuilderSettings' => $javascriptBuilderSettings])) + ->add(new AstrologyFlowElement()) + ->build(); -$Pipeline = (new PipelineBuilder(["javascriptBuilderSettings"=>$javascriptBuilderSettings]))->add(new AstrologyFlowElement())->build(); - -$FlowData = $Pipeline->createFlowData(); +$flowData = $Pipeline->createFlowData(); // Add any information from the request (headers, cookies and additional // client side provided information) - -$FlowData->evidence->setFromWebRequest(); +$flowData->evidence->setFromWebRequest(); // Process the FlowData - -$FlowData->process(); +$flowData->process(); // The client side JavaScript calls back to this page -if (isset($_GET["json"])) { - header("Content-Type: application/json; charset=UTF-8"); - echo json_encode($FlowData->jsonbundler->json); +if (isset($_GET['json'])) { + header('Content-Type: application/json; charset=UTF-8'); + echo json_encode($flowData->jsonbundler->json); return; } // Generate the HTML for the form that gets a user's starsign +$output = ''; -$output = ""; - -$output .= "

Starsign

"; - +$output .= '

Starsign

'; $output .= "
"; // Add the results if they're available - - -if ($FlowData->astrology->starSign) { - $output .= "

Your starsign is " . $FlowData->astrology->starSign . "

"; +if ($flowData->astrology->starSign) { + $output .= '

Your starsign is ' . $flowData->astrology->starSign . '

'; } $output .= "
"; -if ($FlowData->astrology->hemisphere) { - $output .= "

Look at the " . $FlowData->astrology->hemisphere . " hemisphere stars tonight!

"; +if ($flowData->astrology->hemisphere) { + $output .= '

Look at the ' . $flowData->astrology->hemisphere . ' hemisphere stars tonight!

'; } -$output .= "
"; - -$output .= ""; +$output .= ''; // Return the full output to the page - echo $output; -//! [usage] diff --git a/examples/FlowElementsForExamples.php b/examples/FlowElementsForExamples.php index fd84317..3162874 100644 --- a/examples/FlowElementsForExamples.php +++ b/examples/FlowElementsForExamples.php @@ -21,93 +21,92 @@ * such notice(s) shall fulfill the requirements of that article. * ********************************************************************* */ -use fiftyone\pipeline\core\FlowElement; -use fiftyone\pipeline\core\ElementDataDictionary; use fiftyone\pipeline\core\BasicListEvidenceKeyFilter; +use fiftyone\pipeline\core\ElementDataDictionary; +use fiftyone\pipeline\core\FlowElement; // Two simple FlowElements class ExampleFlowElementA extends FlowElement { - public $dataKey = "example1"; - public function processInternal($FlowData) + public $dataKey = 'example1'; + + public $properties = [ + 'exampleProperty1' => [ + 'type' => 'int' + ] + ]; + + public function processInternal($flowData) { - $data = new ElementDataDictionary($this, array("exampleProperty1" => 5)); + $data = new ElementDataDictionary($this, ['exampleProperty1' => 5]); - $FlowData->setElementData($data); + $flowData->setElementData($data); } - public $properties = array( - "exampleProperty1" => array( - "type" => "int" - ) - ); - public function getEvidenceKeyFilter() { - return new BasicListEvidenceKeyFilter(["header.user-agent"]); + return new BasicListEvidenceKeyFilter(['header.user-agent']); } } class ExampleFlowElementB extends FlowElement { - public $dataKey = "example2"; + public $dataKey = 'example2'; + + public $properties = [ + 'exampleProperty2' => [ + 'type' => 'int' + ] + ]; - public function processInternal($FlowData) + public function processInternal($flowData) { - $data = new ElementDataDictionary($this, array("exampleProperty2" => 7)); + $data = new ElementDataDictionary($this, ['exampleProperty2' => 7]); - $FlowData->setElementData($data); + $flowData->setElementData($data); } - public $properties = array( - "exampleProperty2" => array( - "type" => "int" - ) - ); - public function getEvidenceKeyFilter() { - return new BasicListEvidenceKeyFilter(["header.user-agent"]); + return new BasicListEvidenceKeyFilter(['header.user-agent']); } } - -if (!class_exists("ErrorFlowElement")) { -// A FlowElement that triggers an error +if (!class_exists('ErrorFlowElement')) { + // A FlowElement that triggers an error class ErrorFlowElement extends FlowElement { - public $dataKey = "error"; + public $dataKey = 'error'; - public function processInternal($FlowData) + public function processInternal($flowData) { - throw new Exception("Something went wrong"); + throw new Exception('Something went wrong'); } public function getEvidenceKeyFilter() { - return new BasicListEvidenceKeyFilter(["header.user-agent"]); + return new BasicListEvidenceKeyFilter(['header.user-agent']); } } } - -if (!class_exists("StopFlowElement")) { +if (!class_exists('StopFlowElement')) { // A FlowElement that stops processing class StopFlowElement extends FlowElement { - public $dataKey = "stop"; + public $dataKey = 'stop'; - public function processInternal($FlowData) + public function processInternal($flowData) { - $FlowData->stop(); + $flowData->stop(); } public function getEvidenceKeyFilter() { - return new BasicListEvidenceKeyFilter(["header.user-agent"]); + return new BasicListEvidenceKeyFilter(['header.user-agent']); } } } diff --git a/examples/Pipeline.php b/examples/Pipeline.php index c980527..7a245b3 100644 --- a/examples/Pipeline.php +++ b/examples/Pipeline.php @@ -21,18 +21,18 @@ * such notice(s) shall fulfill the requirements of that article. * ********************************************************************* */ -/** +/* * @example Pipeline.php * * This example demonstrates how various FlowElements can be combined in a Pipeline and processed * */ -use fiftyone\pipeline\core\PipelineBuilder; use fiftyone\pipeline\core\Logger; +use fiftyone\pipeline\core\PipelineBuilder; // Require some FlowElements to use in this example -require(__DIR__ . "/FlowElementsForExamples.php"); +require __DIR__ . '/FlowElementsForExamples.php'; // Two simple example FlowElements @@ -51,7 +51,7 @@ class ArrayLogger extends Logger public function logInternal($log) { - if ($log["message"] === "test") { + if ($log['message'] === 'test') { $this->log[] = $log; } } @@ -59,31 +59,31 @@ public function logInternal($log) // We make a Pipeline with our elements -$Pipeline = (new PipelineBuilder()) +$pipeline = (new PipelineBuilder()) ->add($fe1) ->add($feStop) ->add($fe2) - ->addLogger(new ArrayLogger("info")) + ->addLogger(new ArrayLogger('info')) ->build(); // We create FlowData which we will add evidence to -$FlowData = $Pipeline->createFlowData(); +$flowData = $pipeline->createFlowData(); -$FlowData->evidence->set("header.user-agent", "test"); -$FlowData->evidence->set("some.other-evidence", "test"); +$flowData->evidence->set('header.user-agent', 'test'); +$flowData->evidence->set('some.other-evidence', 'test'); // Add extra evidence available in a web request -$FlowData->evidence->setFromWebRequest(); +$flowData->evidence->setFromWebRequest(); // Process the FlowData -$FlowData->process(); +$flowData->process(); // Get a property from the first FlowElement -$FlowData->example1->exampleProperty1; +$flowData->example1->exampleProperty1; // Get all properties which match a condition -$FlowData->getWhere("type", "int"); +$flowData->getWhere('type', 'int'); // Get from an element by its object -$FlowData->getFromElement($fe1)->exampleProperty1; +$flowData->getFromElement($fe1)->exampleProperty1; diff --git a/src/AspectPropertyValue.php b/src/AspectPropertyValue.php index 56fef46..0329890 100644 --- a/src/AspectPropertyValue.php +++ b/src/AspectPropertyValue.php @@ -21,34 +21,33 @@ * such notice(s) shall fulfill the requirements of that article. * ********************************************************************* */ - - namespace fiftyone\pipeline\core; /** - * An AspectPropertyValue is a wrapper for a value - * It lets you check this wrapper has a value inside it - * If not value is set, a specific no value message is returned -*/ + * An AspectPropertyValue is a wrapper for a value + * It lets you check this wrapper has a value inside it + * If not value is set, a specific no value message is returned. + */ class AspectPropertyValue { - private $_value; - public $noValueMessage = null; + public $noValueMessage; public $hasValue = false; + private $_value; /** - * Constructor for AspectPropertyValue - * @param string if there is no value, the reason for there not being one - * @param mixed the value - */ - public function __construct($noValueMessage = null, $value = "noValue") + * Constructor for AspectPropertyValue. + * + * @param null|string $noValueMessage Reason why the value is missing + * @param mixed $value + */ + public function __construct($noValueMessage = null, $value = 'noValue') { - if ($value !== "noValue") { + if ($value !== 'noValue') { $this->value = $value; $this->noValueMessage = null; $this->hasValue = true; } - + if ($noValueMessage) { $this->hasValue = false; $this->noValueMessage = $noValueMessage; @@ -56,16 +55,19 @@ public function __construct($noValueMessage = null, $value = "noValue") } /** - * Magic getter to access the value or throw an error with the no value message - * @param string key - * @return mixed value - */ + * Magic getter to access the value or throw an error with the no value message. + * + * @param string $key + * @return mixed + * @throws \Exception + */ public function __get($key) { - if ($key === "value") { + if ($key === 'value') { if ($this->hasValue) { return $this->_value; - } else if (!empty($this->noValueMessage)) { + } + if (!empty($this->noValueMessage)) { throw new \Exception($this->noValueMessage); } } @@ -73,7 +75,7 @@ public function __get($key) public function __set($key, $value) { - if ($key === "value") { + if ($key === 'value') { $this->_value = $value; $this->hasValue = true; } diff --git a/src/BasicListEvidenceKeyFilter.php b/src/BasicListEvidenceKeyFilter.php index 58eb583..8a19ab6 100644 --- a/src/BasicListEvidenceKeyFilter.php +++ b/src/BasicListEvidenceKeyFilter.php @@ -21,34 +21,34 @@ * such notice(s) shall fulfill the requirements of that article. * ********************************************************************* */ - - namespace fiftyone\pipeline\core; /** - * An instance of EvidenceKeyFilter that uses a simple array of keys - * Evidence not using these keys is filtered out -*/ + * An instance of EvidenceKeyFilter that uses a simple array of keys + * Evidence not using these keys is filtered out. + */ class BasicListEvidenceKeyFilter extends EvidenceKeyFilter { private $list; /** - * @param mixed[] an array of keys to keep - */ + * @param array $list an array of keys to keep + */ public function __construct($list) { $this->list = $list; } /** - * @param string key to check in the filter - * @return boolean is this key in the filter's keys list? - */ + * @param string $key key to check in the filter + * @return bool is this key in the filter's keys list? + */ public function filterEvidenceKey($key) { + $key = strtolower($key); + foreach ($this->list as $evidenceKey) { - if (strtolower($key) === strtolower($evidenceKey)) { + if ($key === strtolower($evidenceKey)) { return true; } } @@ -58,7 +58,8 @@ public function filterEvidenceKey($key) /** * Get the internal list of evidence keys in this filter. - * @return mixed[] evidence keys + * + * @return array evidence keys */ public function getList() { diff --git a/src/Constants.php b/src/Constants.php index 21a90e9..1f04f8e 100644 --- a/src/Constants.php +++ b/src/Constants.php @@ -24,10 +24,11 @@ namespace fiftyone\pipeline\core; /** - * Class containing projects's constants. + * Class containing project's constants. */ -class Constants { - const SETHEADER_ELEMENT_KEY = "set-headers"; - const SETHEADER_DATA_KEY = "responseheaderdictionary"; - const ACCEPTCH_HEADER = "Accept-CH"; +class Constants +{ + public const SETHEADER_ELEMENT_KEY = 'set-headers'; + public const SETHEADER_DATA_KEY = 'responseheaderdictionary'; + public const ACCEPTCH_HEADER = 'Accept-CH'; } diff --git a/src/ElementData.php b/src/ElementData.php index 3a09baa..1246a98 100644 --- a/src/ElementData.php +++ b/src/ElementData.php @@ -25,85 +25,92 @@ /** * Stores information created by a FlowElement based on FlowData. - * Stored in FlowData -*/ + * Stored in FlowData. + */ class ElementData { public $flowElement; /** - * Constructor for element data - * @param FlowElement - */ + * Constructor for element data. + * + * @param FlowElement $flowElement + */ public function __construct($flowElement) { $this->flowElement = $flowElement; } - /** - * Get a value from the ElementData contents - * This calls the ElementData class' (often overridden) getInternal method - * @param string property - * @return mixed - */ - public function get($key) - { - return $this->getInternal($key); - } - public function __get($key) { return $this->get($key); } - + /** - * Get the values contained in the ElementData instance as a dictionary - * of keys and values. - * @return mixed[] - */ - public function asDictionary() + * Get a value from the ElementData contents + * This calls the ElementData class' (often overridden) getInternal method. + * + * @param string $key Property name + * @return mixed + */ + public function get($key) { - return; + return $this->getInternal($key); } - + /** - * Called by the get() method - * Returns the requested property from the data - * @param string property - * @return mixed - */ - protected function getInternal($key) + * Get the values contained in the ElementData instance as a dictionary + * of keys and values. + * + * @return array + */ + public function asDictionary() { return; } /** - * Helper method to get property as a string - * @param string property - * @return string - */ + * Helper method to get property as a string. + * + * @param string $key Property name + * @return string + */ public function getAsString($key) { return strval($this->get($key)); } /** - * Helper method to get property as a float - * @param string property - * @return float - */ + * Helper method to get property as a float. + * + * @param string $key + * @return float + */ public function getAsFloat($key) { return floatval($this->get($key)); } /** - * Helper method to get property as a int - * @param string property - * @return int - */ + * Helper method to get property as a int. + * + * @param string $key Property name + * @return int + */ public function getAsInteger($key) { return intval($this->get($key)); } + + /** + * Called by the get() method + * Returns the requested property from the data. + * + * @param string $key Property name + * @return mixed + */ + protected function getInternal($key) + { + return; + } } diff --git a/src/ElementDataDictionary.php b/src/ElementDataDictionary.php index 55f0e3a..afd70ce 100644 --- a/src/ElementDataDictionary.php +++ b/src/ElementDataDictionary.php @@ -24,45 +24,48 @@ namespace fiftyone\pipeline\core; /** -* An extension of ElementData with dictionary object storage / lookup -**/ + * An extension of ElementData with dictionary object storage / lookup. + */ class ElementDataDictionary extends ElementData { public $contents; /** - * Constructor for element data dictionary - * @param FlowElement - * @param mixed[] dicitonary contents - */ + * Constructor for element data dictionary. + * + * @param FlowElement $flowElement + * @param array $contents Dictionary contents + */ public function __construct($flowElement, $contents) { $this->contents = $contents; parent::__construct($flowElement); } - + /** - * Get the values contained in the ElementData instance as a dictionary - * of keys and values. - * @return mixed[] - */ + * Get the values contained in the ElementData instance as a dictionary + * of keys and values. + * + * @return array + */ public function asDictionary() { return $this->contents; } /** - * Internal getter for contents - * @param string key - * @return mixed - */ + * Internal getter for contents. + * + * @param string $key + * @return mixed + */ public function getInternal($key) { if (isset($this->contents[$key])) { return $this->contents[$key]; - } else { - return null; } + + return null; } } diff --git a/src/Evidence.php b/src/Evidence.php index c45fc7e..fb1b65c 100644 --- a/src/Evidence.php +++ b/src/Evidence.php @@ -24,28 +24,30 @@ namespace fiftyone\pipeline\core; /** - * Storage of evidence on a FlowData object -*/ + * Storage of evidence on a FlowData object. + */ class Evidence { protected $flowData; - protected $evidence = array(); + protected $evidence = []; /** - * evidence container constructor - * @param FlowData parent FlowData - */ + * Evidence container constructor. + * + * @param FlowData $flowData Parent FlowData + */ public function __construct($flowData) { $this->flowData = $flowData; } /** - * If a flow element can use the key then add the key value pair to the - * evidence collection - * @param string key - * @param mixed value - */ + * If a flow element can use the key then add the key value pair to the + * evidence collection. + * + * @param string $key + * @param mixed $value + */ public function set($key, $value) { $keep = false; @@ -63,13 +65,14 @@ public function set($key, $value) } /** - * Helper function to set multiple pieces of evidence from an array - * @param mixed[] - */ + * Helper function to set multiple pieces of evidence from an array. + * + * @param array $array + */ public function setArray($array) { if (!is_array($array)) { - $this->flowData->setError("core", Messages::PASS_KEY_VALUE); + $this->flowData->setError('core', Messages::PASS_KEY_VALUE); } foreach ($array as $key => $value) { @@ -78,13 +81,14 @@ public function setArray($array) } /** - * Extract evidence from a web request - * No argument version automatically reads from current request using the - * $_SERVER, $_COOKIE, $_GET and $_POST globals - * @param $server key value pairs for the HTTP headers - * @param $cookies key value pairs for the cookies - * @param $query key value pairs for the form parameters - */ + * Extract evidence from a web request + * No argument version automatically reads from current request using the + * $_SERVER, $_COOKIE, $_GET and $_POST globals. + * + * @param null|array $server Key-value pairs for the HTTP headers + * @param null|array $cookies Key-value pairs for the cookies + * @param null|array $query Key-value pairs for the form parameters + */ public function setFromWebRequest($server = null, $cookies = null, $query = null) { if ($server === null) { @@ -101,32 +105,32 @@ public function setFromWebRequest($server = null, $cookies = null, $query = null $query = array_merge($_POST, $_GET); } - $evidence = array(); - + $evidence = []; + foreach ($server as $name => $value) { if (substr($name, 0, 5) == 'HTTP_') { $key = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5))))); - + $key = strtolower($key); - - $evidence["header." . $key] = $value; + + $evidence['header.' . $key] = $value; } } - + foreach ($cookies as $key => $value) { - $evidence["cookie." . $key] = $value; + $evidence['cookie.' . $key] = $value; } foreach ($query as $key => $value) { - $evidence["query." . $key] = $value; + $evidence['query.' . $key] = $value; } - - if (isset($server["SERVER_ADDR"])) { - $evidence["server.host-ip"] = $server["SERVER_ADDR"]; + + if (isset($server['SERVER_ADDR'])) { + $evidence['server.host-ip'] = $server['SERVER_ADDR']; } - if (isset($server["REMOTE_ADDR"])) { - $evidence["server.client-ip"] = $server["REMOTE_ADDR"]; + if (isset($server['REMOTE_ADDR'])) { + $evidence['server.client-ip'] = $server['REMOTE_ADDR']; } // Protocol @@ -139,32 +143,34 @@ public function setFromWebRequest($server = null, $cookies = null, $query = null // Override protocol with referer header if set - if (isset($server["HTTP_REFERER"]) && $server["HTTP_REFERER"]) { - $protocol = parse_url($server["HTTP_REFERER"], PHP_URL_SCHEME); + if (isset($server['HTTP_REFERER']) && $server['HTTP_REFERER']) { + $protocol = parse_url($server['HTTP_REFERER'], PHP_URL_SCHEME); } - $evidence["header.protocol"] = $protocol; - + $evidence['header.protocol'] = $protocol; + $this->setArray($evidence); } /** - * Get a piece of evidence by key - * @param string key - */ + * Get a piece of evidence by key. + * + * @param string $key + */ public function get($key) { if (isset($this->evidence[$key])) { return $this->evidence[$key]; - } else { - return null; - }; + } + + return null; } /** - * Get all evidence - * @return mixed[] - */ + * Get all evidence. + * + * @return array + */ public function getAll() { return $this->evidence; diff --git a/src/EvidenceKeyFilter.php b/src/EvidenceKeyFilter.php index 0f3ee60..c4ca87c 100644 --- a/src/EvidenceKeyFilter.php +++ b/src/EvidenceKeyFilter.php @@ -24,39 +24,51 @@ namespace fiftyone\pipeline\core; /** - * An evidence key filter is added to a FlowElement - * It tells the Pipeline which evidence it is interested in - * This can be used to determine whether a request can be cached - * Or to filter out evidence not needed by any element in a Pipeline - * This base class is always extended for a specific filter type -*/ + * An evidence key filter is added to a FlowElement + * It tells the Pipeline which evidence it is interested in + * This can be used to determine whether a request can be cached + * Or to filter out evidence not needed by any element in a Pipeline + * This base class is always extended for a specific filter type. + */ class EvidenceKeyFilter { - private $_filterEvidenceKey = null; + /** + * @var null|callable + */ + private $_filterEvidenceKey; + + public function __set($name, $value) + { + if ($name === 'filterEvidenceKey') { + $this->_filterEvidenceKey = $value; + } + } /** - * filterevidence from an object - * @param mixed[] evidence dicitonary contents - * @return mixed[] filtered evidence dictionary contents - */ + * Filter Evidence from an object. + * + * @param array $evidenceKeyObject Evidence dictionary contents + * @return array Filtered evidence dictionary contents + */ public function filterEvidence($evidenceKeyObject) { - $filtered = array(); + $filtered = []; foreach ($evidenceKeyObject as $key => $value) { if ($this->filterEvidenceKey($key)) { $filtered[$key] = $value; } - }; + } return $filtered; } /** - * see if a property key should be in the filtered evidence - * @param string property name - * @return boolean should this be filtered out or not? - */ + * Check whether a property key should be in the filtered evidence. + * + * @param string $key Property name + * @return bool Should this be filtered out or not? + */ public function filterEvidenceKey($key) { if ($this->_filterEvidenceKey) { @@ -65,11 +77,4 @@ public function filterEvidenceKey($key) return true; } - - public function __set($name, $value) - { - if ($name === 'filterEvidenceKey') { - $this->_filterEvidenceKey = $value; - } - } } diff --git a/src/FlowData.php b/src/FlowData.php index e593c71..0133f83 100644 --- a/src/FlowData.php +++ b/src/FlowData.php @@ -24,11 +24,11 @@ namespace fiftyone\pipeline\core; /** - * FlowData is created by a specific Pipeline - * It collects evidence set by the user - * It passes evidence to FlowElements in the Pipeline - * These elements can return ElementData or populate an errors object -*/ + * FlowData is created by a specific Pipeline + * It collects evidence set by the user + * It passes evidence to FlowElements in the Pipeline + * These elements can return ElementData or populate an errors object. + */ class FlowData { public $pipeline; @@ -36,12 +36,13 @@ class FlowData public $evidence; public $data; public $processed; - public $errors = array(); + public $errors = []; /** - * Constructor for FlowData - * @param Pipeline // parent Pipeline - */ + * Constructor for FlowData. + * + * @param Pipeline $pipeline Parent Pipeline + */ public function __construct($pipeline) { $this->pipeline = $pipeline; @@ -50,17 +51,28 @@ public function __construct($pipeline) } /** - * process function runs the process function on every attached FlowElement - * allowing data to be changed based on evidence - * This can only be run once per FlowData instance - * @return FlowData - */ + * Magic getter to allow $FlowData->FlowElementKey getting. + * + * @param string $flowElementKey + * @return ElementData + */ + public function __get($flowElementKey) + { + return $this->get($flowElementKey); + } + + /** + * process function runs the process function on every attached FlowElement + * allowing data to be changed based on evidence + * This can only be run once per FlowData instance. + * @return FlowData + */ public function process() { if (!$this->processed) { foreach ($this->pipeline->flowElements as $flowElement) { if (!$this->stopped) { - // All errors are caught and stored in an errors array keyed by the + // All errors are caught and stored in an errors array keyed by the // FlowElement that set the error try { @@ -76,13 +88,13 @@ public function process() // Set processed flag to true. FlowData can only be processed once $this->processed = true; - } else { - $this->setError("global", new \Exception(Messages::FLOW_DATA_PROCESSED)); + $this->setError('global', new \Exception(Messages::FLOW_DATA_PROCESSED)); } if (count($this->errors) != 0 && $this->pipeline->suppressProcessExceptions === false) { $exception = reset($this->errors); + throw $exception; } @@ -90,84 +102,74 @@ public function process() } /** - * Retrieve data by FlowElement object - * @param FlowElement + * Retrieve data by FlowElement object. + * + * @param FlowElement $flowElement * @return ElementData - */ + */ public function getFromElement($flowElement) { return $this->get($flowElement->dataKey); } /** - * Retrieve data by FlowElement key - * @param string FlowElementDataKey - * @return ElementData + * Retrieve data by FlowElement key. * - */ + * @param string $flowElementKey + * @return ElementData + * @throws \Exception + */ public function get($flowElementKey) - { - if (isset($this->data[$flowElementKey])) { - return $this->data[$flowElementKey]; - } else { - if(is_null($this->data)){ - throw new \Exception( - sprintf(Messages::NO_ELEMENT_DATA_NULL, $flowElementKey)); - } else { - throw new \Exception( - sprintf(Messages::NO_ELEMENT_DATA, - $flowElementKey, - join(",", array_keys($this->data)))); - } + { + if ($this->data === null) { + throw new \Exception(sprintf(Messages::NO_ELEMENT_DATA_NULL, $flowElementKey)); } - } - /** - * Magic getter to allow $FlowData->FlowElementKey getting - * @param string FlowElementKey - * @return $ElementData - */ - public function __get($flowElementKey) - { - return $this->get($flowElementKey); + if (!isset($this->data[$flowElementKey])) { + throw new \Exception(sprintf(Messages::NO_ELEMENT_DATA, $flowElementKey, join(',', array_keys($this->data)))); + } + + return $this->data[$flowElementKey]; } /** - * Set data (used by FlowElement) - * @param ElementData - */ + * Set data (used by FlowElement). + * + * @param ElementData $data + */ public function setElementData($data) { $this->data[$data->flowElement->dataKey] = $data; } /** - * Set error (should be keyed by FlowElement dataKey) - * @param string key - * @param Exception error - */ + * Set error (should be keyed by FlowElement dataKey). + * + * @param string $key + * @param \Exception $error + */ public function setError($key, $error) { $this->errors[$key] = $error; - $logMessage = "Error occurred during processing"; + $logMessage = 'Error occurred during processing'; if (!empty($key)) { - $logMessage = $logMessage . " of " . $key . ". \n" . $error; + $logMessage = $logMessage . ' of ' . $key . ". \n" . $error; } - - $this->pipeline->log("error", $logMessage); + $this->pipeline->log('error', $logMessage); } /** * Get an array evidence stored in the FlowData, filtered by - * its FlowElements' EvidenceKeyFilters + * its FlowElements' EvidenceKeyFilters. + * * @return array - */ + */ public function getEvidenceDataKey() { - $requestedEvidence = array(); + $requestedEvidence = []; $evidence = $this->evidence->getAll(); foreach ($this->pipeline->flowElements as $flowElement) { @@ -178,51 +180,45 @@ public function getEvidenceDataKey() } /** - * Stop processing any subsequent FlowElements - * @return void - */ + * Stop processing any subsequent FlowElements. + */ public function stop() { $this->stopped = true; } /** - * Get data from FlowElement based on property meta data - * @param string metakey - * @param mixed metavalue + * Get data from FlowElement based on property metadata. + * + * @param string $metaKey + * @param mixed $metaValue * @return array - */ + */ public function getWhere($metaKey, $metaValue) { - $metaKey = \strtolower($metaKey); - $metaValue = \strtolower($metaValue); - - $keys = array(); - - if (isset($this->pipeline->propertyDatabase[$metaKey])) { - if (isset($this->pipeline->propertyDatabase[$metaKey][$metaValue])) { - foreach ($this->pipeline->propertyDatabase[$metaKey][$metaValue] as $key => $value) { - $keys[$key] = $value["flowElement"]; - } - } - } + $metaKey = strtolower($metaKey); + $metaValue = strtolower($metaValue); - $output = array(); + $keys = []; - if (isset($keys)) { - foreach ($keys as $key => $flowElement) { + if (isset($this->pipeline->propertyDatabase[$metaKey][$metaValue])) { + foreach ($this->pipeline->propertyDatabase[$metaKey][$metaValue] as $key => $value) { + $keys[$key] = $value['flowElement']; + } + } - // First check if FlowElement has any data set + $output = []; - if (isset($this->data[$flowElement])) { - $data = $this->get($flowElement); + foreach ($keys as $key => $flowElement) { + // First check if FlowElement has any data set + if (isset($this->data[$flowElement])) { + $data = $this->get($flowElement); - if ($data) { - try { - $output[$key] = $data->get($key); - } catch (\Exception $e) { - continue; - } + if ($data) { + try { + $output[$key] = $data->get($key); + } catch (\Exception $e) { + continue; } } } diff --git a/src/FlowElement.php b/src/FlowElement.php index 329f6a6..205135c 100644 --- a/src/FlowElement.php +++ b/src/FlowElement.php @@ -24,12 +24,12 @@ namespace fiftyone\pipeline\core; /** - * A FlowElement is placed inside a Pipeline - * It receives Evidence via a FlowData object - * It uses this to optionally create ElementData on the FlowData - * It has a unique dataKey which is used to extract data from the FlowData - * Any errors in processing are caught in the FlowData's errors object -**/ + * A FlowElement is placed inside a Pipeline + * It receives Evidence via a FlowData object + * It uses this to optionally create ElementData on the FlowData + * It has a unique dataKey which is used to extract data from the FlowData + * Any errors in processing are caught in the FlowData's errors object. + */ class FlowElement { public $dataKey; @@ -38,9 +38,21 @@ class FlowElement public $pipelines = []; /** - * General wrapper function that calls a FlowElement's processInternal method - * @param FlowData - */ + * A default dummy constructor is needed for there are classes inheriting this + * class deeper than 1-level of inheritance and calling parent::__construct() in their + * explicit constructors unfortunately intermediates do not define their own __construct() + * so the call propagates up to the base class FlowElement and fails. + * Intermediates might define their own __construct() at some point, so we do not want to + * remove parent::__construct() calls, rather add this one as a catch-all. + * + * */ + public function __construct() {} + + /** + * General wrapper function that calls a FlowElement's processInternal method. + * + * @param FlowData $flowData + */ public function process($flowData) { return $this->processInternal($flowData); @@ -48,19 +60,21 @@ public function process($flowData) /** * Function for getting the FlowElement's EvidenceKeyFilter - * Used by the filterEvidence method + * Used by the filterEvidence method. + * * @return EvidenceKeyFilter - */ + */ public function getEvidenceKeyFilter() { return new EvidenceKeyFilter(); } /** - * Filter FlowData evidence using the FlowElement's EvidenceKeyFilter - * @param FlowData + * Filter FlowData evidence using the FlowElement's EvidenceKeyFilter. + * + * @param FlowData $flowData * @return mixed - */ + */ public function filterEvidence($flowData) { $filter = $this->getEvidenceKeyFilter(); @@ -69,10 +83,11 @@ public function filterEvidence($flowData) } /** - * Filter FlowData evidence using the FlowElement's EvidenceKeyFilter - * @param FlowData + * Filter FlowData evidence using the FlowElement's EvidenceKeyFilter. + * + * @param string $key * @return mixed - */ + */ public function filterEvidenceKey($key) { $filter = $this->getEvidenceKeyFilter(); @@ -81,10 +96,10 @@ public function filterEvidenceKey($key) } /** - * Callback called when an engine is added to a pipeline - * @param Pipeline - * @return void - */ + * Callback called when an engine is added to a pipeline. + * + * @param Pipeline $pipeline + */ public function onRegistration($pipeline) { return $pipeline; @@ -92,9 +107,10 @@ public function onRegistration($pipeline) /** * Process FlowData - this is process function - * is usually overriden by specific FlowElements to do their core work - * @param FlowData - */ + * is usually overriden by specific FlowElements to do their core work. + * + * @param FlowData $flowData + */ public function processInternal($flowData) { return true; @@ -102,9 +118,10 @@ public function processInternal($flowData) /** * Get properties - * is usually overriden by specific FlowElements - * @return array key value array of properties - */ + * Usually overridden by specific FlowElements. + * + * @return array Key-value array of properties + */ public function getProperties() { return $this->properties; @@ -112,27 +129,14 @@ public function getProperties() /** * Update a FlowElement's property list - * This is used by elements that are only aware of their properites + * This is used by elements that are only aware of their properties * at a later stage, such as cloud request based FlowElements or - * FlowElements that change their properties later based on new datafiles - */ + * FlowElements that change their properties later based on new datafiles. + */ public function updatePropertyList() { foreach ($this->pipelines as $pipeline) { $pipeline->updatePropertyDatabaseForFlowElement($this); } } - - /** - * A default dummy constructor is needed for there are classes inheriting this - * class deeper than 1-level of inheritance and calling parent::__construct() in their - * explicit constructors unfortunately intermediates do not define their own __construct() - * so the call propagates up to the base class FlowElement and fails. - * Intermediates might define their own __construct() at some point, so we do not want - * remove parent::__construct() calls, rather add this one as a catch all. - * - * */ - public function __construct() { - - } } diff --git a/src/JavascriptBuilderElement.php b/src/JavascriptBuilderElement.php index 0bf6452..7f12650 100644 --- a/src/JavascriptBuilderElement.php +++ b/src/JavascriptBuilderElement.php @@ -23,6 +23,8 @@ namespace fiftyone\pipeline\core; +use JShrink\Minifier; + /** * The JavaScriptBuilder aggregates JavaScript properties * from FlowElements in the Pipeline. This JavaScript also (when needed) @@ -39,158 +41,152 @@ class JavascriptBuilderElement extends FlowElement public $settings; public $minify; - public function __construct($settings = array()) + public $dataKey = 'javascriptbuilder'; + + public function __construct($settings = []) { $this->settings = [ - - "_objName" => isset($settings["objName"]) ? $settings["objName"] : "fod", - "_protocol" => isset($settings["protocol"]) ? $settings["protocol"] : null, - "_host" => isset($settings["host"]) ? $settings["host"] : null, - "_endpoint" => isset($settings["endpoint"]) ? $settings["endpoint"] : "", - "_enableCookies" => isset($settings["enableCookies"]) ? $settings["enableCookies"] : true - + '_objName' => $settings['objName'] ?? 'fod', + '_protocol' => $settings['protocol'] ?? null, + '_host' => $settings['host'] ?? null, + '_endpoint' => $settings['endpoint'] ?? '', + '_enableCookies' => $settings['enableCookies'] ?? true ]; - $this->minify = isset($settings["minify"]) ? $settings["minify"] : true; - } - public $dataKey = "javascriptbuilder"; + $this->minify = $settings['minify'] ?? true; + } /** * The JavaScriptBuilder captures query string evidence and - * headers for detecting whether the request is http or https - */ + * headers for detecting whether the request is http or https. + * + * @return EvidenceKeyFilter + */ public function getEvidenceKeyFilter() { $filter = new EvidenceKeyFilter(); $filter->filterEvidenceKey = function ($key) { - if (strpos($key, "query.") !== false) { + if (strpos($key, 'query.') !== false) { return true; } - - if ($key == "header.host" || $key == "header.protocol") { + + if ($key == 'header.host' || $key == 'header.protocol') { return true; } - + return false; }; - + return $filter; } /** * The JavaScriptBundler collects client side javascript to serve. - * @param FlowData FlowData - */ + * + * @param FlowData $flowData + */ public function processInternal($flowData) { - $m = new \Mustache_Engine(); - - $vars = array(); + $vars = []; foreach ($this->settings as $key => $value) { $vars[$key] = $value; } - $vars["_jsonObject"] = json_encode($flowData->jsonbundler->json); + $vars['_jsonObject'] = json_encode($flowData->jsonbundler->json); // Generate URL and autoUpdate params + $protocol = $this->settings['_protocol']; + $host = $this->settings['_host']; - $protocol = $this->settings["_protocol"]; - $host = $this->settings["_host"]; - - if (!isset($protocol) || trim($protocol) === '') { + if ($protocol === null || trim($protocol) === '') { // Check if protocol is provided in evidence - - if ($flowData->evidence->get("header.protocol")) { - $protocol = $flowData->evidence->get("header.protocol"); + if ($flowData->evidence->get('header.protocol')) { + $protocol = $flowData->evidence->get('header.protocol'); } } - if (!isset($protocol) || trim($protocol) === '') { - $protocol = "https"; - } + if ($protocol === null || trim($protocol) === '') { + $protocol = 'https'; + } - if (!isset($host) || trim($host) === '') { + if ($host === null || trim($host) === '') { // Check if host is provided in evidence - - if ($flowData->evidence->get("header.host")) { - $host = $flowData->evidence->get("header.host"); + if ($flowData->evidence->get('header.host')) { + $host = $flowData->evidence->get('header.host'); } } - $vars["_host"] = $host; - $vars["_protocol"] = $protocol; + $vars['_host'] = $host; + $vars['_protocol'] = $protocol; $params = $this->getEvidenceKeyFilter()->filterEvidence($flowData->evidence->getAll()); - if ($vars["_host"] && $vars["_protocol"] && $vars["_endpoint"]) { - $vars["_url"] = $vars["_protocol"] . "://" . $vars["_host"] . $vars["_endpoint"]; - + if ($vars['_host'] && $vars['_protocol'] && $vars['_endpoint']) { + $vars['_url'] = $vars['_protocol'] . '://' . $vars['_host'] . $vars['_endpoint']; // Add query parameters to the URL $query = []; - - foreach ($params as $param => $paramValue) { - $paramKey = explode(".", $param)[1]; + foreach ($params as $param => $paramValue) { + $paramKey = explode('.', $param)[1]; $query[$paramKey] = $paramValue; } - + $urlQuery = http_build_query($query); - + // Does the URL already have a query string in it? - - if (strpos($vars["_url"], "?") === false) { - $vars["_url"] .= "?"; + if (strpos($vars['_url'], '?') === false) { + $vars['_url'] .= '?'; } else { - $vars["_url"] .= "&"; + $vars['_url'] .= '&'; } - - $vars["_url"] .= $urlQuery; - $vars["_updateEnabled"] = true; + $vars['_url'] .= $urlQuery; + + $vars['_updateEnabled'] = true; } else { - $vars["_updateEnabled"] = false; + $vars['_updateEnabled'] = false; } // Use results from device detection if available to determine // if the browser supports promises. - - if (property_exists($flowData, "device") && property_exists($flowData->device, "promise")) { - $vars["_supportsPromises"] = $flowData->device->promise->value == true; + if (property_exists($flowData, 'device') && property_exists($flowData->device, 'promise')) { + $vars['_supportsPromises'] = $flowData->device->promise->value == true; } else { - $vars["_supportsPromises"] = false; + $vars['_supportsPromises'] = false; } // Check if any delayedproperties exist in the json + $vars['_hasDelayedProperties'] = strpos($vars['_jsonObject'], 'delayexecution') !== false; + $vars['_sessionId'] = $flowData->evidence->get('query.session-id'); + $vars['_sequence'] = $flowData->evidence->get('query.sequence'); - $vars["_hasDelayedProperties"] = strpos($vars["_jsonObject"], "delayexecution") !== false; - $vars["_sessionId"] = $flowData->evidence->get("query.session-id"); - $vars["_sequence"] = $flowData->evidence->get("query.sequence"); - $jsParams = []; foreach ($params as $param => $paramValue) { - $paramKey = explode(".", $param)[1]; + $paramKey = explode('.', $param)[1]; $jsParams[$paramKey] = $paramValue; } - - $vars["_parameters"] = json_encode($jsParams); - $output = $m->render(file_get_contents($this->getTemplatePath()), $vars); + $vars['_parameters'] = json_encode($jsParams); + + $output = (new \Mustache_Engine())->render(file_get_contents($this->getTemplatePath()), $vars); - if($this->minify) { + if ($this->minify) { // Minify the output - $output = \JShrink\Minifier::minify($output); + $output = Minifier::minify($output); } - - $data = new ElementDataDictionary($this, ["javascript" => $output]); - $flowData->setElementData($data); + $data = new ElementDataDictionary($this, ['javascript' => $output]); - return; + $flowData->setElementData($data); } + /** + * @return string + * @throws \Exception + */ private function getTemplatePath() { $templatePath = '51degrees/fiftyone.pipeline.javascript-templates/JavaScriptResource.mustache'; diff --git a/src/JsonBundlerElement.php b/src/JsonBundlerElement.php index 5a9f927..c922092 100644 --- a/src/JsonBundlerElement.php +++ b/src/JsonBundlerElement.php @@ -29,17 +29,18 @@ * side via the JavaScriptBuilder and also used inside the * JavaScriptBuilder itself to pass properties to the client side. * Both this and the JavaScriptBuilder element are automatically - * added to a Pipeline unless specifically ommited in the PipelineBuilder + * added to a Pipeline unless specifically omitted in the PipelineBuilder. */ class JsonBundlerElement extends FlowElement { - public $dataKey = "jsonbundler"; + public $dataKey = 'jsonbundler'; public $json; private $propertyCache = []; /** - * The JSONBundler extracts all properties from a FlowData and serializes them into JSON - * @param FlowData FlowData + * The JSONBundler extracts all properties from a FlowData and serializes them into JSON. + * + * @param FlowData $flowData */ public function processInternal($flowData) { @@ -47,7 +48,7 @@ public function processInternal($flowData) // Storing JavaScript properties in an extra section $output = [ - "javascriptProperties" => [] + 'javascriptProperties' => [] ]; if (count($this->propertyCache)) { @@ -57,50 +58,54 @@ public function processInternal($flowData) $this->propertyCache = []; } - foreach ($flowData->pipeline->flowElements as $flowElement) { - if ($flowElement->dataKey === "jsonbundler" || $flowElement->dataKey === "sequence" || $flowElement->dataKey === "javascriptbuilder" || $flowElement->dataKey === "set-headers") { + if ( + $flowElement->dataKey === 'jsonbundler' || + $flowElement->dataKey === 'sequence' || + $flowElement->dataKey === 'javascriptbuilder' || + $flowElement->dataKey === 'set-headers' + ) { continue; } $properties = $flowElement->getProperties(); if (!$propertyCacheSet) { - $delayExecutionList = []; $delayedEvidenceProperties = []; // Loop over all properties and see if any have delay execution set to true - foreach ($properties as $propertyKey => $propertyMeta) { - - if (isset($propertyMeta["delayexecution"]) && $propertyMeta["delayexecution"]) { + if (isset($propertyMeta['delayexecution']) && $propertyMeta['delayexecution']) { $delayExecutionList[] = $propertyKey; } } // Loop over all properties again and see if any have evidenceproperties which // have delayedExecution set to true - foreach ($properties as $propertyKey => $propertyMeta) { - - if (isset($propertyMeta["evidenceproperties"])) { - - $delayedEvidencePropertiesList = array_filter($propertyMeta["evidenceproperties"], function ($evidenceProperty) use ($delayExecutionList) { - return in_array($evidenceProperty, $delayExecutionList); - }); + if (isset($propertyMeta['evidenceproperties'])) { + $delayedEvidencePropertiesList = array_filter( + $propertyMeta['evidenceproperties'], + function ($evidenceProperty) use ($delayExecutionList) { + return in_array($evidenceProperty, $delayExecutionList); + } + ); if (count($delayedEvidencePropertiesList)) { - $delayedEvidenceProperties[$propertyKey] = array_map(function ($property) use ($flowElement) { - return $flowElement->dataKey . '.' . $property; - }, $delayedEvidencePropertiesList); + $delayedEvidenceProperties[$propertyKey] = array_map( + function ($property) use ($flowElement) { + return $flowElement->dataKey . '.' . $property; + }, + $delayedEvidencePropertiesList + ); } } } $this->propertyCache[$flowElement->dataKey] = [ - "delayExecutionList" => $delayExecutionList, - "evidenceProperties" => $delayedEvidenceProperties + 'delayExecutionList' => $delayExecutionList, + 'evidenceProperties' => $delayedEvidenceProperties ]; } @@ -111,29 +116,24 @@ public function processInternal($flowData) foreach ($properties as $propertyKey => $property) { $value = null; - $nullReason = "Unknown"; + $nullReason = 'Unknown'; // Check if property has delayed execution and set in JSON if yes - - if (in_array($propertyKey, $propertyCache["delayExecutionList"])) { - $output[$flowElement->dataKey][strtolower($propertyKey) . "delayexecution"] = true; + if (in_array($propertyKey, $propertyCache['delayExecutionList'])) { + $output[$flowElement->dataKey][strtolower($propertyKey) . 'delayexecution'] = true; } - // // Check if property has any delayed execution evidence properties and set in JSON if yes - - if (isset($propertyCache["evidenceProperties"][$propertyKey])) { - $output[$flowElement->dataKey][strtolower($propertyKey) . 'evidenceproperties'] = $propertyCache["evidenceProperties"][$propertyKey]; + // Check if property has any delayed execution evidence properties and set in JSON if yes + if (isset($propertyCache['evidenceProperties'][$propertyKey])) { + $output[$flowElement->dataKey][strtolower($propertyKey) . 'evidenceproperties'] = $propertyCache['evidenceProperties'][$propertyKey]; } try { - $valueContainer = $flowData->get($flowElement->dataKey)->get($propertyKey); // Check if value is of the aspect property value type - - if (is_object($valueContainer) && property_exists($valueContainer, "hasValue")) { + if (is_object($valueContainer) && property_exists($valueContainer, 'hasValue')) { // Check if it has a value - if ($valueContainer->hasValue) { $value = $valueContainer->value; } else { @@ -142,41 +142,36 @@ public function processInternal($flowData) } } else { // Standard value - $value = $valueContainer; } } catch (\Exception $e) { // Catching missing property exceptions and other errors - continue; } $output[strtolower($flowElement->dataKey)][strtolower($propertyKey)] = $value; if ($value == null) { - $output[strtolower($flowElement->dataKey)][strtolower($propertyKey) . "nullreason"] = $nullReason; + $output[strtolower($flowElement->dataKey)][strtolower($propertyKey) . 'nullreason'] = $nullReason; } - $sequence = $flowData->evidence->get("query.sequence"); + $sequence = $flowData->evidence->get('query.sequence'); if (!$sequence || $sequence < 10) { // Cloud properties come back as capitalized // TODO change this, but for now - - if (isset($property["Type"])) { - $property["type"] = $property["Type"]; + if (isset($property['Type'])) { + $property['type'] = $property['Type']; } - if (isset($property["type"]) && strtolower($property["type"]) === "javascript") { - $output["javascriptProperties"][] = strtolower($flowElement->dataKey) . "." . strtolower($propertyKey); + if (isset($property['type']) && strtolower($property['type']) === 'javascript') { + $output['javascriptProperties'][] = strtolower($flowElement->dataKey) . '.' . strtolower($propertyKey); } } } } - $data = new ElementDataDictionary($this, ["json" => $output]); + $data = new ElementDataDictionary($this, ['json' => $output]); $flowData->setElementData($data); - - return; } } diff --git a/src/Logger.php b/src/Logger.php index 3e66f39..61c5e2b 100644 --- a/src/Logger.php +++ b/src/Logger.php @@ -24,26 +24,24 @@ namespace fiftyone\pipeline\core; /** - * Logging for a Pipeline + * Logging for a Pipeline. */ class Logger { - private $minLevel; - - private $levels = ["trace", "debug", "information", "warning", "error", "critical"]; - public $settings; + private $minLevel; + private $levels = ['trace', 'debug', 'information', 'warning', 'error', 'critical']; /** - * Create a logger - * @param string level ("trace", "debug", "information", "warning", "error", "critical") - * @param array settings - customs settings for a logger + * Create a logger. * - **/ - public function __construct($level, $settings = array()) + * @param string $level Values: 'trace', 'debug', 'information', 'warning', 'error', 'critical' + * @param array $settings Custom settings for a logger + */ + public function __construct($level, $settings = []) { if (!$level) { - $level = "error"; + $level = 'error'; } $this->settings = $settings; @@ -51,31 +49,32 @@ public function __construct($level, $settings = array()) } /** - * Log a message - * @param string message level - * @param string message - */ + * Log a message. + * + * @param string $level + * @param string $message + */ public function log($level, $message) { $levelIndex = array_search(strtolower($level), $this->levels); if ($levelIndex >= $this->minLevel) { - $log = array( - - "time" => date('Y-m-d H:i:s'), - "level" => $level, - "message" => $message - - ); + $log = [ + 'time' => date('Y-m-d H:i:s'), + 'level' => $level, + 'message' => $message + ]; $this->logInternal($log); } } /** - * Internal logging function overriden by specific loggers - * @param array log - */ + * Internal logging function overridden by specific loggers. + * + * @param array $log + * @return array + */ public function logInternal($log) { return $log; diff --git a/src/Messages.php b/src/Messages.php index edb3a70..80e6aac 100644 --- a/src/Messages.php +++ b/src/Messages.php @@ -28,41 +28,36 @@ * messages, or otherwise. Messages which require formatting will contain * format characters e.g. %s. */ -class Messages { +class Messages +{ /** * Error message thrown when there is no matching element in the FlowData. */ - const NO_ELEMENT_DATA = "There is no element data for '%s' against " - . "this flow data. Available element data keys are: '%s'"; - const NO_ELEMENT_DATA_NULL = "There is no element data for '%s' against " - . "this flow data.'"; - const PASS_KEY_VALUE = "Must pass key and value"; - const FLOW_DATA_PROCESSED = "FlowData already processed"; + public const NO_ELEMENT_DATA = "There is no element data for '%s' against this flow data. Available element data keys are: '%s'"; + public const NO_ELEMENT_DATA_NULL = "There is no element data for '%s' against this flow data.'"; + public const PASS_KEY_VALUE = 'Must pass key and value'; + public const FLOW_DATA_PROCESSED = 'FlowData already processed'; /** - * Property does not start with SetHeader. This takes the name of a property - * as a format argument. + * Property does not start with SetHeader. This takes the name of a property as a format argument. */ - const PROPERTY_NOT_SET_HEADER = "Property Name '%s' does not start with 'SetHeader'."; - + public const PROPERTY_NOT_SET_HEADER = "Property Name '%s' does not start with 'SetHeader'."; + /** - * Property Name is not in the valid format. This takes the property name + * Property Name is not in the valid format. This takes the property name * as format argument. */ - const WRONG_PROPERTY_FORMAT = - "Property Name '%s' is not in the expected format i.e. SetHeader[Component][HeaderName]. "; + public const WRONG_PROPERTY_FORMAT = "Property Name '%s' is not in the expected format i.e. SetHeader[Component][HeaderName]. "; /** - * Element not found in flowData. This takes the element datakey + * Element not found in flowData. This takes the element datakey * as format argument. */ - const ELEMENT_NOT_FOUND = - "Element '%s' is not present in the FlowData. "; + public const ELEMENT_NOT_FOUND = "Element '%s' is not present in the FlowData. "; /** - * Property not found in flowData. This takes the element datakey + * Property not found in flowData. This takes the element dataKey * and property names as format arguments. - */ - const PROPERTY_NOT_FOUND = - "Property '%s' is not present in the FlowData against '%s' ElementData. "; + */ + public const PROPERTY_NOT_FOUND = "Property '%s' is not present in the FlowData against '%s' ElementData. "; } diff --git a/src/Pipeline.php b/src/Pipeline.php index 2b49327..61c21d7 100644 --- a/src/Pipeline.php +++ b/src/Pipeline.php @@ -24,48 +24,40 @@ namespace fiftyone\pipeline\core; /** -* Pipeline holding a list of FlowElements for processing, -* can create FlowData that will be passed through these, -* collecting ElementData -* Should be constructed through the PipelineBuilder class -**/ + * Pipeline holding a list of FlowElements for processing, + * can create FlowData that will be passed through these, + * collecting ElementData + * Should be constructed through the PipelineBuilder class. + */ class Pipeline { public $flowElements; - public $flowElementsList = array(); + public $flowElementsList = []; public $logger; public $metaDataStore; public $suppressProcessExceptions; public $propertyDatabase; /** - * Pipeline constructor - * @param FlowElement[] list of FlowElements - * @param array settings array - */ + * Pipeline constructor. + * + * @param FlowElement[] $flowElements List of FlowElements + * @param array $settings + */ public function __construct($flowElements, $settings) { - if (!isset($settings["logger"])) { - $this->logger = new Logger(null, null); - } else { - $this->logger = $settings["logger"]; - } + $this->logger = $settings['logger'] ?? new Logger(null); - /* If true then pipeline will suppress exceptions - added to FlowData errors otherwise will throw the - exception occurred during the processing of first - element.*/ - if (!isset($settings["suppressProcessExceptions"])) { - $this->suppressProcessExceptions = false; - } else { - $this->suppressProcessExceptions = $settings["suppressProcessExceptions"]; - } - - $this->log("info", "test"); + /* + * If true then pipeline will suppress exceptions added to FlowData errors, + * otherwise will throw the exception occurred during the processing of the + * first element. + */ + $this->suppressProcessExceptions = (bool) ($settings['suppressProcessExceptions'] ?? false); $this->flowElements = $flowElements; - $this->propertyDatabase = array(); + $this->propertyDatabase = []; foreach ($flowElements as $flowElement) { $this->flowElementsList[$flowElement->dataKey] = $flowElement; @@ -79,22 +71,28 @@ public function __construct($flowElements, $settings) } /** - * Create a FlowData based on what's in the Pipeline + * Create a FlowData based on what's in the Pipeline. + * * @return FlowData - */ + */ public function createFlowData() { - return new FlowData($this, $this->flowElements); + return new FlowData($this); } + /** + * @param string $level + * @param string $message + */ public function log($level, $message) { $this->logger->log($level, $message); } /** - * Get a FlowElement by its name - * @param string name + * Get a FlowElement by its name. + * + * @param string $key * @return FlowElement */ public function getElement($key) @@ -103,19 +101,19 @@ public function getElement($key) } /** - * Update metadata store for a FlowElement based on its list of properties - * @param FlowElement + * Update metadata store for a FlowElement based on its list of properties. + * + * @param FlowElement $flowElement */ public function updatePropertyDatabaseForFlowElement($flowElement) { $dataKey = $flowElement->dataKey; // First unset any properties stored by the FlowElement - foreach ($this->propertyDatabase as $propertyValues) { foreach ($propertyValues as $propertyList) { foreach ($propertyList as $key => $info) { - if ($info["flowElement"] === $dataKey) { + if ($info['flowElement'] === $dataKey) { unset($propertyList[$key]); } } @@ -126,24 +124,23 @@ public function updatePropertyDatabaseForFlowElement($flowElement) foreach ($properties as $key => $property) { foreach ($property as $metaKey => $metaValue) { - $metaKey = \strtolower($metaKey); - + $metaKey = strtolower($metaKey); if (!isset($this->propertyDatabase[$metaKey])) { - $this->propertyDatabase[$metaKey] = array(); + $this->propertyDatabase[$metaKey] = []; } - if (is_string($metaValue)) { - $metaValue = \strtolower($metaValue); - } else { + if (!is_string($metaValue)) { continue; } + $metaValue = strtolower($metaValue); + if (!isset($this->propertyDatabase[$metaKey][$metaValue])) { - $this->propertyDatabase[$metaKey][$metaValue] = array(); + $this->propertyDatabase[$metaKey][$metaValue] = []; } - $property["flowElement"] = $dataKey; + $property['flowElement'] = $dataKey; $this->propertyDatabase[$metaKey][$metaValue][$key] = $property; } diff --git a/src/PipelineBuilder.php b/src/PipelineBuilder.php index 2e0ba1d..8bf5353 100644 --- a/src/PipelineBuilder.php +++ b/src/PipelineBuilder.php @@ -24,83 +24,35 @@ namespace fiftyone\pipeline\core; /** - * A PipelineBuilder generates a Pipeline object - * Before construction of the Pipeline, FlowElements are added to it - * There are also options for how JavaScript is output from the Pipeline -*/ + * A PipelineBuilder generates a Pipeline object + * Before construction of the Pipeline, FlowElements are added to it + * There are also options for how JavaScript is output from the Pipeline. + */ class PipelineBuilder { public $pipelines; public $addJavaScriptBuilder; - public $javascriptBuilderSettings; + public $javascriptBuilderSettings = []; public $useSetHeaderProperties; + protected $flowElements = []; + protected $settings = []; - public function __construct($settings = array()) + public function __construct($settings = []) { - // List of Pipelines the FlowElement has been added to $this->pipelines = []; - if (isset($settings["addJavaScriptBuilder"])) { - $this->addJavaScriptBuilder = $settings["addJavaScriptBuilder"]; - } else { - $this->addJavaScriptBuilder = true; - } - - if (isset($settings["javascriptBuilderSettings"])) { - $this->javascriptBuilderSettings = $settings["javascriptBuilderSettings"]; - } - - if (isset($settings["useSetHeaderProperties"])) { - $this->useSetHeaderProperties = $settings["useSetHeaderProperties"]; - } else { - $this->useSetHeaderProperties = true; - } + $this->addJavaScriptBuilder = (bool) ($settings['addJavaScriptBuilder'] ?? true); + $this->javascriptBuilderSettings = $settings['javascriptBuilderSettings'] ?? []; + $this->useSetHeaderProperties = (bool) ($settings['useSetHeaderProperties'] ?? true); } - private function getJavaScriptElements() - { - $flowElements = []; - - if ($this->addJavaScriptBuilder) { - // Add JavaScript elements - - $flowElements[] = new SequenceElement(); - $flowElements[] = new JsonBundlerElement(); - - if ($this->javascriptBuilderSettings !== null) { - $flowElements[] = new JavascriptBuilderElement($this->javascriptBuilderSettings); - } else { - $flowElements[] = new JavascriptBuilderElement([]); - } - } - - return $flowElements; - } - - private function getSetHeaderElements() - { - $flowElements = []; - - if ($this->useSetHeaderProperties) { - - // Add SetHeader elements - $flowElements[] = new SetHeaderElement(); - } - - return $flowElements; - } - - /** - * array of FlowElements - **/ - protected $flowElements = array(); - protected $settings = array(); - /** - * Add FlowElement to be used in Pipeline - * @param FlowElement - */ + * Add FlowElement to be used in Pipeline. + * + * @param FlowElement $flowElement + * @return static + */ public function add($flowElement) { $this->flowElements[] = $flowElement; @@ -109,70 +61,108 @@ public function add($flowElement) } /** - * Build Pipeline once done + * Build Pipeline once done. + * * @return Pipeline - */ + */ public function build() { - $this->flowElements = array_merge($this->flowElements, - $this->getJavaScriptElements(), - $this->getSetHeaderElements()); + $this->flowElements = array_merge( + $this->flowElements, + $this->getJavaScriptElements(), + $this->getSetHeaderElements() + ); return new Pipeline($this->flowElements, $this->settings); } /** - * Add an instance of the logger class to the Pipeline - * @param Logger - * @return PipelineBuilder - */ + * Add an instance of the logger class to the Pipeline. + * + * @param Logger $logger + * @return static + */ public function addLogger($logger) { - $this->settings["logger"] = $logger; + $this->settings['logger'] = $logger; return $this; } /** - * Build from a JSON configuration file - * This JSON file should look like the following - * `{ - * "PipelineOptions": { - * "Elements": [ - * { - * "BuilderName": // Name of element as in use statement, - * "BuildParameters": { - * // An object of parameters passed to the constructor - * } - * }] - * }` - * @param string file name of the file to load config, or alternatively - * pass a config object already read from file - * @return Pipeline - */ + * Build from a JSON configuration file + * This JSON file should have the following structure: + * `{ + * "PipelineOptions": { + * "Elements": [ + * { + * "BuilderName": // Name of element as in use statement, + * "BuildParameters": { + * // An object of parameters passed to the constructor + * } + * }] + * }`. + * + * @param array|string $fileOrConfig Filename of the config file to load config or associative array of config values + * @return Pipeline + */ public function buildFromConfig($fileOrConfig) { - if (is_string($fileOrConfig)) - { + if (is_string($fileOrConfig)) { $config = json_decode(file_get_contents($fileOrConfig), true); - } - else - { + } else { $config = $fileOrConfig; } - foreach ($config["PipelineOptions"]["Elements"] as $element) { - $builder = $element["BuilderName"]; + foreach ($config['PipelineOptions']['Elements'] as $element) { + $builder = $element['BuilderName']; - if (isset($element["BuildParameters"])) { - $flowElement = new $builder($element["BuildParameters"]); + if (isset($element['BuildParameters'])) { + $flowElement = new $builder($element['BuildParameters']); } else { $flowElement = new $builder(); } - + $this->flowElements[] = $flowElement; } return new Pipeline($this->flowElements, $this->settings); } + + /** + * @return FlowElement[] + */ + private function getJavaScriptElements() + { + $flowElements = []; + + if ($this->addJavaScriptBuilder) { + // Add JavaScript elements + $flowElements[] = new SequenceElement(); + $flowElements[] = new JsonBundlerElement(); + + if ($this->javascriptBuilderSettings === null) { + $flowElements[] = new JavascriptBuilderElement([]); + } else { + $flowElements[] = new JavascriptBuilderElement($this->javascriptBuilderSettings); + } + } + + return $flowElements; + } + + /** + * @return FlowElement[] + */ + private function getSetHeaderElements() + { + $flowElements = []; + + if ($this->useSetHeaderProperties) { + // Add SetHeader elements + $flowElements[] = new SetHeaderElement(); + } + + return $flowElements; + } } diff --git a/src/SequenceElement.php b/src/SequenceElement.php index 2646978..231c092 100644 --- a/src/SequenceElement.php +++ b/src/SequenceElement.php @@ -24,26 +24,28 @@ namespace fiftyone\pipeline\core; /** - * The SequenceElement stores session data regarding - * requests for client side JavaScript from the JavaScript - * created by a Pipeline's JavaScriptBuilder - * If a Pipeline is constructed with the JavaScript elements - * enabled this is added automatically along with the JavaScriptBuilder - * and JSONBundler. -**/ + * The SequenceElement stores session data regarding + * requests for client side JavaScript from the JavaScript + * created by a Pipeline's JavaScriptBuilder + * If a Pipeline is constructed with the JavaScript elements + * enabled this is added automatically along with the JavaScriptBuilder + * and JSONBundler. + */ class SequenceElement extends FlowElement { - public $dataKey = "sequence"; + public $dataKey = 'sequence'; /** - * The SequenceElement uses query.sequence and query.session-id evidence - */ + * The SequenceElement uses query.sequence and query.session-id evidence. + * + * @return EvidenceKeyFilter + */ public function getEvidenceKeyFilter() { $filter = new EvidenceKeyFilter(); $filter->filterEvidenceKey = function ($key) { - if ($key == "query.sequence" || $key == "query.session-id") { + if ($key === 'query.sequence' || $key === 'query.session-id') { return true; } @@ -54,30 +56,26 @@ public function getEvidenceKeyFilter() } /** - * The SequenceElement stores session data for requests for JavaScript - * @param {FlowData} FlowData - */ + * The SequenceElement stores session data for requests for JavaScript. + * + * @param FlowData $flowData + */ public function processInternal($flowData) { - if ($flowData->evidence->get("query.session-id")) { + if ($flowData->evidence->get('query.session-id')) { // Get current sequence number - - $sequence = $flowData->evidence->get("query.sequence"); - + $sequence = $flowData->evidence->get('query.sequence'); + if ($sequence) { $sequence = intval($sequence); } else { $sequence = 1; } - - $flowData->evidence->set("query.sequence", $sequence + 1); + + $flowData->evidence->set('query.sequence', $sequence + 1); } else { - $flowData->evidence->set( - "query.session-id", - uniqid() - ); - - $flowData->evidence->set("query.sequence", 1); + $flowData->evidence->set('query.session-id', uniqid()); + $flowData->evidence->set('query.sequence', 1); } } } diff --git a/src/SetHeaderElement.php b/src/SetHeaderElement.php index 497eb1d..9a3ba65 100644 --- a/src/SetHeaderElement.php +++ b/src/SetHeaderElement.php @@ -23,201 +23,186 @@ namespace fiftyone\pipeline\core; -use Exception; - /** - * Set response headers element class. This is used to get response - * headers based on what the browser supports. For example, newer - * Chrome browsers support the Accept-CH header + * Set response headers element class. This is used to get response + * headers based on what the browser supports. For example, newer + * Chrome browsers support the Accept-CH header. */ -class SetHeaderElement extends FlowElement { - - public $dataKey = "set-headers"; +class SetHeaderElement extends FlowElement +{ + public $dataKey = 'set-headers'; private $setHeaderProperties = []; /** - * Add the response header dictionary to the FlowData. - * @param FlowData FlowData + * Add the response header dictionary to the FlowData. + * + * @param FlowData $flowData */ - public function processInternal($flowData) { - - if(empty($setHeaderProperties)){ - - $this->setHeaderProperties = $this->getSetHeaderPropertiesPipeline($flowData->pipeline); - } + public function processInternal($flowData) + { + if (empty($setHeaderProperties)) { + $this->setHeaderProperties = $this->getSetHeaderPropertiesPipeline($flowData->pipeline); + } - $responseHeaders = $this->getResponseHeaderValue($flowData, $this->setHeaderProperties); + $responseHeaders = $this->getResponseHeaderValue($flowData, $this->setHeaderProperties); - $data = new ElementDataDictionary($this, ["responseheaderdictionary" => $responseHeaders]); + $data = new ElementDataDictionary($this, ['responseheaderdictionary' => $responseHeaders]); $flowData->setElementData($data); - - return; } - /** - * Get All the properties starting with SetHeader string from pipeline - * @param pipeline Pipeline - * @return A dictionary object containing SetHeader properties list against flowElement + /** + * Get All the properties starting with SetHeader string from pipeline. + * + * @param Pipeline $pipeline + * @return array A dictionary object containing SetHeader properties list against flowElement */ - public function getSetHeaderPropertiesPipeline($pipeline) { - $setHeaderPropertiesDict = []; - - // Loop over each flowElement in pipeline to check SetHeader properties - foreach ($pipeline->flowElements as $flowElement) { + public function getSetHeaderPropertiesPipeline($pipeline) + { + $setHeaderPropertiesDict = []; - # Get the properties against the flowElement - $properties = $flowElement->getProperties(); + // Loop over each flowElement in pipeline to check SetHeader properties + foreach ($pipeline->flowElements as $flowElement) { + // Get the properties against the flowElement + $properties = $flowElement->getProperties(); - $setHeaderElementList = []; + $setHeaderElementList = []; // Loop over each flowElement property - foreach ($properties as $propertyKey => $propertyMeta) { - // Check if the property starts ith SetHeader - if(strpos($propertyKey, "setheader") !== false){ - array_push($setHeaderElementList, $propertyMeta["name"]); - } - } - - // Add SetHeader element list in dict against flowElement.datakey as key - if (count($setHeaderElementList)) { - $setHeaderPropertiesDict[$flowElement->dataKey] = $setHeaderElementList; - } - } - - return $setHeaderPropertiesDict; + foreach ($properties as $propertyKey => $propertyMeta) { + // Check if the property starts ith SetHeader + if (strpos($propertyKey, 'setheader') !== false) { + $setHeaderElementList[] = $propertyMeta['name']; + } + } + + // Add SetHeader element list in dict against flowElement.datakey as key + if (count($setHeaderElementList)) { + $setHeaderPropertiesDict[$flowElement->dataKey] = $setHeaderElementList; + } + } + + return $setHeaderPropertiesDict; } - - /** - * Get response header value using set header properties from FlowData - * @param flowdata A processed FlowData object containing setheader properties - * @param setHeaderPropertiesDict A processed FlowData object containing setheader properties - * @return A dictionary object containing SetHeader properties list against flowElement + + /** + * Get response header value using set header properties from FlowData. + * + * @param FlowData $flowData A processed FlowData object containing setheader properties + * @param array $setHeaderPropertiesDict A processed FlowData object containing setheader properties + * @return array A dictionary object containing SetHeader properties list against flowElement */ - public function getResponseHeaderValue($flowData, $setHeaderPropertiesDict) { - $responseHeadersDict = []; + public function getResponseHeaderValue($flowData, $setHeaderPropertiesDict) + { + $responseHeadersDict = []; // Loop over all the flowElements to process Set Header properties for User Agent Client Hints foreach ($setHeaderPropertiesDict as $elementDataKey => $setHeaderElementList) { - - // Loop over each setHeader property of the element - foreach ($setHeaderElementList as $setHeaderProperty) { - + // Loop over each setHeader property of the element + foreach ($setHeaderElementList as $setHeaderProperty) { // Get response header key to be set in response $responseHeader = $this->getResponseHeaderName($setHeaderProperty); // Get SetHeader property value from elementData $setHeaderValue = $this->getPropertyValue($flowData, $elementDataKey, $setHeaderProperty); - if (isset($responseHeadersDict[$responseHeader])) { - $responseHeaderValue = $responseHeadersDict[$responseHeader]; - if($responseHeaderValue == ""){ - $responseHeaderValue = $setHeaderValue; - } - else{ - if($setHeaderValue != ""){ - $responseHeaderValue = $responseHeaderValue . "," . $setHeaderValue; - } - } - $responseHeadersDict[$responseHeader] = $responseHeaderValue; - } - else { - $responseHeadersDict[$responseHeader] = $setHeaderValue; - } - } - } - return $responseHeadersDict; + if (isset($responseHeadersDict[$responseHeader])) { + $responseHeaderValue = $responseHeadersDict[$responseHeader]; + if ($responseHeaderValue == '') { + $responseHeaderValue = $setHeaderValue; + } else { + if ($setHeaderValue != '') { + $responseHeaderValue = $responseHeaderValue . ',' . $setHeaderValue; + } + } + $responseHeadersDict[$responseHeader] = $responseHeaderValue; + } else { + $responseHeadersDict[$responseHeader] = $setHeaderValue; + } + } + } + + return $responseHeadersDict; } - /** - * Try to get the value for the given element and property. - * If the value cannot be found or is null/unknown, then "" - * will be returned. - * @param flowData A processed FlowData instance to get the value from. - * @param elementKey Key for the element data to get the value from - * @param propertyKey Name of the property to get the value for. - * @return value or empty string + /** + * Try to get the value for the given element and property. + * If the value cannot be found or is null/unknown, then an empty string will be returned. + * + * @param FlowData $flowData A processed FlowData instance to get the value from + * @param string $elementKey Key for the element data to get the value from + * @param string $propertyKey name of the property to get the value for + * @return string */ - public function getPropertyValue($flowData, $elementKey, $propertyKey){ + public function getPropertyValue($flowData, $elementKey, $propertyKey) + { + if ($flowData->{$elementKey}) { + // Get the elementData from flowData that contains required property. + $elementData = $flowData->{$elementKey}; + } else { + echo sprintf(Messages::ELEMENT_NOT_FOUND, $elementKey); - $value = ""; + return ''; + } - if($flowData->$elementKey) { - // Get the elementData from flowData that contains required property. - $elementData = $flowData->$elementKey; - } - else{ - echo sprintf(Messages::ELEMENT_NOT_FOUND, $elementKey); - return ""; - } - - $propertyKey = strtolower($propertyKey); - // TODO: catch is never called here. Consider replacing it with: - // if (isset($elementData->$propertyKey)) - // The change can't be made right now, as it causes device-detection-php - // tests to fail. Further investigation is needed. - try { - $property = $elementData->$propertyKey; - } catch (Exception $e) { - echo sprintf(Messages::PROPERTY_NOT_FOUND, $propertyKey, $elementKey); - return ""; - } - - if($property && $property->hasValue && !in_array($property->value, ["Unknown", "noValue"])){ - $value = $property->value; - } - else{ - $value = ""; - } - return $value; + $propertyKey = strtolower($propertyKey); + + // TODO: catch is never called here. Consider replacing it with: + // if (isset($elementData->$propertyKey)) + // The change can't be made right now, as it causes device-detection-php + // tests to fail. Further investigation is needed. + try { + $property = $elementData->{$propertyKey}; + } catch (\Exception $e) { + echo sprintf(Messages::PROPERTY_NOT_FOUND, $propertyKey, $elementKey); + + return ''; + } + + if ($property && $property->hasValue && !in_array($property->value, ['Unknown', 'noValue'])) { + return $property->value; + } + + return ''; } - /** - * Determines which response header the property value will be appended to by - * stripping the 'SetHeader' string and the 'Component Name' from the property name. - * @param propertyKey Key for SetHeaderAcceptCH property - * @return Response Header name + /** + * Determines which response header the property value will be appended to by + * stripping the 'SetHeader' string and the 'Component Name' from the property name. + * + * @param string $propertyKey Key for SetHeaderAcceptCH property + * @return string Response Header name + * @throws \Exception */ - public function getResponseHeaderName($propertyKey) { - - $actualPropertyName = $propertyKey; - $responseHeader = ""; - - // Check if property name starts with SetHeader. - // If Yes, Discard SetHeader from property name. - if(strcmp(substr($propertyKey, 0, 9), "SetHeader") !== 0){ - throw new Exception(sprintf( - Messages::PROPERTY_NOT_SET_HEADER, - $actualPropertyName)); - } - else{ - $propertyKey = str_replace("SetHeader", "", $propertyKey); - } - - // Check if the first letter of Component name is in Uppercase - // If Yes, Split the propertyKey based on Uppercase letters - if(ctype_upper(substr($propertyKey, 0,1)) == FALSE){ - throw new Exception(sprintf( - Messages::WRONG_PROPERTY_FORMAT, - $actualPropertyName)); - } - else{ - $parts = preg_split('/(?=[A-Z][^A-Z]*)/', $propertyKey, -1, PREG_SPLIT_NO_EMPTY); - - // Get the Component name string to be removed from the key - $discardLetter = $parts[0]; - } - - // Check if property name contains the header name that starts with upper case - // If Yes, Remove the previously found Component Name to get the Header Name - if (count($parts) <= 1){ - throw new Exception(sprintf( - Messages::WRONG_PROPERTY_FORMAT, - $actualPropertyName)); } - else{ - $responseHeader = str_replace($discardLetter, "", $propertyKey); - } - - return $responseHeader; + public function getResponseHeaderName($propertyKey) + { + $actualPropertyName = $propertyKey; + + // Check if property name starts with SetHeader. + // If Yes, Discard SetHeader from property name. + if (strcmp(substr($propertyKey, 0, 9), 'SetHeader') !== 0) { + throw new \Exception(sprintf(Messages::PROPERTY_NOT_SET_HEADER, $actualPropertyName)); + } + + $propertyKey = str_replace('SetHeader', '', $propertyKey); + + // Check if the first letter of Component name is in Uppercase + // If Yes, Split the propertyKey based on Uppercase letters + if (ctype_upper(substr($propertyKey, 0, 1)) === false) { + throw new \Exception(sprintf(Messages::WRONG_PROPERTY_FORMAT, $actualPropertyName)); + } + + $parts = preg_split('/(?=[A-Z][^A-Z]*)/', $propertyKey, -1, PREG_SPLIT_NO_EMPTY); + + // Get the Component name string to be removed from the key + $discardLetter = $parts[0]; + + // Check if property name contains the header name that starts with upper case + // If Yes, Remove the previously found Component Name to get the Header Name + if (count($parts) <= 1) { + throw new \Exception(sprintf(Messages::WRONG_PROPERTY_FORMAT, $actualPropertyName)); + } + + return str_replace($discardLetter, '', $propertyKey); } } diff --git a/src/Utils.php b/src/Utils.php index f1feba6..4dd825d 100644 --- a/src/Utils.php +++ b/src/Utils.php @@ -25,26 +25,25 @@ class Utils { - /** - * Set response headers in the response object (e.g. Accept-CH) - * @param response: The response to set the headers in. - * @param flowData: A processed FlowData instance to get the response header values - * from. - */ - public static function setResponseHeader($flowData) + /** + * Set response headers in the response object (e.g. Accept-CH). + * + * @param FlowData $flowData A processed FlowData instance to get the response header values from + */ + public static function setResponseHeader($flowData) { $setHeaderElementKey = Constants::SETHEADER_ELEMENT_KEY; $setHeaderDataKey = Constants::SETHEADER_DATA_KEY; - // Get response headers dictionary containing key values to be set in response - $responseHeaderDict = $flowData->$setHeaderElementKey->$setHeaderDataKey; - + // Get response headers dictionary containing key values to be set in response + $responseHeaderDict = $flowData->{$setHeaderElementKey}->{$setHeaderDataKey}; + foreach ($responseHeaderDict as $responseKey => $responseValue) { - $responseValue = str_replace(",", ", ", $responseValue); - - if(strlen($responseValue) > 0){ - echo header("$responseKey: $responseValue"); + $responseValue = str_replace(',', ', ', $responseValue); + + if (strlen($responseValue) > 0) { + header("{$responseKey}: {$responseValue}"); } } } -} \ No newline at end of file +} diff --git a/tests/CoreTests.php b/tests/CoreTests.php index ec7e409..e9895f2 100644 --- a/tests/CoreTests.php +++ b/tests/CoreTests.php @@ -37,46 +37,45 @@ class CoreTests extends TestCase public function testLogger() { $testPipeline = new TestPipeline(); - $loggerMessage = $testPipeline->logger->log[0]["message"]; - $this->assertTrue($loggerMessage === "test"); + $loggerMessage = $testPipeline->logger->log[0]['message']; + $this->assertSame('test', $loggerMessage); } - + // Test getting evidence public function testEvidence() { $testPipeline = new TestPipeline(); - $userAgent = $testPipeline->flowData->evidence->get("header.user-agent"); - $this->assertTrue($userAgent === "test"); + $userAgent = $testPipeline->flowData->evidence->get('header.user-agent'); + $this->assertSame('test', $userAgent); } // Test filtering evidence public function testEvidenceKeyFilter() { $testPipeline = new TestPipeline(); - $nullEvidence = $testPipeline->flowData->evidence->get("header.other-evidence"); - $this->assertTrue($nullEvidence === null); + $nullEvidence = $testPipeline->flowData->evidence->get('header.other-evidence'); + $this->assertNull($nullEvidence); } // Test Getter methods public function testGet() { $testPipeline = new TestPipeline(); - $getValue = $testPipeline->flowData->get("example1")->get("integer"); - $this->assertTrue($getValue === 5); + $getValue = $testPipeline->flowData->get('example1')->get('integer'); + $this->assertSame(5, $getValue); } public function testGetWhere() { $testPipeline = new TestPipeline(); - $getValue = count($testPipeline->flowData->getWhere("type", "int")); - $this->assertTrue($getValue === 1); + $this->assertCount(1, $testPipeline->flowData->getWhere('type', 'int')); } public function testGetFromElement() { $testPipeline = new TestPipeline(); - $getValue = $testPipeline->flowData->getFromElement($testPipeline->flowElement1)->get("integer"); - $this->assertTrue($getValue === 5); + $getValue = $testPipeline->flowData->getFromElement($testPipeline->flowElement1)->get('integer'); + $this->assertSame(5, $getValue); } // Test check stop FlowData works @@ -84,25 +83,25 @@ public function testStopFlowData() { $getValue = null; $testPipeline = new TestPipeline(); + try { - $getValue = $testPipeline->flowData->get("example2"); + $getValue = $testPipeline->flowData->get('example2'); $this->fail(); - } - catch (\Exception $e) { + } catch (\Exception $e) { // An exception should be thrown. } - $this->assertTrue($getValue === null); + + $this->assertNull($getValue); } // Test exception is thrown when not suppressed. - public function testErrors_DontSuppressException() { - + public function testErrorsDontSuppressException() + { try { $testPipeline = new TestPipeline(false); - $this->fail("Exception is expected."); - } - catch (\Exception $e) { - $this->assertTrue(!empty($e->getMessage())); + $this->fail('Exception is expected.'); + } catch (\Exception $e) { + $this->assertNotEmpty($e->getMessage()); } } @@ -110,50 +109,49 @@ public function testErrors_DontSuppressException() { public function testErrors() { $testPipeline = new TestPipeline(); - $getValue = $testPipeline->flowData->errors["error"]; - $this->assertTrue(isset($getValue)); + $getValue = $testPipeline->flowData->errors['error']; + $this->assertNotNull($getValue); } // Test Already Processed FlowData. - public function testErrors_AlreadyProcessed() { - - $logger = new MemoryLogger("info"); - $flowElement1 = new ExampleFlowElement1(); - $pipeline = (new PipelineBuilder()) - ->add($flowElement1) - ->addLogger($logger) - ->build(); - $flowData = $pipeline->createFlowData(); - $flowData->process(); + public function testErrorsAlreadyProcessed() + { + $logger = new MemoryLogger('info'); + $flowElement1 = new ExampleFlowElement1(); + $pipeline = (new PipelineBuilder()) + ->add($flowElement1) + ->addLogger($logger) + ->build(); + $flowData = $pipeline->createFlowData(); + $flowData->process(); + try { $flowData->process(); - $this->fail("Exception is expected."); - } - catch (\Exception $e) { - $this->assertEquals($e->getMessage(), "FlowData already processed"); + $this->fail('Exception is expected.'); + } catch (\Exception $e) { + $this->assertSame('FlowData already processed', $e->getMessage()); } } - + // Test if adding properties at a later stage works (for cloud FlowElements for example) public function testUpdateProperties() { $flowElement1 = new ExampleFlowElement1(); - $logger = new MemoryLogger("info"); + $logger = new MemoryLogger('info'); $pipeline = (new PipelineBuilder())->add($flowElement1) - ->add(new StopFlowData()) - ->add(new ExampleFlowElement2()) - ->addLogger($logger) - ->build(); - $flowElement1->properties["integer"]["testing"] = "true"; + ->add(new StopFlowData()) + ->add(new ExampleFlowElement2()) + ->addLogger($logger) + ->build(); + $flowElement1->properties['integer']['testing'] = 'true'; $flowData = $pipeline->createFlowData(); - $flowData->evidence->set("header.user-agent", "test"); - $flowData->evidence->set("some.other-evidence", "test"); + $flowData->evidence->set('header.user-agent', 'test'); + $flowData->evidence->set('some.other-evidence', 'test'); $flowData->process(); - $getValue = count($flowData->getWhere("testing", "true")); - $this->assertTrue($getValue === 0); + $this->assertCount(0, $flowData->getWhere('testing', 'true')); + $flowElement1->updatePropertyList(); - $getValue = count($flowData->getWhere("testing", "true")); - $this->assertTrue($getValue === 1); + $this->assertCount(1, $flowData->getWhere('testing', 'true')); } } diff --git a/tests/ExampleTests.php b/tests/ExampleTests.php index a64d058..5828fed 100644 --- a/tests/ExampleTests.php +++ b/tests/ExampleTests.php @@ -30,16 +30,16 @@ class ExampleTests extends TestCase public function testCustomFlowElementExample() { ob_start(); // hide output - include __DIR__ . "/../examples/CustomFlowElement.php"; + include __DIR__ . '/../examples/CustomFlowElement.php'; ob_end_clean(); // discard output - $this->assertTrue(strpos($output, "Starsign") !== false); + $this->assertTrue(strpos($output, 'Starsign') !== false); } public function testPipelineExample() { - include __DIR__ . "/../examples/Pipeline.php"; + include __DIR__ . '/../examples/Pipeline.php'; - $this->assertTrue($FlowData->example1->exampleProperty1 === 5); + $this->assertTrue($flowData->example1->exampleProperty1 === 5); } } diff --git a/tests/FlowDataTests.php b/tests/FlowDataTests.php index 87c6a16..12e285d 100644 --- a/tests/FlowDataTests.php +++ b/tests/FlowDataTests.php @@ -23,140 +23,118 @@ namespace fiftyone\pipeline\core\tests; -use fiftyone\pipeline\core\FlowData; use fiftyone\pipeline\core\ElementData; +use fiftyone\pipeline\core\FlowData; use fiftyone\pipeline\core\FlowElement; use fiftyone\pipeline\core\Messages; - use PHPUnit\Framework\TestCase; -class FlowDataTests extends TestCase { - +class FlowDataTests extends TestCase +{ /** * Check that an element data can be returned from a FlowData using its * data key. */ - public function testGetWithKey() { + public function testGetWithKey() + { $element = $this->createMock(FlowElement::class); - $element->dataKey = "testKey"; + $element->dataKey = 'testKey'; $data = new ElementData($element); - + $flowData = new FlowData(null); $flowData->setElementData($data); - - $returnedData = $flowData->get("testKey"); + + $returnedData = $flowData->get('testKey'); $this->assertNotNull($returnedData); } - + /** * Check that an element data can be returned from a FlowData using its * data key directly via a "magic getter". */ - public function testMagicGetter() { + public function testMagicGetter() + { $element = $this->createMock(FlowElement::class); - $element->dataKey = "testKey"; + $element->dataKey = 'testKey'; $data = new ElementData($element); - + $flowData = new FlowData(null); $flowData->setElementData($data); - + $returnedData = $flowData->testKey; $this->assertNotNull($returnedData); } - + /** * Check that an element data can be returned from a FlowData using the * getFromElement method. */ - public function testGetFromElement() { + public function testGetFromElement() + { $element = $this->createMock(FlowElement::class); - $element->dataKey = "testKey"; + $element->dataKey = 'testKey'; $data = new ElementData($element); - + $flowData = new FlowData(null); $flowData->setElementData($data); - + $returnedData = $flowData->getFromElement($element); $this->assertNotNull($returnedData); } - + /** * Check that an exception is thrown when fetching a key which does not * exist in the FlowData, and that the correct error message is returned. */ - public function testMissingKey() { + public function testMissingKey() + { $element = $this->createMock(FlowElement::class); - $element->dataKey = "testKey"; + $element->dataKey = 'testKey'; $data = new ElementData($element); - + $flowData = new FlowData(null); $flowData->setElementData($data); - try { - $returnedData = $flowData->get("otherKey"); - $this->fail(); - } - catch (\Exception $e) { - $this->assertEquals( - sprintf(Messages::NO_ELEMENT_DATA, - "otherKey", - "testKey"), - $e->getMessage()); - } + $this->expectExceptionMessage(sprintf(Messages::NO_ELEMENT_DATA, 'otherKey', 'testKey')); + $flowData->get('otherKey'); } - + /** * Check that an exception is thrown when fetching a key through a magic * getter which does not exist in the FlowData, and that the correct error * message is returned. */ - public function testMissingKeyMagicGetter() { + public function testMissingKeyMagicGetter() + { $element = $this->createMock(FlowElement::class); - $element->dataKey = "testKey"; + $element->dataKey = 'testKey'; $data = new ElementData($element); - + $flowData = new FlowData(null); $flowData->setElementData($data); - try { - $returnedData = $flowData->otherKey; - $this->fail(); - } - catch (\Exception $e) { - $this->assertEquals( - sprintf(Messages::NO_ELEMENT_DATA, - "otherKey", - "testKey"), - $e->getMessage()); - } + $this->expectExceptionMessage(sprintf(Messages::NO_ELEMENT_DATA, 'otherKey', 'testKey')); + $flowData->otherKey; } - + /** * Check that an exception is thrown when fetching a key using the * getFromElement method which does not exist in the FlowData, and that the * correct error message is returned. */ - public function testMissingKeyFromElement() { + public function testMissingKeyFromElement() + { $element = $this->createMock(FlowElement::class); - $element->dataKey = "testKey"; + $element->dataKey = 'testKey'; $data = new ElementData($element); - + $element2 = $this->createMock(FlowElement::class); - $element2->dataKey = "otherKey"; - + $element2->dataKey = 'otherKey'; + $flowData = new FlowData(null); $flowData->setElementData($data); - try { - $returnedData = $flowData->getFromElement($element2); - $this->fail(); - } - catch (\Exception $e) { - $this->assertEquals( - sprintf(Messages::NO_ELEMENT_DATA, - "otherKey", - "testKey"), - $e->getMessage()); - } + $this->expectExceptionMessage(sprintf(Messages::NO_ELEMENT_DATA, 'otherKey', 'testKey')); + $flowData->getFromElement($element2); } } diff --git a/tests/JavaScriptBundlerTests.php b/tests/JavaScriptBundlerTests.php index 7f59e0f..548a87c 100644 --- a/tests/JavaScriptBundlerTests.php +++ b/tests/JavaScriptBundlerTests.php @@ -23,60 +23,60 @@ namespace fiftyone\pipeline\core\tests; +use fiftyone\pipeline\core\AspectPropertyValue; +use fiftyone\pipeline\core\ElementDataDictionary; use fiftyone\pipeline\core\FlowElement; use fiftyone\pipeline\core\PipelineBuilder; -use fiftyone\pipeline\core\ElementDataDictionary; -use fiftyone\pipeline\core\AspectPropertyValue; use PHPUnit\Framework\TestCase; class TestEngine extends FlowElement { - public $dataKey = "test"; - - public $properties = array( - "javascript" => array( - "type" => "javascript" - ), - "apvGood" => array( - "type" => "string" - ), - "apvBad" => array( - "type" => "string" - ), - "normal" => array( - "type" => "boolean" - ) - ); - - public function processInternal($FlowData) + public $dataKey = 'test'; + + public $properties = [ + 'javascript' => [ + 'type' => 'javascript' + ], + 'apvGood' => [ + 'type' => 'string' + ], + 'apvBad' => [ + 'type' => 'string' + ], + 'normal' => [ + 'type' => 'boolean' + ] + ]; + + public function processInternal($flowData) { $contents = []; - $contents["javascript"] = "console.log('hello world')"; - $contents["normal"] = true; + $contents['javascript'] = "console.log('hello world')"; + $contents['normal'] = true; - $contents["apvGood"] = new AspectPropertyValue(null, "Value"); - $contents["apvBad"] = new AspectPropertyValue("No value"); + $contents['apvGood'] = new AspectPropertyValue(null, 'Value'); + $contents['apvBad'] = new AspectPropertyValue('No value'); $data = new ElementDataDictionary($this, $contents); - $FlowData->setElementData($data); + $flowData->setElementData($data); } } class TestPipeline { - public $Pipeline; + public $pipeline; - public function __construct($minify = NULL) + public function __construct($minify = null) { if (is_null($minify)) { - $pipelineSettings = array(); + $pipelineSettings = []; } else { - $jsSettings = array('minify' => $minify); - $pipelineSettings = array('javascriptBuilderSettings' => $jsSettings); + $jsSettings = ['minify' => $minify]; + $pipelineSettings = ['javascriptBuilderSettings' => $jsSettings]; } - $this->Pipeline = (new PipelineBuilder($pipelineSettings)) + $this->pipeline = (new PipelineBuilder($pipelineSettings)) ->add(new TestEngine()) ->build(); } @@ -84,25 +84,23 @@ public function __construct($minify = NULL) class DelayedExecutionEngine1 extends FlowElement { - - public $dataKey = "delayedexecutiontest1"; + public $dataKey = 'delayedexecutiontest1'; public $properties = [ - "one" => [ - "delayexecution" => false, - "type" => 'javascript' + 'one' => [ + 'delayexecution' => false, + 'type' => 'javascript' ], - "two" => [ - "evidenceproperties" => ['jsontestengine'] + 'two' => [ + 'evidenceproperties' => ['jsontestengine'] ] ]; public function processInternal($flowData) { - $contents = [ - "one" => 1, - "two" => 2 + 'one' => 1, + 'two' => 2 ]; $data = new ElementDataDictionary($this, $contents); @@ -113,25 +111,23 @@ public function processInternal($flowData) class DelayedExecutionEngine2 extends FlowElement { - - public $dataKey = "delayedexecutiontest2"; + public $dataKey = 'delayedexecutiontest2'; public $properties = [ - "one" => [ - "delayexecution" => true, - "type" => 'javascript' + 'one' => [ + 'delayexecution' => true, + 'type' => 'javascript' ], - "two" => [ - "evidenceproperties" => ['one'] + 'two' => [ + 'evidenceproperties' => ['one'] ] ]; public function processInternal($flowData) { - $contents = [ - "one" => 1, - "two" => 2 + 'one' => 1, + 'two' => 2 ]; $data = new ElementDataDictionary($this, $contents); @@ -142,28 +138,26 @@ public function processInternal($flowData) class DelayedExecutionEngine3 extends FlowElement { - - public $dataKey = "delayedexecutiontest3"; + public $dataKey = 'delayedexecutiontest3'; public $properties = [ - "one" => [ - "evidenceproperties" => ['two', 'three'] + 'one' => [ + 'evidenceproperties' => ['two', 'three'] ], - "two" => [ - "delayexecution" => true + 'two' => [ + 'delayexecution' => true ], - "three" => [ - "delayexecution" => false + 'three' => [ + 'delayexecution' => false ] ]; public function processInternal($flowData) { - $contents = [ - "one" => 1, - "two" => 2, - "three" => 3 + 'one' => 1, + 'two' => 2, + 'three' => 3 ]; $data = new ElementDataDictionary($this, $contents); @@ -176,137 +170,116 @@ class JavaScriptBundlerTests extends TestCase { public function testJSONBundler() { - $Pipeline = (new TestPipeline(false))->Pipeline; - - $FlowData = $Pipeline->createFlowData(); - - $FlowData->process(); + $flowData = (new TestPipeline(false))->pipeline->createFlowData(); + $flowData->process(); - $expected = array( - 'javascriptProperties' => - array( + $expected = [ + 'javascriptProperties' => [ 0 => 'test.javascript', - ), - 'test' => - array( + ], + 'test' => [ 'javascript' => 'console.log(\'hello world\')', 'apvgood' => 'Value', 'apvbad' => null, 'apvbadnullreason' => 'No value', 'normal' => true, - ) - ); + ] + ]; - $this->assertEquals($FlowData->jsonbundler->json, $expected); + $this->assertSame($expected, $flowData->jsonbundler->json); } - public function testJavaScriptBuilder_Minify() + public function testJavaScriptBuilderMinify() { // Generate minified javascript - $Pipeline = (new TestPipeline(true))->Pipeline; - $FlowData = $Pipeline->createFlowData(); - $FlowData->process(); - $minified = $FlowData->javascriptbuilder->javascript; + $flowData = (new TestPipeline(true))->pipeline->createFlowData(); + $flowData->process(); + $minified = $flowData->javascriptbuilder->javascript; // Generate non-minified javascript - $Pipeline = (new TestPipeline(false))->Pipeline; - $FlowData = $Pipeline->createFlowData(); - $FlowData->process(); - $nonminified = $FlowData->javascriptbuilder->javascript; + $flowData = (new TestPipeline(false))->pipeline->createFlowData(); + $flowData->process(); + $nonminified = $flowData->javascriptbuilder->javascript; // Generate javascript with default settings - $Pipeline = (new TestPipeline())->Pipeline; - $FlowData = $Pipeline->createFlowData(); - $FlowData->process(); - $default = $FlowData->javascriptbuilder->javascript; + $flowData = (new TestPipeline())->pipeline->createFlowData(); + $flowData->process(); + $default = $flowData->javascriptbuilder->javascript; - // We don't want to get too specific here. Just check that + // We don't want to get too specific here. Just check that // the minified version is smaller to confirm that it's // done something. $this->assertGreaterThan(strlen($minified), strlen($nonminified)); // Check that default is to minify the output - $this->assertEquals(strlen($default), strlen($minified)); + $this->assertSame(strlen($default), strlen($minified)); } public function testSequence() { - $Pipeline = (new TestPipeline(false))->Pipeline; - - $FlowData = $Pipeline->createFlowData(); - - $FlowData->evidence->set("query.session-id", "test"); - $FlowData->evidence->set("query.sequence", 10); - - $FlowData->process(); + $flowData = (new TestPipeline(false))->pipeline->createFlowData(); + $flowData->evidence->set('query.session-id', 'test'); + $flowData->evidence->set('query.sequence', 10); - $this->assertEquals($FlowData->evidence->get("query.sequence"), 11); - - $this->assertEquals(count($FlowData->jsonbundler->json["javascriptProperties"]), 0); + $flowData->process(); + + $this->assertSame(11, $flowData->evidence->get('query.sequence')); + $this->assertCount(0, $flowData->jsonbundler->json['javascriptProperties']); } - public function test_jsonbundler_when_delayed_execution_false() + public function testJsonbundlerWhenDelayedExecutionFalse() { - - $pipeline = new PipelineBuilder(); - - $pipeline->add(new DelayedExecutionEngine1()); - $pipeline = $pipeline->build(); + $pipeline = (new PipelineBuilder()) + ->add(new DelayedExecutionEngine1()) + ->build(); $flowData = $pipeline->createFlowData(); - $flowData->process(); - $expected = json_encode(["one" => 1, "two" => 2]); - $actual = json_encode($flowData->jsonbundler->json["delayedexecutiontest1"]); - $this->assertEquals($actual, $expected); + $expected = json_encode(['one' => 1, 'two' => 2]); + $actual = json_encode($flowData->jsonbundler->json['delayedexecutiontest1']); + $this->assertJsonStringEqualsJsonString($expected, $actual); } - public function test_jsonbundler_when_delayed_execution_true() + public function testJsonbundlerWhenDelayedExecutionTrue() { - - $pipeline = new PipelineBuilder(); - - $pipeline->add(new DelayedExecutionEngine2()); - $pipeline = $pipeline->build(); + $pipeline = (new PipelineBuilder()) + ->add(new DelayedExecutionEngine2()) + ->build(); $flowData = $pipeline->createFlowData(); $flowData->process(); $expected = json_encode([ - "onedelayexecution" => true, - "one" => 1, - "twoevidenceproperties" => ['delayedexecutiontest2.one'], - "two" => 2 + 'onedelayexecution' => true, + 'one' => 1, + 'twoevidenceproperties' => ['delayedexecutiontest2.one'], + 'two' => 2 ]); - - $actual = json_encode($flowData->jsonbundler->json["delayedexecutiontest2"]); - $this->assertEquals($actual, $expected); + $actual = json_encode($flowData->jsonbundler->json['delayedexecutiontest2']); + + $this->assertJsonStringEqualsJsonString($expected, $actual); } - - public function test_jsonbundler_when_delayed_execution_multiple() + public function testJsonbundlerWhenDelayedExecutionMultiple() { - - $pipeline = new PipelineBuilder(); - - $pipeline->add(new DelayedExecutionEngine3()); - $pipeline = $pipeline->build(); - + $pipeline = (new PipelineBuilder()) + ->add(new DelayedExecutionEngine3()) + ->build(); + $flowData = $pipeline->createFlowData(); - $flowData->process(); $expected = json_encode([ - "oneevidenceproperties" => ['delayedexecutiontest3.two'], - "one" => 1, - "twodelayexecution" => true, - "two" => 2, - "three" => 3 + 'oneevidenceproperties' => ['delayedexecutiontest3.two'], + 'one' => 1, + 'twodelayexecution' => true, + 'two' => 2, + 'three' => 3 ]); - - $actual = json_encode($flowData->jsonbundler->json["delayedexecutiontest3"]); - $this->assertEquals($actual, $expected); + $actual = json_encode($flowData->jsonbundler->json['delayedexecutiontest3']); + + $this->assertJsonStringEqualsJsonString($expected, $actual); } } diff --git a/tests/SetHeaderTests.php b/tests/SetHeaderTests.php index b026f86..4d78e24 100644 --- a/tests/SetHeaderTests.php +++ b/tests/SetHeaderTests.php @@ -23,100 +23,159 @@ namespace fiftyone\pipeline\core\tests; +use fiftyone\pipeline\core\AspectPropertyValue; use fiftyone\pipeline\core\ElementDataDictionary; -use fiftyone\pipeline\core\SetHeaderElement; use fiftyone\pipeline\core\Messages; +use fiftyone\pipeline\core\SetHeaderElement; use fiftyone\pipeline\core\tests\classes\Constants; use fiftyone\pipeline\core\tests\classes\TestPipeline; use fiftyone\pipeline\core\Utils; -use fiftyone\pipeline\core\AspectPropertyValue; use PHPUnit\Framework\TestCase; class SetHeaderTests extends TestCase -{ +{ // Data Provider for testGetResponseHeaderValue - public static function provider_testGetResponseHeaderValue() + public static function provider_testGetResponseHeaderValue() { - return array( - array(array("device" => new ElementDataDictionary(null, array( "setheaderbrowseraccept-ch" => new AspectPropertyValue(null, Constants::UNKNOWN), "setheaderplatformaccept-ch" => new AspectPropertyValue(null, Constants::UNKNOWN), "setheaderhardwareaccept-ch" => new AspectPropertyValue(null, Constants::UNKNOWN)))), ""), - array(array("device" => new ElementDataDictionary(null, array( "setheaderbrowseraccept-ch" => new AspectPropertyValue(null, Constants::ACCEPTCH_BROWSER_VALUE)))), "SEC-CH-UA,SEC-CH-UA-Full-Version"), - array(array("device" => new ElementDataDictionary(null, array( "setheaderplatformaccept-ch" => new AspectPropertyValue(null, Constants::ACCEPTCH_PLATFORM_VALUE), "setheaderhardwareaccept-ch" => new AspectPropertyValue(null, Constants::ACCEPTCH_HARDWARE_VALUE)))), "SEC-CH-UA-Model,SEC-CH-UA-Mobile,SEC-CH-UA-Arch,SEC-CH-UA-Platform,SEC-CH-UA-Platform-Version"), - array(array("device" => new ElementDataDictionary(null, array( "setheaderbrowseraccept-ch" => new AspectPropertyValue(null, Constants::ACCEPTCH_BROWSER_VALUE), "setheaderplatformaccept-ch" => new AspectPropertyValue(null, Constants::ACCEPTCH_PLATFORM_VALUE), "setheaderhardwareaccept-ch" => new AspectPropertyValue(null, Constants::ACCEPTCH_HARDWARE_VALUE)))), "SEC-CH-UA,SEC-CH-UA-Full-Version,SEC-CH-UA-Model,SEC-CH-UA-Mobile,SEC-CH-UA-Arch,SEC-CH-UA-Platform,SEC-CH-UA-Platform-Version") - ); + return [ + [ + [ + 'device' => new ElementDataDictionary(null, [ + 'setheaderbrowseraccept-ch' => new AspectPropertyValue(null, Constants::UNKNOWN), + 'setheaderplatformaccept-ch' => new AspectPropertyValue(null, Constants::UNKNOWN), + 'setheaderhardwareaccept-ch' => new AspectPropertyValue(null, Constants::UNKNOWN) + ]) + ], + '' + ], + [ + [ + 'device' => new ElementDataDictionary(null, [ + 'setheaderbrowseraccept-ch' => new AspectPropertyValue(null, Constants::ACCEPTCH_BROWSER_VALUE) + ]) + ], + 'SEC-CH-UA,SEC-CH-UA-Full-Version' + ], + [ + [ + 'device' => new ElementDataDictionary(null, [ + 'setheaderplatformaccept-ch' => new AspectPropertyValue(null, Constants::ACCEPTCH_PLATFORM_VALUE), + 'setheaderhardwareaccept-ch' => new AspectPropertyValue(null, Constants::ACCEPTCH_HARDWARE_VALUE) + ]) + ], + 'SEC-CH-UA-Model,SEC-CH-UA-Mobile,SEC-CH-UA-Arch,SEC-CH-UA-Platform,SEC-CH-UA-Platform-Version' + ], + [ + [ + 'device' => new ElementDataDictionary(null, [ + 'setheaderbrowseraccept-ch' => new AspectPropertyValue(null, Constants::ACCEPTCH_BROWSER_VALUE), + 'setheaderplatformaccept-ch' => new AspectPropertyValue(null, Constants::ACCEPTCH_PLATFORM_VALUE), + 'setheaderhardwareaccept-ch' => new AspectPropertyValue(null, Constants::ACCEPTCH_HARDWARE_VALUE) + ]) + ], + 'SEC-CH-UA,SEC-CH-UA-Full-Version,SEC-CH-UA-Model,SEC-CH-UA-Mobile,SEC-CH-UA-Arch,SEC-CH-UA-Platform,SEC-CH-UA-Platform-Version' + ] + ]; } - // Test response header value to be set for UACH /** + * Test response header value to be set for UACH. + * * @dataProvider provider_testGetResponseHeaderValue + * @param mixed $device + * @param mixed $expectedValue */ public function testGetResponseHeaderValue($device, $expectedValue) { - $setHeaderPropertiesDict = array('device' => array('SetHeaderBrowserAccept-CH', 'SetHeaderHardwareAccept-CH', 'SetHeaderPlatformAccept-CH')); + $setHeaderPropertiesDict = [ + 'device' => [ + 'SetHeaderBrowserAccept-CH', + 'SetHeaderHardwareAccept-CH', + 'SetHeaderPlatformAccept-CH' + ] + ]; $testPipeline = new TestPipeline(); $setHeaderElement = new SetHeaderElement(); - $testPipeline->flowData->data = $device; - $flowData = $testPipeline->flowData; + $testPipeline->flowData->data = $device; + $flowData = $testPipeline->flowData; $actualValue = $setHeaderElement->getResponseHeaderValue($flowData, $setHeaderPropertiesDict); - $this->assertEquals($expectedValue, $actualValue["Accept-CH"]); - + $this->assertSame($expectedValue, $actualValue['Accept-CH']); } - - // Test response header not being sent for empty value - public function testSetResponseHeader_emptyHeader() + + /** + * Test response header not being sent for empty value + */ + public function testSetResponseHeaderEmptyHeader() { - $data = array("set-headers" => (object) array("responseheaderdictionary" => array("Accept-CH"=> ""))); - $setHeaderPropertiesDict = array('device' => array('SetHeaderBrowserAccept-CH', 'SetHeaderHardwareAccept-CH', 'SetHeaderPlatformAccept-CH')); + $this->markTestSkipped('Nothing being tested because Utils::setResponseHeader() returns void'); + + $data = [ + 'set-headers' => (object) [ + 'responseheaderdictionary' => [ + 'Accept-CH' => '' + ] + ] + ]; + $setHeaderPropertiesDict = [ + 'device' => [ + 'SetHeaderBrowserAccept-CH', + 'SetHeaderHardwareAccept-CH', + 'SetHeaderPlatformAccept-CH' + ] + ]; $testPipeline = new TestPipeline(); $testPipeline->flowData->data = $data; $flowData = $testPipeline->flowData; - $actualValue = Utils::setResponseHeader($flowData); - $this->assertEquals(False, isset($actualValue["Accept-CH"])); + $actualValue = Utils::setResponseHeader($flowData); + $this->assertEquals(false, isset($actualValue['Accept-CH'])); } // Data Provider for testGetResponseHeaderValue - public static function provider_testGetResponseHeaderName_Valid() + public static function provider_testGetResponseHeaderName_Valid() { - return array( - array("SetHeaderBrowserAccept-CH", "Accept-CH"), - array("SetHeaderBrowserCritical-CH", "Critical-CH"), - array("SetHeaderUnknownAccept-CH", "Accept-CH") - ); + return [ + ['SetHeaderBrowserAccept-CH', 'Accept-CH'], + ['SetHeaderBrowserCritical-CH', 'Critical-CH'], + ['SetHeaderUnknownAccept-CH', 'Accept-CH'] + ]; } - // Test get response header function for valid formats. /** + * Test get response header function for valid formats. + * * @dataProvider provider_testGetResponseHeaderName_Valid + * @param mixed $data + * @param mixed $expectedValue */ - public function testGetResponseHeaderName_Valid($data, $expectedValue) + public function testGetResponseHeaderNameValid($data, $expectedValue) { - $setHeaderElement = new SetHeaderElement(); - $actualValue = $setHeaderElement->getResponseHeaderName($data); - $this->assertEquals($expectedValue, $actualValue); + $setHeaderElement = new SetHeaderElement(); + $actualValue = $setHeaderElement->getResponseHeaderName($data); + $this->assertSame($expectedValue, $actualValue); } // Data Provider for testGetResponseHeaderValue - public static function provider_testGetResponseHeaderName_InValid() + public static function provider_testGetResponseHeaderName_InValid() { - return array( - array("TestBrowserAccept-CH", Messages::PROPERTY_NOT_SET_HEADER), - array("SetHeaderbrowserAccept-ch", Messages::WRONG_PROPERTY_FORMAT), - array("SetHeaderBrowseraccept-ch", Messages::WRONG_PROPERTY_FORMAT) - ); + return [ + ['TestBrowserAccept-CH', Messages::PROPERTY_NOT_SET_HEADER], + ['SetHeaderbrowserAccept-ch', Messages::WRONG_PROPERTY_FORMAT], + ['SetHeaderBrowseraccept-ch', Messages::WRONG_PROPERTY_FORMAT] + ]; } - // Test get response header function for valid formats. /** + * Test get response header function for valid formats. + * * @dataProvider provider_testGetResponseHeaderName_InValid + * @param mixed $data + * @param mixed $expectedValue */ - public function testGetResponseHeaderName_InValid($data, $expectedValue) + public function testGetResponseHeaderNameInValid($data, $expectedValue) { $setHeaderElement = new SetHeaderElement(); - - try{ - $setHeaderElement->getResponseHeaderName($data); - } catch(\Exception $e){ - $this->assertEquals(sprintf($expectedValue, $data), $e->getMessage()); - } - + + $this->expectExceptionMessage(sprintf($expectedValue, $data)); + $setHeaderElement->getResponseHeaderName($data); } } diff --git a/tests/classes/Constants.php b/tests/classes/Constants.php index 9159dae..47e6673 100644 --- a/tests/classes/Constants.php +++ b/tests/classes/Constants.php @@ -1,35 +1,36 @@ - [ + 'type' => 'int' + ] + ]; + public function processInternal($flowData) { - $data = new ElementDataDictionary($this, array("integer" => 5)); + $data = new ElementDataDictionary($this, ['integer' => 5]); $flowData->setElementData($data); } - public $properties = array( - "integer" => array( - "type" => "int" - ) - ); - public function getEvidenceKeyFilter() { - return new BasicListEvidenceKeyFilter(["header.user-agent"]); + return new BasicListEvidenceKeyFilter(['header.user-agent']); } } diff --git a/tests/classes/ExampleFlowElement2.php b/tests/classes/ExampleFlowElement2.php index f125f4c..a6b2ffc 100644 --- a/tests/classes/ExampleFlowElement2.php +++ b/tests/classes/ExampleFlowElement2.php @@ -21,33 +21,31 @@ * such notice(s) shall fulfill the requirements of that article. * ********************************************************************* */ - - namespace fiftyone\pipeline\core\tests\classes; -use fiftyone\pipeline\core\FlowElement; -use fiftyone\pipeline\core\ElementDataDictionary; use fiftyone\pipeline\core\BasicListEvidenceKeyFilter; +use fiftyone\pipeline\core\ElementDataDictionary; +use fiftyone\pipeline\core\FlowElement; class ExampleFlowElement2 extends FlowElement { - public $dataKey = "example2"; + public $dataKey = 'example2'; + + public $properties = [ + 'integer2' => [ + 'type' => 'int' + ] + ]; public function processInternal($flowData) { - $data = new ElementDataDictionary($this, array("integer" => 7)); + $data = new ElementDataDictionary($this, ['integer' => 7]); $flowData->setElementData($data); } - public $properties = array( - "integer2" => array( - "type" => "int" - ) - ); - public function getEvidenceKeyFilter() { - return new BasicListEvidenceKeyFilter(["header.user-agent"]); + return new BasicListEvidenceKeyFilter(['header.user-agent']); } } diff --git a/tests/classes/MemoryLogger.php b/tests/classes/MemoryLogger.php index 647a62a..29865ea 100644 --- a/tests/classes/MemoryLogger.php +++ b/tests/classes/MemoryLogger.php @@ -1,40 +1,38 @@ -log[] = $log; - } - } -} \ No newline at end of file +log[] = $log; + } + } +} diff --git a/tests/classes/StopFlowData.php b/tests/classes/StopFlowData.php index 69c9701..f5f83b8 100644 --- a/tests/classes/StopFlowData.php +++ b/tests/classes/StopFlowData.php @@ -21,16 +21,14 @@ * such notice(s) shall fulfill the requirements of that article. * ********************************************************************* */ - - namespace fiftyone\pipeline\core\tests\classes; -use fiftyone\pipeline\core\FlowElement; use fiftyone\pipeline\core\BasicListEvidenceKeyFilter; +use fiftyone\pipeline\core\FlowElement; class StopFlowData extends FlowElement { - public $dataKey = "stop"; + public $dataKey = 'stop'; public function processInternal($flowData) { @@ -39,7 +37,6 @@ public function processInternal($flowData) public function getEvidenceKeyFilter() { - return new BasicListEvidenceKeyFilter(["header.user-agent"]); + return new BasicListEvidenceKeyFilter(['header.user-agent']); } } - diff --git a/tests/classes/TestPipeline.php b/tests/classes/TestPipeline.php index 4200d97..a8adbfa 100644 --- a/tests/classes/TestPipeline.php +++ b/tests/classes/TestPipeline.php @@ -21,8 +21,6 @@ * such notice(s) shall fulfill the requirements of that article. * ********************************************************************* */ - - namespace fiftyone\pipeline\core\tests\classes; use fiftyone\pipeline\core\PipelineBuilder; @@ -31,16 +29,13 @@ class TestPipeline { public $pipeline; - public $flowElement1; - public $flowData; - public $logger; public function __construct($suppressException = true) { - $this->logger = new MemoryLogger("info"); + $this->logger = new MemoryLogger('info'); $this->flowElement1 = new ExampleFlowElement1(); $this->pipeline = (new PipelineBuilder()) ->add($this->flowElement1) @@ -49,10 +44,11 @@ public function __construct($suppressException = true) ->add(new ExampleFlowElement2()) ->addLogger($this->logger) ->build(); + $this->pipeline->log('info', 'test'); $this->pipeline->suppressProcessExceptions = $suppressException; $this->flowData = $this->pipeline->createFlowData(); - $this->flowData->evidence->set("header.user-agent", "test"); - $this->flowData->evidence->set("some.other-evidence", "test"); + $this->flowData->evidence->set('header.user-agent', 'test'); + $this->flowData->evidence->set('some.other-evidence', 'test'); $this->flowData->process(); } } From 7aab800aa802b0231779beacda90f086b900f971 Mon Sep 17 00:00:00 2001 From: lukareihl Date: Mon, 27 Nov 2023 08:39:44 +0100 Subject: [PATCH 4/4] Add javascript-templates repo as part of this composer package --- composer.json | 12 ++---------- javascript-templates | 1 + src/JavascriptBuilderElement.php | 20 ++++---------------- 3 files changed, 7 insertions(+), 26 deletions(-) create mode 160000 javascript-templates diff --git a/composer.json b/composer.json index 3185b6a..c113acb 100644 --- a/composer.json +++ b/composer.json @@ -27,8 +27,7 @@ "ext-ctype": "*", "ext-json": "*", "mustache/mustache": "^2.13", - "tedivm/jshrink": "~1.0", - "51degrees/fiftyone.pipeline.javascript-templates": "1.*" + "tedivm/jshrink": "~1.0" }, "require-dev": { "kint-php/kint": "^3.3", @@ -43,12 +42,5 @@ "psr-4": { "fiftyone\\pipeline\\core\\tests\\": "tests/" } - }, - "repositories": [ - { - "type": "vcs", - "url": "https://github.com/51Degrees/javascript-templates", - "no-api": true - } - ] + } } diff --git a/javascript-templates b/javascript-templates new file mode 160000 index 0000000..2a7d986 --- /dev/null +++ b/javascript-templates @@ -0,0 +1 @@ +Subproject commit 2a7d986ae5adb1e19353e815d7796a374fceff5f diff --git a/src/JavascriptBuilderElement.php b/src/JavascriptBuilderElement.php index 0bf6452..fb9f840 100644 --- a/src/JavascriptBuilderElement.php +++ b/src/JavascriptBuilderElement.php @@ -177,7 +177,10 @@ public function processInternal($flowData) $vars["_parameters"] = json_encode($jsParams); - $output = $m->render(file_get_contents($this->getTemplatePath()), $vars); + $output = $m->render( + file_get_contents(__DIR__ . '/../javascript-templates/JavaScriptResource.mustache'), + $vars + ); if($this->minify) { // Minify the output @@ -190,19 +193,4 @@ public function processInternal($flowData) return; } - - private function getTemplatePath() - { - $templatePath = '51degrees/fiftyone.pipeline.javascript-templates/JavaScriptResource.mustache'; - $prefixes = ['/../../../', '/../vendor/']; - - foreach ($prefixes as $prefix) { - $path = __DIR__ . $prefix . $templatePath; - if (file_exists($path)) { - return $path; - } - } - - throw new \Exception('Could not find JavaScriptResource template'); - } }