/** * Fill the product filter with a array. * * @author David Pauli <*****@*****.**> * @since 0.0.1 * @since 0.1.0 Use a default Locale and Currency. * @api * @param String[] $productFilterParameter The values of a product filter. */ public function setProductFilter($productFilterParameter) { if (!InputValidator::isArray($productFilterParameter) || InputValidator::isEmptyArray($productFilterParameter)) { return; } foreach ($productFilterParameter as $key => $parameter) { if ($key == "page") { $this->setPage($parameter); } else { if ($key == "resultsPerPage") { $this->setResultsPerPage($parameter); } else { if ($key == "direction") { $this->setDirection($parameter); } else { if ($key == "sort") { $this->setSort($parameter); } else { if ($key == "q") { $this->setQ($parameter); } else { if ($key == "categoryID") { $this->setCategoryID($parameter); } else { Logger::warning("Unknown attribute <i>" . $key . "</i> in product filter attribute."); } } } } } } } }
/** * @group utility */ function testIsArray() { $this->assertFalse(InputValidator::isArray(42)); $this->assertFalse(InputValidator::isArray("String")); $this->assertTrue(InputValidator::isArray(array())); $this->assertTrue(InputValidator::isArray(array(1, 2, 3))); }
/** * This is the constructor of the Quantity object. * * @api * @author David Pauli <*****@*****.**> * @param mixed[] $quantityParameter The quantity parameter. * @since 0.2.0 */ public function __construct($quantityParameter) { if (InputValidator::isArray($quantityParameter)) { if (!InputValidator::isEmptyArrayKey($quantityParameter, "amount")) { $this->quantityAmount = $quantityParameter['amount']; } if (!InputValidator::isEmptyArrayKey($quantityParameter, "unit")) { $this->quantityUnit = $quantityParameter['unit']; } } }
/** * Call this function to create a JSON string from a array. * * @author David Pauli <*****@*****.**> * @since 0.0.0 * @param mixed[] $array The array to make a JSON. * @return String The JSON string. */ public static function createJSON($array) { if (!InputValidator::isArray($array)) { return null; } $result = json_encode($array); if (!InputValidator::isJSON($result)) { Logger::warning("There is an error with creating a JSON with the following array: <strong>" . json_last_error() . ": " . json_last_error_msg() . "</strong><br/>\n" . "<pre>" . $array . "</pre>"); return null; } return $result; }
/** * Call this function with the JSON in parameter. * * @param String $JSON The JSON string to parse. * @return array The array of the JSON element or null if there is an error. */ public static function parseJSON($JSON) { if (!InputValidator::isJSON($JSON)) { return array(); } $result = json_decode($JSON, true); if (!InputValidator::isArray($result)) { Logger::warning("There is an error with parsing the follwing JSON: <strong>" . json_last_error() . ": " . json_last_error_msg() . "</strong><br/>\n" . "<pre>" . $JSON . "</pre>"); return array(); } return $result; }
/** * This is the constructor. * * @author David Pauli <*****@*****.**> * @param String[] $addressParameter The array with information of the adddress. * @since 0.1.3 */ public function __construct($addressParameter) { self::errorReset(); // if parameter is no array if (!InputValidator::isArray($addressParameter)) { self::errorSet("A-1"); Logger::error("ep6\\Address\nThe address parameter " . $addressParameter . " is no array."); return; } if (!InputValidator::isEmptyArrayKey($addressParameter, "birthday")) { $this->birthday = $addressParameter["birthday"]; } if (!InputValidator::isEmptyArrayKey($addressParameter, "city")) { $this->city = $addressParameter["city"]; } if (!InputValidator::isEmptyArrayKey($addressParameter, "company")) { $this->company = $addressParameter["company"]; } if (!InputValidator::isEmptyArrayKey($addressParameter, "country")) { $this->country = $addressParameter["country"]; } if (!InputValidator::isEmptyArrayKey($addressParameter, "emailAddress")) { $this->emailAddress = $addressParameter["emailAddress"]; } if (!InputValidator::isEmptyArrayKey($addressParameter, "firstName")) { $this->firstName = $addressParameter["firstName"]; } if (!InputValidator::isEmptyArrayKey($addressParameter, "lastName")) { $this->lastName = $addressParameter["lastName"]; } if (!InputValidator::isEmptyArrayKey($addressParameter, "salutation")) { $this->salutation = $addressParameter["salutation"]; } if (!InputValidator::isEmptyArrayKey($addressParameter, "state")) { $this->state = $addressParameter["state"]; } if (!InputValidator::isEmptyArrayKey($addressParameter, "street")) { $this->street = $addressParameter["street"]; } if (!InputValidator::isEmptyArrayKey($addressParameter, "streetDetails")) { $this->streetDetails = $addressParameter["streetDetails"]; } if (!InputValidator::isEmptyArrayKey($addressParameter, "title")) { $this->title = $addressParameter["title"]; } if (!InputValidator::isEmptyArrayKey($addressParameter, "vatId")) { $this->VATID = $addressParameter["vatId"]; } if (!InputValidator::isEmptyArrayKey($addressParameter, "zipCode")) { $this->zipCode = $addressParameter["zipCode"]; } }
/** * This is the constructor of the price with quantity object. * * @api * @author David Pauli <*****@*****.**> * @since 0.1.0 * @param mixed[] $priceParameter The price parameter. * @param mixed[] $quantityParameter The quantity parameter. * @param String $locale The localization parameter. */ public function __construct($priceParameter, $quantityParameter, $locale) { parent::__construct($priceParameter); if (InputValidator::isArray($quantityParameter)) { if (!InputValidator::isEmptyArrayKey($quantityParameter, "amount")) { $this->quantityAmount = $quantityParameter['amount']; } if (InputValidator::isLocale($locale)) { if (!InputValidator::isEmptyArrayKey($quantityParameter, "unit")) { $this->quantityUnit[$locale] = $quantityParameter['unit']; } } } }
/** * This is the constructor of the price object. * * @api * @author David Pauli <*****@*****.**> * @since 0.0.0 * @since 0.1.0 Add functionality to construct. * @param mixed[] $priceParamter The price parameter. */ public function __construct($priceParameter) { if (InputValidator::isArray($priceParameter)) { if (!InputValidator::isEmptyArrayKey($priceParameter, "amount")) { $this->amount = $priceParameter['amount']; } if (!InputValidator::isEmptyArrayKey($priceParameter, "taxType")) { $this->taxType = $priceParameter['taxType']; } if (!InputValidator::isEmptyArrayKey($priceParameter, "currency")) { $this->currency = $priceParameter['currency']; } } }
/** * This is the constructor. * * @author David Pauli <*****@*****.**> * @param String[] $paymentMethodParameter The payment method in an array to construct. * @since 0.1.3 */ public function __construct($paymentMethodParameter) { // if parameter is no string if (!InputValidator::isArray($paymentMethodParameter)) { $this->errorSet("SM-1"); Logger::error("ep6\\PaymentMethod\nThe parameter payment method paramater " . $paymentMethodParameter . " is no array."); return; } if (!InputValidator::isEmptyArrayKey($paymentMethodParameter, "id")) { $this->paymentMethodId = $paymentMethodParameter["id"]; } if (!InputValidator::isEmptyArrayKey($paymentMethodParameter, "name")) { $this->name = $paymentMethodParameter["name"]; } }
/** * This is the constructor. * * @author David Pauli <*****@*****.**> * @param String[] $shippingMethodParameter The shipping method in an array to construct. * @since 0.1.3 */ public function __construct($shippingMethodParameter) { self::errorReset(); // if parameter is no string if (!InputValidator::isArray($shippingMethodParameter)) { $this->errorSet("SM-1"); Logger::error("ep6\\ShippingMethod\nThe shipping method parameter " . $shippingMethodParameter . " is no array."); return; } if (!InputValidator::isEmptyArrayKey($shippingMethodParameter, "id")) { $this->shippingMethodId = $shippingMethodParameter["id"]; } if (!InputValidator::isEmptyArrayKey($shippingMethodParameter, "name")) { $this->name = $shippingMethodParameter["name"]; } }
/** * Call this function with the JSON in parameter. * * @author David Pauli <*****@*****.**> * @param String $JSON The JSON string to parse. * @return mixed[] The array of the JSON element or null if there is an error. * @since 0.0.0 * @since 0.1.2 Better the warnings. * @since 0.1.2 Add error reporting. */ public static function parseJSON($JSON) { self::errorReset(); if (!InputValidator::isJSON($JSON)) { Logger::warning("ep6\\JSONHandler\nJSON string (" . $JSON . ") is not valid."); self::errorSet("JSONH-1"); return array(); } $result = json_decode($JSON, true); if (!InputValidator::isArray($result)) { Logger::warning("ep6\\JSONHandler\nThere is an error with parsing the follwing JSON (" . $JSON . "): " . json_last_error() . ": " . json_last_error_msg()); self::errorSet("JSONH-2"); return array(); } return $result; }
/** * This is the constructor of the Price object. * * @author David Pauli <*****@*****.**> * @param mixed[] $priceParamter The price parameter to create the Price object. * @since 0.0.0 * @since 0.1.0 Add functionality to construct. * @since 0.1.1 Parse formatted attribute. */ public function __construct($priceParameter) { if (InputValidator::isArray($priceParameter)) { if (!InputValidator::isEmptyArrayKey($priceParameter, "amount")) { $this->amount = $priceParameter['amount']; } if (!InputValidator::isEmptyArrayKey($priceParameter, "taxType") && ($priceParameter['taxType'] == PriceTaxModel::GROSS || $priceParameter['taxType'] == PriceTaxModel::NET)) { $this->taxType = $priceParameter['taxType']; } if (!InputValidator::isEmptyArrayKey($priceParameter, "currency")) { $this->currency = $priceParameter['currency']; } if (!InputValidator::isEmptyArrayKey($priceParameter, "formatted")) { $this->formatted = $priceParameter['formatted']; } } }
/** * This function gets the product attributes. * * @author David Pauli <*****@*****.**> * @since 0.1.0 * @api * @param mixed[] $attribute The attribute in an array. */ public function __construct($attribute) { if (!InputValidator::isEmptyArrayKey($attribute, "key")) { $this->internName = $attribute["key"]; } if (!InputValidator::isEmptyArrayKey($attribute, "displayKey")) { $this->name = $attribute["displayKey"]; } if (!InputValidator::isEmptyArrayKey($attribute, "singleValue")) { $this->oneValue = $attribute["singleValue"]; } if (!InputValidator::isEmptyArrayKey($attribute, "type")) { $this->type = $attribute["type"]; } if (!InputValidator::isEmptyArrayKey($attribute, "type") && !InputValidator::isArray($attribute["values"])) { foreach ($attribute["values"] as $key => $value) { if (!InputValidator::isEmptyArrayKey($value, "value") && !InputValidator::isEmptyArrayKey($value, "displayValue")) { $this->values[$value["value"]] = $value["displayValue"]; } } } }
/** * Parses the REST response data and save it. * * @author David Pauli <*****@*****.**> * @param Array $orderParameter The order in an array. * @since 0.1.3 */ private function parseData($orderParameter) { // if the product comes from the shop API if (InputValidator::isArray($orderParameter) && !InputValidator::isEmptyArrayKey($orderParameter, "orderId")) { $this->orderId = $orderParameter['orderId']; if (!InputValidator::isEmptyArrayKey($orderParameter, "orderNumber")) { $this->orderNumber = $orderParameter['orderNumber']; } if (!InputValidator::isEmptyArrayKey($orderParameter, "creationDate")) { $this->creationDate = new Date($orderParameter['creationDate']); } if (!InputValidator::isEmptyArrayKey($orderParameter, "billingAddress") && InputValidator::isArray($orderParameter["billingAddress"])) { $this->billingAddress = new Address($orderParameter['billingAddress']); } if (!InputValidator::isEmptyArrayKey($orderParameter, "shippingAddress") && InputValidator::isArray($orderParameter["shippingAddress"])) { $this->shippingAddress = new Address($orderParameter['shippingAddress']); } if (!InputValidator::isEmptyArrayKey($orderParameter, "invoicedOn")) { $this->invoiceDate = new Date($orderParameter['invoicedOn']); } if (!InputValidator::isEmptyArrayKey($orderParameter, "deliveredOn")) { $this->deliveryDate = new Date($orderParameter['deliveredOn']); } if (!InputValidator::isEmptyArrayKey($orderParameter, "pendingOn")) { $this->pendingDate = new Date($orderParameter['pendingOn']); } if (!InputValidator::isEmptyArrayKey($orderParameter, "archivedOn")) { $this->archiveDate = new Date($orderParameter['archivedOn']); } if (!InputValidator::isEmptyArrayKey($orderParameter, "dispatchedOn")) { $this->dispatchDate = new Date($orderParameter['dispatchedOn']); } if (!InputValidator::isEmptyArrayKey($orderParameter, "viewedOn")) { $this->viewDate = new Date($orderParameter['viewedOn']); } if (!InputValidator::isEmptyArrayKey($orderParameter, "rejectedOn")) { $this->rejectionDate = new Date($orderParameter["rejectedOn"]); } if (!InputValidator::isEmptyArrayKey($orderParameter, "closedOn")) { $this->closeDate = new Date($orderParameter["closedOn"]); } if (!InputValidator::isEmptyArrayKey($orderParameter, "paidOn")) { $this->payDate = new Date($orderParameter["paidOn"]); } if (!InputValidator::isEmptyArrayKey($orderParameter, "returnedOn")) { $this->returnDate = new Date($orderParameter["returnedOn"]); } if (!InputValidator::isEmptyArrayKey($orderParameter, "currencyId") && !InputValidator::isEmptyArrayKey($orderParameter, "taxModel")) { $priceParameter = array("taxType" => $orderParameter["taxModel"], "currency" => $orderParameter["currencyId"]); if (!InputValidator::isEmptyArrayKey($orderParameter, "grandTotal")) { $priceParameter["amount"] = $orderParameter["grandTotal"]; $this->totalPrice = new Price($priceParameter); } if (!InputValidator::isEmptyArrayKey($orderParameter, "totalBeforeTax")) { $priceParameter["amount"] = $orderParameter["totalBeforeTax"]; $this->totalWithoutTaxPrice = new Price($priceParameter); } if (!InputValidator::isEmptyArrayKey($orderParameter, "totalTax")) { $priceParameter["amount"] = $orderParameter["totalTax"]; $this->taxPrice = new Price($priceParameter); } } if (!InputValidator::isEmptyArrayKey($orderParameter, "customerComment")) { $this->customerComment = $orderParameter["customerComment"]; } if (!InputValidator::isEmptyArrayKey($orderParameter, "internalNote")) { $this->internalNote = $orderParameter["internalNote"]; } if (!InputValidator::isEmptyArrayKey($orderParameter, "shippingData")) { $shippingData = $orderParameter["shippingData"]; if (!InputValidator::isEmptyArrayKey($shippingData, "shippingMethod")) { $this->shippingMethod = new ShippingMethod($shippingData["shippingMethod"]); } if (!InputValidator::isEmptyArrayKey($shippingData, "price")) { $this->shippingPrice = new Price($shippingData["price"]); } } if (!InputValidator::isEmptyArrayKey($orderParameter, "paymentData")) { $paymentData = $orderParameter["paymentData"]; if (!InputValidator::isEmptyArrayKey($paymentData, "paymentMethod")) { $this->paymentMethod = new ShippingMethod($paymentData["paymentMethod"]); } if (!InputValidator::isEmptyArrayKey($paymentData, "price")) { $this->paymentPrice = new Price($paymentData["price"]); } } } // update timestamp when make the next request $timestamp = (int) (microtime(true) * 1000); $this->NEXT_REQUEST_TIMESTAMP = $timestamp + RESTClient::$NEXT_RESPONSE_WAIT_TIME; }
/** * Parses the REST response data and save it. * * @author David Pauli <*****@*****.**> * @param Array $productParameter The product in an array. * @since 0.1.3 */ private function parseData($productParameter) { // if the product comes from the shop API if (InputValidator::isArray($productParameter) && !InputValidator::isEmptyArrayKey($productParameter, "productId")) { $this->productID = $productParameter['productId']; if (!InputValidator::isEmptyArrayKey($productParameter, "forSale")) { $this->forSale = $productParameter['forSale']; } if (!InputValidator::isEmptyArrayKey($productParameter, "specialOffer")) { $this->specialOffer = $productParameter['specialOffer']; } if (!InputValidator::isEmptyArrayKey($productParameter, "name")) { $this->name = $productParameter['name']; } if (!InputValidator::isEmptyArrayKey($productParameter, "shortDescription")) { $this->shortDescription = $productParameter['shortDescription']; } if (!InputValidator::isEmptyArrayKey($productParameter, "description")) { $this->description = $productParameter['description']; } if (!InputValidator::isEmptyArrayKey($productParameter, "availabilityText")) { $this->availabilityText = $productParameter['availabilityText']; } if (!InputValidator::isEmptyArrayKey($productParameter, "productNumber")) { $this->productNumber = $productParameter['productNumber']; } if (!InputValidator::isEmptyArrayKey($productParameter, "energyLabelsString")) { $this->energyLabelsString = $productParameter['energyLabelsString']; } if (!InputValidator::isEmptyArrayKey($productParameter, "manufacturer")) { $this->manufacturer = $productParameter['manufacturer']; } if (!InputValidator::isEmptyArrayKey($productParameter, "upc")) { $this->UPC = $productParameter['upc']; } if (!InputValidator::isEmptyArrayKey($productParameter, "ean")) { $this->EAN = $productParameter['ean']; } if (!InputValidator::isEmptyArrayKey($productParameter, "essentialFeatures")) { $this->essentialFeatures = $productParameter['essentialFeatures']; } if (!InputValidator::isEmptyArrayKey($productParameter, "searchKeywords")) { $this->searchKeywords = $productParameter['searchKeywords']; } if (!InputValidator::isEmptyArrayKey($productParameter, "visibility")) { $this->visibility = $productParameter['visibility']; } if (!InputValidator::isEmptyArrayKey($productParameter, "deliveryPeriod")) { $this->deliveryPeriod = $productParameter['deliveryPeriod']; } if (!InputValidator::isEmptyArrayKey($productParameter, "deliveryWeight")) { $this->deliveryWeight = new Quantity($productParameter['deliveryWeight']); } if (!InputValidator::isEmptyArrayKey($productParameter, "availibility") && ($productParameter['availibility'] == ProductAvailibility::ONSTOCK || $productParameter['availibility'] == ProductAvailibility::WARNSTOCK || $productParameter['availibility'] == ProductAvailibility::OUTSTOCK)) { $this->availibility = $productParameter['availibility']; } if (!InputValidator::isEmptyArrayKey($productParameter, "energyLabelSourceFile")) { $this->energyLabelSourceFile = $productParameter['energyLabelSourceFile']; } // parse images if (!InputValidator::isEmptyArrayKey($productParameter, "images")) { foreach ($productParameter['images'] as $image) { if (InputValidator::isArray($image) && !InputValidator::isEmptyArrayKey($image, "classifier") && !InputValidator::isEmptyArrayKey($image, "url")) { $this->images[$image['classifier']] = new Image($image['url']); } } } // parse price if (!InputValidator::isEmptyArrayKey($productParameter, "priceInfo")) { $priceInformation = $productParameter['priceInfo']; if (!InputValidator::isEmptyArrayKey($priceInformation, "price") && !InputValidator::isEmptyArrayKey($priceInformation, "quantity")) { $this->price = new ProductPrice($this->productID, ProductPriceType::PRICE, $priceInformation['price'], $priceInformation['quantity']); } if (!InputValidator::isEmptyArrayKey($priceInformation, "depositPrice")) { $this->depositPrice = new ProductPrice($this->productID, ProductPriceType::DEPOSIT, $priceInformation['depositPrice'], $priceInformation['quantity']); } if (!InputValidator::isEmptyArrayKey($priceInformation, "ecoParticipationPrice")) { $this->ecoParticipationPrice = new ProductPrice($this->productID, ProductPriceType::ECOPARTICIPATION, $priceInformation['ecoParticipationPrice'], $priceInformation['quantity']); } if (!InputValidator::isEmptyArrayKey($priceInformation, "priceWithDeposits")) { $this->withDepositPrice = new ProductPrice($this->productID, ProductPriceType::WITHDEPOSITS, $priceInformation['priceWithDeposits'], $priceInformation['quantity']); } if (!InputValidator::isEmptyArrayKey($priceInformation, "manufacturerPrice")) { $this->manufacturerPrice = new ProductPrice($this->productID, ProductPriceType::MANUFACTURER, $priceInformation['manufacturerPrice'], $priceInformation['quantity']); } if (!InputValidator::isEmptyArrayKey($priceInformation, "basePrice")) { $this->basePrice = new ProductPrice($this->productID, ProductPriceType::BASE, $priceInformation['basePrice'], $priceInformation['quantity']); } } } // update timestamp when make the next request $timestamp = (int) (microtime(true) * 1000); $this->NEXT_REQUEST_TIMESTAMP = $timestamp + RESTClient::$NEXT_RESPONSE_WAIT_TIME; }
/** * Fill the product filter with an array. * * @author David Pauli <*****@*****.**> * @param mixed[] $productFilterParameter The Product Filter Parameter as an array. * @since 0.0.1 * @since 0.1.0 Use a default Locale and Currency. * @since 0.1.2 Add error reporting. */ public function setProductFilter($productFilterParameter) { $this->errorReset(); if (!InputValidator::isArray($productFilterParameter) || InputValidator::isEmptyArray($productFilterParameter)) { $this->errorSet("PF-1"); Logger::warning("ep6\\ProductFilter\nProduct filter parameter " . $productFilterParameter . " to create product filter is invalid."); return; } foreach ($productFilterParameter as $key => $parameter) { if ($key == "page") { $this->setPage($parameter); } else { if ($key == "resultsPerPage") { $this->setResultsPerPage($parameter); } else { if ($key == "direction") { $this->setDirection($parameter); } else { if ($key == "sort") { $this->setSort($parameter); } else { if ($key == "q") { $this->setQ($parameter); } else { if ($key == "categoryID") { $this->setCategoryID($parameter); } else { $this->errorSet("PF-2"); Logger::warning("ep6\\ProductFilter\nUnknown attribute <i>" . $key . "</i> in product filter attribute."); } } } } } } } }
/** * This send function sends a special command to the REST server with additional parameter. * * @author David Pauli <*****@*****.**> * @since 0.0.0 * @since 0.0.1 Use HTTPRequestMethod enum. * @since 0.1.0 Allow empty message body if the status code is 204. * @api * @param String command The path which is requested in the REST client. * @param String[] postfields Add specific parameters to the REST server. * @return mixed[] The returned elements as array. */ public static function send($command, $postfields = array()) { if (!InputValidator::isRESTCommand($command) || !self::$ISCONNECTED || !InputValidator::isArray($postfields)) { return null; } $protocol = self::$ISSSL ? "https" : "http"; $url = $protocol . "://" . self::$HOST . "/" . self::PATHTOREST . "/" . self::$SHOP . "/" . $command; $headers = array("Accept: " . self::HTTP_ACCEPT, "Content-Type: " . self::HTTP_CONTENT_TYPE); if (InputValidator::isAuthToken(self::$AUTHTOKEN)) { array_push($headers, "Authorization: Bearer " . self::$AUTHTOKEN); } $curl = curl_init($url); curl_setopt($curl, CURLOPT_FAILONERROR, 1); // show full errors curl_setopt($curl, CURLOPT_FORBID_REUSE, 0); // connection can be opened curl_setopt($curl, CURLOPT_FRESH_CONNECT, 0); // no new connection required curl_setopt($curl, CURLOPT_NOBODY, 0); // show body curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // get response as string curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0); // no connection timeout curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, 0); // no connection timeout curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE); // cURL will choose the http version curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER); // understand ipv4 and ipv6 if (self::$ISSSL) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // don't check the peer ssl cerrificate curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS); curl_setopt($curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS); curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT); // default ssl version } else { curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP); curl_setopt($curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP); } switch (self::$HTTP_REQUEST_METHOD) { case HTTPRequestMethod::GET: curl_setopt($curl, CURLOPT_HTTPGET, 1); break; case HTTPRequestMethod::POST: $JSONpostfield = JSONHandler::createJSON($postfields); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTREDIR, 0); // don't post on redirects curl_setopt($curl, CURLOPT_POSTFIELDS, $JSONpostfield); break; case HTTPRequestMethod::PUT: $JSONpostfield = JSONHandler::createJSON($postfields); array_push($headers, "Content-Length: " . strlen($JSONpostfield)); curl_setopt($curl, CURLOPT_POSTFIELDS, $JSONpostfield); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT'); break; case HTTPRequestMethod::DELETE: $JSONpostfield = JSONHandler::createJSON($postfields); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_POSTFIELDS, $JSONpostfield); break; case HTTPRequestMethod::PATCH: $JSONpostfield = JSONHandler::createJSON($postfields); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($curl, CURLOPT_POSTFIELDS, $JSONpostfield); break; } curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($curl); $info = curl_getinfo($curl); $error = curl_error($curl); curl_close($curl); $logMessage = self::$HTTP_REQUEST_METHOD . " " . $info["url"] . "<br/>" . "<strong>Response</strong>: " . $info["http_code"] . ": <pre>" . htmlspecialchars($response) . "</pre><br/>" . "<strong>Content-Type</strong>: " . $info["content_type"] . "<br/>" . "<strong>Size</strong> (Header/Request): " . $info["header_size"] . "/" . $info["request_size"] . " Bytes<br/>" . "<strong>Time</strong> (Total/Namelookup/Connect/Pretransfer/Starttransfer/Redirect): " . $info["total_time"] . " / " . $info["namelookup_time"] . " / " . $info["connect_time"] . " / " . $info["pretransfer_time"] . " / " . $info["starttransfer_time"] . " / " . $info["redirect_time"] . " seconds<br/>"; Logger::notify("<strong>HTTP-SEND</strong>:<br/>" . $logMessage); // if message body is empty this is allowed with 204 if (!$response && $info["http_code"] != "204") { Logger::error("Error with send REST client: " . $error); return null; } elseif (!in_array($info["http_code"], array("200", "201", "204"))) { Logger::warning("Get wrong response: " . $info["http_code"]); return null; } return JSONHandler::parseJSON($response); }
/** * This send function sends a special command to the REST server with additional parameter. * * @author David Pauli <*****@*****.**> * @param String command The path which is requested in the REST client. * @param String[] $postParameter Add specific parameters to the REST server. * @since 0.0.0 * @since 0.0.1 Use HTTPRequestMethod enum. * @since 0.1.0 Allow empty message body if the status code is 204. * @since 0.1.2 Restructure the logging message and fix the PATCH call. * @since 0.1.2 Add error reporting. * @since 0.1.3 Remove isRESTCommand function. * @since 0.2.1 Refactor the complete send method. */ public static function send($command = "", $postParameter = array()) { self::errorReset(); if (!InputValidator::isArray($postParameter)) { Logger::warning("ep6\\RESTClient\\Post parameter (" . $postParameter . ") are not valid."); self::errorSet("RESTC-5"); return null; } if (!self::$ISCONNECTED) { Logger::warning("ep6\\RESTClient\nClient is not connected."); self::errorSet("RESTC-6"); return null; } $protocol = self::$ISSSL ? "https" : "http"; $url = $protocol . "://" . self::$HOST . "/" . self::PATHTOREST . "/" . self::$SHOP . "/" . $command; $headers = array("Accept: " . self::HTTP_ACCEPT, "Content-Type: " . self::HTTP_CONTENT_TYPE_JSON, "User-Agent: " . self::USER_AGENT); // add authentification if there is a token if (InputValidator::isAuthToken(self::$AUTHTOKEN)) { array_push($headers, "Authorization: Bearer " . self::$AUTHTOKEN); } # parse cookies if (!InputValidator::isEmptyArray(self::$COOKIES)) { $cookiesValues = array(); foreach (self::$COOKIES as $key => $value) { array_push($cookiesValues, $key . "=" . $value); } array_push($headers, "Cookie: " . implode("; ", $cookiesValues)); } $curl = curl_init($url); curl_setopt($curl, CURLOPT_FAILONERROR, 1); // show full errors curl_setopt($curl, CURLOPT_FORBID_REUSE, 0); // connection can be opened curl_setopt($curl, CURLOPT_FRESH_CONNECT, 0); // no new connection required curl_setopt($curl, CURLOPT_NOBODY, 0); // show body curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // get response as string curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 0); // no connection timeout curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, 0); // no connection timeout curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_NONE); // cURL will choose the http version curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_WHATEVER); // understand ipv4 and ipv6 curl_setopt($curl, CURLINFO_HEADER_OUT, 1); // save the header in the log curl_setopt($curl, CURLOPT_HEADER, 1); // get the header if (self::$ISSSL) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // don't check the peer ssl cerrificate curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS); curl_setopt($curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS); curl_setopt($curl, CURLOPT_SSLVERSION, 0); // default ssl version } else { curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP); curl_setopt($curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP); } switch (self::$HTTP_REQUEST_METHOD) { case HTTPRequestMethod::GET: curl_setopt($curl, CURLOPT_HTTPGET, 1); break; case HTTPRequestMethod::POST: $JSONpostfield = JSONHandler::createJSON($postParameter); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTREDIR, 0); // don't post on redirects curl_setopt($curl, CURLOPT_POSTFIELDS, $JSONpostfield); break; case HTTPRequestMethod::PUT: $JSONpostfield = JSONHandler::createJSON($postParameter); array_push($headers, "Content-Length: " . strlen($JSONpostfield)); curl_setopt($curl, CURLOPT_POSTFIELDS, $JSONpostfield); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT'); break; case HTTPRequestMethod::DELETE: $JSONpostfield = JSONHandler::createJSON($postParameter); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_POSTFIELDS, $JSONpostfield); break; case HTTPRequestMethod::PATCH: $JSONpostfield = "[" . JSONHandler::createJSON($postParameter) . "]"; curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($curl, CURLOPT_POSTFIELDS, $JSONpostfield); break; } curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($curl); $info = curl_getinfo($curl); $error = curl_error($curl); curl_close($curl); # get header and body list($header, $body) = self::explodeResponse($response); $header = trim($header); $content = trim($body); $logMessage = "Request:\n" . "Parameters: " . http_build_query($postParameter) . "\n" . $info["request_header"] . "Response:\n" . "Size (Header/Request): " . $info["header_size"] . "/" . $info["request_size"] . " Bytes\n" . "Time (Total/Namelookup/Connect/Pretransfer/Starttransfer/Redirect): " . $info["total_time"] . " / " . $info["namelookup_time"] . " / " . $info["connect_time"] . " / " . $info["pretransfer_time"] . " / " . $info["starttransfer_time"] . " / " . $info["redirect_time"] . " seconds\n" . $response . "\n"; Logger::notify("ep6\\RESTClient:\n" . $logMessage); # parse header, response code and body self::explodeHeader($header); self::$HTTP_RESPONSE_CODE = (int) $info["http_code"]; if (!InputValidator::isEmpty($content)) { self::$CONTENT = $content; } }
/** * This is the constructor of the product. * * @author David Pauli <*****@*****.**> * @since 0.0.0 * @since 0.1.0 Add price information. * @since 0.1.0 Use a default Locale. * @api * @param mixed[] $productParameter The product to create as array. */ public function __construct($productParameter) { if (!InputValidator::isArray($productParameter) || InputValidator::isEmptyArray($productParameter)) { return; } // if the product comes from the shop API if (InputValidator::isArray($productParameter) && !InputValidator::isEmptyArrayKey($productParameter, "productId")) { $this->productID = $productParameter['productId']; // load locale depended content if (!InputValidator::isEmptyArrayKey($productParameter, "forSale")) { $this->forSale = $productParameter['forSale']; } if (!InputValidator::isEmptyArrayKey($productParameter, "specialOffer")) { $this->specialOffer = $productParameter['specialOffer']; } if (!InputValidator::isEmptyArrayKey($productParameter, "name")) { $this->name = $productParameter['name']; } if (!InputValidator::isEmptyArrayKey($productParameter, "shortDescription")) { $this->shortDescription = $productParameter['shortDescription']; } if (!InputValidator::isEmptyArrayKey($productParameter, "description")) { $this->description = $productParameter['description']; } if (!InputValidator::isEmptyArrayKey($productParameter, "availabilityText")) { $this->availabilityText = $productParameter['availabilityText']; } // parse images foreach ($productParameter['images'] as $image) { if (InputValidator::isArray($image) && !InputValidator::isEmptyArrayKey($image, "classifier") && !InputValidator::isEmptyArrayKey($image, "url")) { $this->images[$image['classifier']] = new Image($image['url']); } } // parse price if (!InputValidator::isEmptyArrayKey($productParameter, "priceInfo")) { $priceInformation = $productParameter['priceInfo']; if (!InputValidator::isEmptyArrayKey($priceInformation, "price") && !InputValidator::isEmptyArrayKey($priceInformation, "quantity") && !InputValidator::isEmptyArrayKey($productParameter, "locale")) { $this->price = new PriceWithQuantity($priceInformation['price'], $priceInformation['quantity'], $productParameter["locale"]); } if (!InputValidator::isEmptyArrayKey($priceInformation, "depositPrice")) { $this->depositPrice = new Price($priceInformation['depositPrice']); } if (!InputValidator::isEmptyArrayKey($priceInformation, "ecoParticipationPrice")) { $this->ecoParticipationPrice = new Price($priceInformation['ecoParticipationPrice']); } if (!InputValidator::isEmptyArrayKey($priceInformation, "priceWithDeposits")) { $this->withDepositPrice = new Price($priceInformation['priceWithDeposits']); } if (!InputValidator::isEmptyArrayKey($priceInformation, "manufactorPrice")) { $this->manufactorPrice = new Price($priceInformation['manufactorPrice']); } if (!InputValidator::isEmptyArrayKey($priceInformation, "basePrice")) { $this->basePrice = new Price($priceInformation['basePrice']); } } } }
/** * This function returns the orders by using the order filter. * * @author David Pauli <*****@*****.**> * @return Order[] Returns an array of orders. * @since 0.1.3 * @since 0.2.0 Set error message for empty responses to notify. * @since 0.2.1 Implement REST client fixes. */ public function getOrders() { $this->errorReset(); $parameter = $this->getParameter(); // if request method is blocked if (!RESTClient::setRequestMethod(HTTPRequestMethod::GET)) { $this->errorSet("RESTC-9"); return; } RESTClient::send(self::RESTPATH . "?" . $parameter); $content = RESTClient::getJSONContent(); // if respond is empty if (InputValidator::isEmpty($content)) { $this->errorSet("OF-1"); Logger::notify("ep6\\OrderFilter\nREST respond for getting orders is empty."); return; } // if there is no results, page AND resultsPerPage element if (InputValidator::isEmptyArrayKey($content, "results") || InputValidator::isEmptyArrayKey($content, "page") || InputValidator::isEmptyArrayKey($content, "resultsPerPage")) { $this->errorSet("OF-2"); Logger::error("ep6\\OrderFilter\nRespond for " . self::RESTPATH . " can not be interpreted."); return; } $this->results = $content['results']; $orders = array(); // is there any order found: load the products. if (!InputValidator::isEmptyArrayKey($content, "items") && sizeof($content['items']) != 0) { foreach ($content['items'] as $item) { $order = new Order($item); // go to every filter foreach ($this->filters as $filter) { if (!InputValidator::isEmptyArrayKey($item, $filter->getAttribute()) || $filter->getOperator() == FilterOperation::UNDEF) { if (!InputValidator::isArray($item[$filter->getAttribute()])) { if (!$filter->isElementInFilter($item)) { continue 2; } } } else { continue 2; } } array_push($orders, $order); } } return $orders; }