diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..03b100e7 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,48 @@ +{ + // Pro informace o možných atributech použijte technologii IntelliSense. + // Umístěním ukazatele myši zobrazíte popisy existujících atributů. + // Další informace najdete tady: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Debug DryRun example", + "type": "php", + "request": "launch", + "program": "${workspaceFolder}/Examples/DryRun.php", + "cwd": "${fileDirname}", + "externalConsole": false, + "port": 9003 + }, + { + "name": "Launch built-in server and debug", + "type": "php", + "request": "launch", + "runtimeArgs": [ + "-S", + "localhost:8000", + "-t", + "." + ], + "port": 9003, + "serverReadyAction": { + "action": "openExternally" + } + }, + { + "name": "Debug current script in console", + "type": "php", + "request": "launch", + "program": "${file}", + "cwd": "${fileDirname}", + "externalConsole": false, + "port": 9003 + }, + { + "name": "Listen for Xdebug", + "type": "php", + "request": "launch", + "port": 9003 + }, + + ] +} \ No newline at end of file diff --git a/Examples/DryRun.php b/Examples/DryRun.php index b9a270ad..3b215b45 100644 --- a/Examples/DryRun.php +++ b/Examples/DryRun.php @@ -4,19 +4,36 @@ * AbraFlexi - Example how to dry-run request * * @author Vítězslav Dvořák - * @copyright (G) 2018 Vitex Software + * @copyright (G) 2018-2023 Vitex Software */ namespace Example\AbraFlexi; include_once './config.php'; -include_once '../vendor/autoload.php'; +/** + * Instance of AbraFlexi Invoice in dry-run mode with random code + */ -$invoice = new \AbraFlexi\FakturaVydana(); +$invoice = new \AbraFlexi\FakturaVydana([ + 'kod'=>'DRY_RUN_TEST', + 'typDokl' => 'code:FAKTURA', + 'poznam' => 'Test ' . time(), + 'varSym' => time()], ['dry-run' => true]); -$invoice->defaultUrlParams['dry-run'] = 'true'; +/** + * Save invoice to AbraFlexi + */ + try { + $resultInsert = $invoice->insertToAbraFlexi(); + } catch (\AbraFlexi\Exception $exc) { + echo $exc->getMessage(); + //For example we can get here: "AbraFlexi\FakturaVydana: Pole 'Variabilní symbol' musí být vyplněno. [DRY_RUN_TEST]" + } -$resultHere = $invoice->insertToFlexiBee(['typDokl' => 'code:FAKTURA']); +/** + * Save to AbraFlexi and load result + */ +$resultSync = $invoice->sync(); -echo json_encode($resultHere, JSON_PRETTY_PRINT);; +echo $resultSync ? 'OK' : 'Failed'; diff --git a/src/AbraFlexi/Adresar.php b/src/AbraFlexi/Adresar.php index f1f1bce7..225de08d 100644 --- a/src/AbraFlexi/Adresar.php +++ b/src/AbraFlexi/Adresar.php @@ -100,16 +100,24 @@ public function getAnyPhoneNumber() { $phoneNo = $numbers['tel']; } if (array_key_exists('kontakty', $numbers) && !empty($numbers['kontakty'])) { + + // Try to use primary contact if present foreach ($numbers['kontakty'] as $kontakt) { if ($kontakt['primarni'] == 'true') { - + if (strlen(trim($kontakt['mobil']))) { + $phoneNo = $kontakt['mobil']; + break; + } } - if (strlen(trim($kontakt['mobil']))) { - $phoneNo = $kontakt['mobil']; - break; - } elseif (strlen(trim($kontakt['mobil']))) { - $phoneNo = $kontakt['mobil']; - break; + } + + // Use first contact if no primary is set + if (is_null($phoneNo)) { + foreach ($numbers['kontakty'] as $kontakt) { + if (strlen(trim($kontakt['mobil']))) { + $phoneNo = $kontakt['mobil']; + break; + } } } } diff --git a/src/AbraFlexi/RO.php b/src/AbraFlexi/RO.php index 50a9d684..86d8c37c 100644 --- a/src/AbraFlexi/RO.php +++ b/src/AbraFlexi/RO.php @@ -1,7 +1,6 @@ ['type' => 'boolean', 'description' => 'The response will contain the global version number of the current export'], 'add-row-count' => ['type' => 'boolean', 'description' => 'Adding Total Records to Output (Pagination)'], 'as-gui' => ['type' => 'boolean', 'description' => 'Turns on functions that complement the GUI processing outputs'], @@ -436,7 +445,9 @@ class RO extends \Ease\Sand { * @param mixed $init default record id or initial data. See processInit() * @param array $options Connection settings and other options override */ - public function __construct($init = null, $options = []) { + public function __construct($init = null, $options = []) + { + $this->urlParams =& $this->urlParamsKnown; //Sync deprecated variable with current TODO: Remove in 2024 $this->init = $init; parent::setObjectName(); $this->setUp($options); @@ -454,7 +465,8 @@ public function __construct($init = null, $options = []) { * * @return string Jméno objektu */ - public function setObjectName($objectName = null) { + public function setObjectName($objectName = null) + { return parent::setObjectName(is_null($objectName) ? ( empty($this->getRecordIdent()) ? $this->getObjectName() : $this->getRecordIdent() . '@' . $this->getObjectName() ) : $objectName); } @@ -467,7 +479,8 @@ public function setObjectName($objectName = null) { * detail,offline,filter,ignore404,nativeTypes * timeout,companyUrl,ver,throwException */ - public function setUp(array $options = []) { + public function setUp(array $options = []) + { if (array_key_exists('ver', $options)) { $this->protoVersion = $options['ver']; $this->prefix = 'v' . round($this->protoVersion) . '/c/'; @@ -483,7 +496,6 @@ public function setUp(array $options = []) { $this->setupProperty($options, 'authSessionId', 'ABRAFLEXI_AUTHSESSID'); $this->setupProperty($options, 'timeout', 'ABRAFLEXI_TIMEOUT'); $this->setupProperty($options, 'nativeTypes', 'ABRAFLEXI_NATIVE_TYPES'); - if (!empty($this->authSessionId)) { $this->defaultHttpHeaders['X-authSessionId'] = $this->authSessionId; } @@ -519,7 +531,8 @@ public function setUp(array $options = []) { * * @return array Options */ - public static function companyUrlToOptions(string $companyUrl) { + public static function companyUrlToOptions(string $companyUrl) + { $urlParts = parse_url($companyUrl); $scheme = isset($urlParts['scheme']) ? $urlParts['scheme'] . '://' : ''; $host = isset($urlParts['host']) ? $urlParts['host'] : ''; @@ -541,7 +554,8 @@ public static function companyUrlToOptions(string $companyUrl) { * * @return array usable as second constructor parameter */ - public function getConnectionOptions() { + public function getConnectionOptions() + { $conOpts = ['url' => $this->url]; if (empty($this->authSessionId)) { $conOpts ['user'] = $this->user; @@ -563,7 +577,8 @@ public function getConnectionOptions() { * Export current/given configutation into Environment * @param array $opts */ - public function configToEnv(array $opts = []) { + public function configToEnv(array $opts = []) + { $options = empty($opts) ? $this->getConnectionOptions() : $opts; if (array_key_exists('url', $options)) { putenv('ABRAFLEXI_URL=' . $options['URL']); @@ -587,7 +602,8 @@ public function configToEnv(array $opts = []) { * * @return boolean Online Status */ - public function curlInit() { + public function curlInit() + { if ($this->offline === false) { $this->curl = \curl_init(); // create curl resource \curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); // return content as a string from curl_exec @@ -606,7 +622,6 @@ public function curlInit() { 'Connection: Keep-Alive', 'Keep-Alive: ' . $this->timeout ]); - \curl_setopt($this->curl, CURLOPT_TIMEOUT, $this->timeout); } @@ -626,7 +641,8 @@ public function curlInit() { * * @param mixed $init číslo/"(code:)kód"/(část)URI záznamu k načtení | pole hodnot k předvyplnění */ - public function processInit($init) { + public function processInit($init) + { if (is_integer($init) && $this->autoload) { $this->loadFromAbraFlexi($init); } elseif (is_array($init)) { @@ -650,7 +666,8 @@ public function processInit($init) { * * @return bool Success */ - public function setDataValue(string $columnName, $value) { + public function setDataValue(string $columnName, $value) + { switch ($columnName) { case 'kod': $value = self::uncode($value); //Alwyas uncode "kod" column @@ -684,7 +701,8 @@ public function setDataValue(string $columnName, $value) { * * @return RO Current object state */ - public function stripBody(array $keep = []) { + public function stripBody(array $keep = []) + { $id = $this->getRecordID(); $code = $this->getRecordCode(); $extIds = $this->getExternalIDs(); @@ -711,7 +729,8 @@ public function stripBody(array $keep = []) { * * @param \DateTime $date */ - public static function dateToFlexiDate(\DateTime $date) { + public static function dateToFlexiDate(\DateTime $date) + { return $date->format(self::$DateFormat); } @@ -720,7 +739,8 @@ public static function dateToFlexiDate(\DateTime $date) { * * @param \DateTime $dateTime */ - public static function dateToFlexiDateTime(\DateTime $dateTime) { + public static function dateToFlexiDateTime(\DateTime $dateTime) + { return $dateTime->format(self::$DateTimeFormat); } @@ -729,7 +749,8 @@ public static function dateToFlexiDateTime(\DateTime $dateTime) { * * @param string $prefix */ - public function setPrefix(string $prefix) { + public function setPrefix(string $prefix) + { switch ($prefix) { case 'a': //Access case 'c': //Company @@ -758,7 +779,8 @@ public function setPrefix(string $prefix) { * * @return boolean format is availble */ - public function setFormat(string $format) { + public function setFormat(string $format) + { $result = true; if (($this->debug === true) && !empty($this->evidence) && isset(Formats::$$this->evidence)) { if (array_key_exists($format, array_flip(Formats::$$this->evidence)) === false) { @@ -780,7 +802,8 @@ public function setFormat(string $format) { * * @return boolean evidence switching status */ - public function setEvidence(string $evidence) { + public function setEvidence(string $evidence) + { switch ($this->prefix) { case '/c/': if ($this->debug === true) { @@ -812,7 +835,8 @@ public function setEvidence(string $evidence) { * * @return string */ - public function getEvidence() { + public function getEvidence() + { return $this->evidence; } @@ -822,7 +846,8 @@ public function getEvidence() { * * @param string $company */ - public function setCompany($company) { + public function setCompany($company) + { $this->company = $company; } @@ -832,7 +857,8 @@ public function setCompany($company) { * * @return string */ - public function getCompany() { + public function getCompany() + { return $this->company; } @@ -841,7 +867,8 @@ public function getCompany() { * * @return string */ - public function getResponseEvidence() { + public function getResponseEvidence() + { switch ($this->evidence) { case 'c': $evidence = 'company'; @@ -863,7 +890,8 @@ public function getResponseEvidence() { * * @return array */ - public static function object2array($object) { + public static function object2array($object) + { $result = null; if (is_object($object)) { $objectData = get_object_vars($object); @@ -890,7 +918,8 @@ public static function object2array($object) { * * @return array */ - public static function objectToID($object) { + public static function objectToID($object) + { $resultID = null; if (is_object($object) && method_exists($object, '__toString') ) { @@ -915,7 +944,8 @@ public static function objectToID($object) { * * @return string Evidence URL */ - public function getEvidenceURL() { + public function getEvidenceURL() + { $evidenceUrl = $this->url . $this->prefix . $this->company; $evidence = $this->getEvidence(); if (!empty($evidence)) { @@ -931,7 +961,8 @@ public function getEvidenceURL() { * * @return string */ - public function evidenceUrlWithSuffix($urlSuffix) { + public function evidenceUrlWithSuffix($urlSuffix) + { $evidenceUrl = $this->getEvidenceUrl(); if (!empty($urlSuffix)) { if (($urlSuffix[0] != '/') && ($urlSuffix[0] != ';') && ($urlSuffix[0] != '?')) { @@ -945,7 +976,8 @@ public function evidenceUrlWithSuffix($urlSuffix) { /** * Update $this->apiURL */ - public function updateApiURL() { + public function updateApiURL() + { $this->apiURL = $this->getEvidenceURL(); $rowIdentifier = $this->getRecordIdent(); if (empty($rowIdentifier)) { @@ -959,7 +991,6 @@ public function updateApiURL() { } $this->apiURL .= '.' . $this->format; } - /* * Add Default Url params to given url if not overrided * @@ -968,7 +999,8 @@ public function updateApiURL() { * @return string url with default params added */ - public function addDefaultUrlParams(string $urlRaw) { + public function addDefaultUrlParams(string $urlRaw) + { return \Ease\Functions::addUrlParams($urlRaw, $this->defaultUrlParams, false); } @@ -983,11 +1015,11 @@ public function addDefaultUrlParams(string $urlRaw) { * @return array|boolean Výsledek operace */ public function performRequest(string $urlSuffix = '', string $method = 'GET', - $format = null) { + $format = null) + { $this->rowCount = null; $this->responseStats = []; $this->errors = []; - if (preg_match('/^http/', $urlSuffix)) { $url = $urlSuffix; } elseif (strlen($urlSuffix) && ($urlSuffix[0] == '/')) { @@ -998,7 +1030,6 @@ public function performRequest(string $urlSuffix = '', string $method = 'GET', $responseCode = $this->doCurlRequest($this->addDefaultUrlParams($url), $method, $format); - return $this->lastCurlResponse ? $this->parseResponse($this->rawResponseToArray(strval($this->lastCurlResponse), $this->responseFormat), $responseCode) : false; } @@ -1011,7 +1042,8 @@ public function performRequest(string $urlSuffix = '', string $method = 'GET', * * @return array */ - public function rawResponseToArray(string $responseRaw, string $format) { + public function rawResponseToArray(string $responseRaw, string $format) + { $responseDecoded = []; if (!empty(trim($responseRaw))) { switch ($format) { @@ -1037,7 +1069,8 @@ public function rawResponseToArray(string $responseRaw, string $format) { * * @return array types resolved */ - public function fixResponseTypes(array $response) { + public function fixResponseTypes(array $response) + { foreach ($response as $evidence => $records) { if (array_key_exists($evidence, EvidenceList::$evidences)) { foreach ($records as $recordId => $record) { @@ -1059,7 +1092,8 @@ public function fixResponseTypes(array $response) { * * @throws \Ease\Exception */ - public function fixRecordTypes(array $record, $evidence = null) { + public function fixRecordTypes(array $record, $evidence = null) + { foreach ($record as $column => $value) { if ($column && !strstr($column, '@')) { $columnInfo = $this->getColumnInfo($column, $evidence); @@ -1118,7 +1152,8 @@ public function fixRecordTypes(array $record, $evidence = null) { * * @return array */ - public function rawJsonToArray($rawJson) { + public function rawJsonToArray($rawJson) + { $responseDecoded = json_decode($rawJson, true, 10); $decodeError = json_last_error_msg(); if ($decodeError == 'No error') { @@ -1143,7 +1178,8 @@ public function rawJsonToArray($rawJson) { * * @return array */ - public function rawXmlToArray($rawXML) { + public function rawXmlToArray($rawXML) + { return $this->fixResponseTypes(self::xml2array($rawXML)); } @@ -1155,7 +1191,8 @@ public function rawXmlToArray($rawXML) { * * @return array main data part of response */ - public function parseResponse($responseDecoded, $responseCode) { + public function parseResponse($responseDecoded, $responseCode) + { $mainResult = null; switch ($responseCode) { case 201: //We do not care about Success Write here @@ -1172,7 +1209,6 @@ public function parseResponse($responseDecoded, $responseCode) { } $mainResult = $this->unifyResponseFormat($responseDecoded); - if (array_key_exists('stats', $responseDecoded)) { $this->responseStats = $responseDecoded['stats']; } elseif (!empty($mainResult)) { @@ -1198,7 +1234,6 @@ public function parseResponse($responseDecoded, $responseCode) { $this->lastResult = $mainResult; break; - case 500: // Internal Server Error if ($this->debug === true) { $this->error500Reporter($responseDecoded); @@ -1236,7 +1271,8 @@ public function parseResponse($responseDecoded, $responseCode) { * * @return int number of errors processed */ - public function parseError(array $responseDecoded) { + public function parseError(array $responseDecoded) + { if (array_key_exists('success', $responseDecoded)) { $this->errors = [['message' => array_key_exists('message', $responseDecoded) ? $responseDecoded['message'] : '']]; } else { @@ -1255,7 +1291,8 @@ public function parseError(array $responseDecoded) { * * @return int HTTP Response CODE */ - public function doCurlRequest($url, $method, $format = null) { + public function doCurlRequest($url, $method, $format = null) + { if (is_null($format)) { $format = $this->format; } @@ -1264,11 +1301,8 @@ public function doCurlRequest($url, $method, $format = null) { curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, strtoupper($method)); //Vždy nastavíme byť i prázná postdata jako ochranu před chybou 411 curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->postFields); - $httpHeaders = $this->defaultHttpHeaders; - $formats = Formats::bySuffix(); - if (!isset($httpHeaders['Accept'])) { $httpHeaders['Accept'] = $formats[$format]['content-type']; } @@ -1280,7 +1314,6 @@ public function doCurlRequest($url, $method, $format = null) { $value = $header . ': ' . $value; }); curl_setopt($this->curl, CURLOPT_HTTPHEADER, $httpHeaders); - // Proveď samotnou operaci $this->lastCurlResponse = curl_exec($this->curl); $this->curlInfo = curl_getinfo($this->curl); @@ -1310,14 +1343,14 @@ public function doCurlRequest($url, $method, $format = null) { * * @return string response format */ - public function contentTypeToResponseFormat(string $contentType, $url = null) { + public function contentTypeToResponseFormat(string $contentType, $url = null) + { if (!empty($url)) { $url = parse_url($url, PHP_URL_PATH); } $contentTypeClean = strstr($contentType, ';') ? substr($contentType, 0, strpos($contentType, ';')) : $contentType; - switch ($url) { case '/login-logout/login'; $responseFormat = 'json'; @@ -1327,7 +1360,6 @@ public function contentTypeToResponseFormat(string $contentType, $url = null) { case 'text/javascript': $responseFormat = 'js'; break; - default: $responseFormat = Formats::contentTypeToSuffix($contentTypeClean); break; @@ -1346,7 +1378,8 @@ public function contentTypeToResponseFormat(string $contentType, $url = null) { * * @return boolean */ - public function setAction(string $action) { + public function setAction(string $action) + { $result = false; $actionsAvailable = $this->getActionsInfo(); if (is_array($actionsAvailable) && array_key_exists($action, @@ -1364,7 +1397,8 @@ public function setAction(string $action) { * * @return array */ - public static function xml2array($xml) { + public static function xml2array($xml) + { $arr = []; if (!empty($xml)) { if (is_string($xml)) { @@ -1387,7 +1421,8 @@ public static function xml2array($xml) { /** * Odpojení od AbraFlexi. */ - public function disconnect() { + public function disconnect() + { if (is_resource($this->curl)) { curl_close($this->curl); } @@ -1397,7 +1432,8 @@ public function disconnect() { /** * Disconnect CURL befere pass away */ - public function __destruct() { + public function __destruct() + { $this->disconnect(); } @@ -1408,7 +1444,8 @@ public function __destruct() { * * @return array */ - public function getFlexiRow($recordID) { + public function getFlexiRow($recordID) + { $record = null; $response = $this->performRequest($this->evidence . '/' . $recordID . '.json'); if (isset($response[$this->evidence])) { @@ -1425,8 +1462,9 @@ public function getFlexiRow($recordID) { * @param array $conditions pole podmínek - rendrují se do () * @param array $urlParams pole parametrů - rendrují za ? */ - public function extractUrlParams(&$conditions, &$urlParams) { - foreach (array_keys($this->urlParams) as $urlParam) { + public function extractUrlParams(&$conditions, &$urlParams) + { + foreach (array_keys($this->urlParamsKnown) as $urlParam) { if (isset($conditions[$urlParam])) { \Ease\Functions::divDataArray($conditions, $urlParams, $urlParam); } @@ -1440,7 +1478,8 @@ public function extractUrlParams(&$conditions, &$urlParams) { * * @return string */ - public static function urlEncode(string $urlRaw) { + public static function urlEncode(string $urlRaw) + { return str_replace(['%27', '%3A'], ["'", ':'], rawurlencode($urlRaw)); } @@ -1452,11 +1491,11 @@ public static function urlEncode(string $urlRaw) { * * @return array Data obtained */ - public function getFlexiData(string $suffix = '', $conditions = null) { + public function getFlexiData(string $suffix = '', $conditions = null) + { $finalUrl = ''; $evidenceToRestore = null; $urlParams = $this->defaultUrlParams; - if (!empty($conditions)) { if (is_array($conditions)) { $this->extractUrlParams($conditions, $urlParams); @@ -1486,7 +1525,6 @@ public function getFlexiData(string $suffix = '', $conditions = null) { } $finalUrl .= $conditions; - if ($suffix == '$sum') { $finalUrl .= '/$sum'; } @@ -1527,7 +1565,8 @@ public function getFlexiData(string $suffix = '', $conditions = null) { * * @return int počet načtených položek */ - public function loadFromAbraFlexi($id = null) { + public function loadFromAbraFlexi($id = null) + { $data = []; if (is_null($id)) { $id = $this->getMyKey(); @@ -1548,7 +1587,8 @@ public function loadFromAbraFlexi($id = null) { * * @return boolean */ - public function reload() { + public function reload() + { $id = $this->getRecordIdent(); $this->dataReset(); $this->loadFromAbraFlexi($id); @@ -1564,7 +1604,8 @@ public function reload() { * * @return string Filter code */ - public function setFilter($filter) { + public function setFilter($filter) + { return $this->filter = is_array($filter) ? self::flexiUrl($filter) : $filter; } @@ -1580,7 +1621,8 @@ public function setFilter($filter) { * * @return string */ - public function getJsonizedData($data = null, $options = 0) { + public function getJsonizedData($data = null, $options = 0) + { if (is_null($data)) { $data = $this->getData(); } @@ -1589,7 +1631,6 @@ public function getJsonizedData($data = null, $options = 0) { $this->getDataForJSON($data)); $jsonRaw = json_encode([$this->nameSpace => $dataToJsonize], $options); - return $jsonRaw; } @@ -1600,13 +1641,13 @@ public function getJsonizedData($data = null, $options = 0) { * * @return array */ - public function getDataForJSON($data = null) { + public function getDataForJSON($data = null) + { if (is_null($data)) { $data = $this->getData(); } $dataForJson = [$this->getEvidence() => $this->objectToID($data)]; - if (!is_null($this->action)) { $dataForJson[$this->evidence . '@action'] = $this->action; $this->action = null; @@ -1650,7 +1691,8 @@ public function getDataForJSON($data = null) { * * @return boolean adding to stack success */ - public function join(&$object) { + public function join(&$object) + { $result = true; if (method_exists($object, 'getDataForJSON')) { $this->chained[] = $object; @@ -1668,7 +1710,8 @@ public function join(&$object) { * * @return string id ready for use in URL */ - public static function urlizeId($id) { + public static function urlizeId($id) + { if (is_array($id)) { $id = rawurlencode('(' . self::flexiUrl($id) . ')'); } elseif (is_numeric($id)) { @@ -1688,7 +1731,8 @@ public static function urlizeId($id) { * * @return boolean */ - public function idExists($identifer = null) { + public function idExists($identifer = null) + { if (is_null($identifer)) { $identifer = $this->getMyKey(); } @@ -1710,7 +1754,8 @@ public function idExists($identifer = null) { * * @return boolean Record presence status */ - public function recordExists($data = []) { + public function recordExists($data = []) + { if (empty($data)) { $data = $this->getData(); @@ -1720,7 +1765,6 @@ public function recordExists($data = []) { $keyColumn = $this->getKeyColumn(); $res = $this->getColumnsFromAbraFlexi([$keyColumn], is_array($data) ? $data : [$keyColumn => $data]); - if (empty($res) || (isset($res['success']) && ($res['success'] == 'false')) || ((isset($res) && is_array($res)) && !isset($res[0]) )) { $found = false; } else { @@ -1738,13 +1782,13 @@ public function recordExists($data = []) { * sloupečku * @return array */ - public function getAllFromAbraFlexi($conditions = null, $indexBy = null) { + public function getAllFromAbraFlexi($conditions = null, $indexBy = null) + { if (is_int($conditions)) { $conditions = [$this->getmyKeyColumn() => $conditions]; } $flexiData = $this->getFlexiData('', $conditions); - if (!is_null($indexBy)) { $flexiData = \Ease\Functions::reindexArrayBy($flexiData); } @@ -1762,7 +1806,8 @@ public function getAllFromAbraFlexi($conditions = null, $indexBy = null) { * @return array */ public function getColumnsFromAbraFlexi($columnsList, $conditions = [], - $indexBy = null) { + $indexBy = null) + { $detail = 'full'; switch (gettype($columnsList)) { case 'integer': //Record ID @@ -1789,9 +1834,7 @@ public function getColumnsFromAbraFlexi($columnsList, $conditions = [], } $conditions['detail'] = $detail; - $flexiData = $this->getFlexiData('', $conditions); - if (is_string($indexBy) && is_array($flexiData) && array_key_exists(0, $flexiData) && array_key_exists($indexBy, $flexiData[0])) { $flexiData = \Ease\Functions::reindexArrayBy($flexiData, $indexBy); @@ -1808,9 +1851,9 @@ public function getColumnsFromAbraFlexi($columnsList, $conditions = [], * * @return string */ - public function getKod($data = null, $unique = true) { + public function getKod($data = null, $unique = true) + { $kod = null; - if (is_null($data)) { $data = $this->getData(); } @@ -1865,7 +1908,8 @@ public function getKod($data = null, $unique = true) { /** * Save RAW Curl Request & Response to files in Temp directory */ - public function saveDebugFiles() { + public function saveDebugFiles() + { $tmpdir = sys_get_temp_dir(); $fname = $this->evidence . '-' . $this->curlInfo['when'] . '.' . $this->format; $reqname = $tmpdir . '/request-' . $fname; @@ -1884,7 +1928,8 @@ public function saveDebugFiles() { * * @param string $data */ - public function setPostFields($data) { + public function setPostFields($data) + { $this->postFields = $data; } @@ -1892,7 +1937,8 @@ public function setPostFields($data) { * Get Content ready to be send as POST body * @return string */ - public function getPostFields() { + public function getPostFields() + { return $this->postFields; } @@ -1904,11 +1950,12 @@ public function getPostFields() { * * @return string "in" fragment */ - public static function flexiIN(array $items, string $key) { + public static function flexiIN(array $items, string $key) + { $slashed = array_map(function ($a, $column) { return $column === 'stitky' ? "'" . self::code($a) . "'" : "'$a'"; }, $items, - array_fill(0, count($items), $key)); + array_fill(0, count($items), $key)); return $key . " in (" . implode(',', $slashed) . ")"; } @@ -1923,9 +1970,9 @@ public static function flexiIN(array $items, string $key) { * * @return string */ - public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq') { + public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq') + { $parts = []; - foreach ($data as $column => $value) { if (!is_numeric($column)) { if (is_integer($data[$column]) || is_float($data[$column])) { @@ -2011,7 +2058,8 @@ public static function flexiUrl(array $data, $joiner = 'and', $defop = 'eq') { * * @return null|int indentifikátor záznamu reprezentovaného objektem */ - public function getRecordID() { + public function getRecordID() + { $id = $this->getDataValue('id'); return is_null($id) ? null : (is_numeric($id) ? intval($id) : $id); } @@ -2024,7 +2072,8 @@ public function getRecordID() { * * @return string record code identifier */ - public function getRecordCode() { + public function getRecordCode() + { return empty($this->getDataValue('kod')) ? null : self::code($this->getDataValue('kod')); } @@ -2036,7 +2085,8 @@ public function getRecordCode() { * * @return string|int|null record code identifier */ - public function getRecordIdent() { + public function getRecordIdent() + { $ident = $this->getExternalID(); if (empty($ident)) { $ident = $this->getRecordCode(); @@ -2055,7 +2105,8 @@ public function getRecordIdent() { * * @return string indentifikátor záznamu reprezentovaného objektem */ - public function __toString() { + public function __toString() + { return strval($this->getRecordIdent()); } @@ -2066,7 +2117,8 @@ public function __toString() { * * @return string Class name */ - public static function evidenceToClassName($evidence) { + public static function evidenceToClassName($evidence) + { return str_replace(' ', '', ucwords(str_replace('-', ' ', $evidence))); } @@ -2075,7 +2127,8 @@ public static function evidenceToClassName($evidence) { * * @return string|null id or null if no records */ - public function getFirstRecordID() { + public function getFirstRecordID() + { $firstID = null; $keyColumn = $this->getKeyColumn(); $firstIdRaw = $this->getColumnsFromAbraFlexi([$keyColumn], @@ -2093,7 +2146,8 @@ public function getFirstRecordID() { * * @return int|null */ - public function getNextRecordID($conditions = []) { + public function getNextRecordID($conditions = []) + { $conditions['order'] = 'id@D'; $conditions['limit'] = 1; $conditions[] = 'id gt ' . $this->getRecordID(); @@ -2109,7 +2163,8 @@ public function getNextRecordID($conditions = []) { * * @return int|null */ - public function getPrevRecordID($conditions = []) { + public function getPrevRecordID($conditions = []) + { $conditions['order'] = 'id@A'; $conditions['limit'] = 1; $conditions[] = 'id lt ' . $this->getRecordID(); @@ -2125,7 +2180,8 @@ public function getPrevRecordID($conditions = []) { * * @return string|array one id or array if multiplete */ - public function getExternalID($want = null) { + public function getExternalID($want = null) + { $extid = null; $ids = $this->getExternalIDs(); if (is_null($want)) { @@ -2158,7 +2214,8 @@ public function getExternalID($want = null) { * * @return array */ - public function getExternalIDs() { + public function getExternalIDs() + { return $this->getDataValue('external-ids'); } @@ -2170,9 +2227,9 @@ public function getExternalIDs() { * * @return int */ - public function getGlobalVersion() { + public function getGlobalVersion() + { $this->getFlexiData('', ['add-global-version' => 'true', 'limit' => 1]); - return $this->globalVersion; } @@ -2183,7 +2240,8 @@ public function getGlobalVersion() { * * @return string API URL for current record or object/evidence */ - public function getApiURL($format = null) { + public function getApiURL($format = null) + { $apiUrl = str_replace(['.' . $this->format, '?limit=0'], '', $this->apiURL); return $apiUrl . (empty($format) ? '' : '.' . $format ); } @@ -2193,7 +2251,8 @@ public function getApiURL($format = null) { * * @return string */ - public function getResponseFormat() { + public function getResponseFormat() + { return $this->responseFormat; } @@ -2204,7 +2263,8 @@ public function getResponseFormat() { * * @return array */ - public function unifyResponseFormat($responseBody) { + public function unifyResponseFormat($responseBody) + { if (!is_array($responseBody) || array_key_exists('message', $responseBody)) { //Unifi response format $response = $responseBody; @@ -2240,7 +2300,8 @@ public function unifyResponseFormat($responseBody) { * * @return array Evidence structure */ - public function getOfflineColumnsInfo($evidence = null) { + public function getOfflineColumnsInfo($evidence = null) + { $columnsInfo = null; $infoSource = self::$infoDir . '/Properties.' . (empty($evidence) ? $this->getEvidence() : $evidence) . '.json'; if (file_exists($infoSource)) { @@ -2264,7 +2325,8 @@ public function getOfflineColumnsInfo($evidence = null) { * * @return array structure */ - public function getOnlineColumnsInfo($evidence = null) { + public function getOnlineColumnsInfo($evidence = null) + { $properties = []; $evidence = is_null($evidence) ? $this->getEvidence() : $evidence; $flexinfo = $this->performRequest('/c/' . $this->company . '/' . $evidence . '/properties.json'); @@ -2291,7 +2353,8 @@ public function getOnlineColumnsInfo($evidence = null) { * @param array $columnsInfo * @param string $evidence */ - public function updateColumnsInfo($columnsInfo = null, $evidence = null) { + public function updateColumnsInfo($columnsInfo = null, $evidence = null) + { $evidence = is_null($evidence) ? $this->getEvidence() : $evidence; if (is_null($columnsInfo)) { $this->columnsInfo[$evidence] = $this->offline ? $this->getOfflineColumnsInfo($evidence) : $this->getOnlineColumnsInfo($evidence); @@ -2308,7 +2371,8 @@ public function updateColumnsInfo($columnsInfo = null, $evidence = null) { * * @return array */ - public function getColumnsInfo($evidence = null) { + public function getColumnsInfo($evidence = null) + { $evidence = is_null($evidence) ? $this->getEvidence() : $evidence; if (!array_key_exists($evidence, $this->columnsInfo)) { $this->updateColumnsInfo($this->getOfflineColumnsInfo($evidence), @@ -2325,7 +2389,8 @@ public function getColumnsInfo($evidence = null) { * * @return array column properties or null if column not exits */ - public function getColumnInfo($column, $evidence = null) { + public function getColumnInfo($column, $evidence = null) + { $columnsInfo = $this->getColumnsInfo(empty($evidence) ? $this->getEvidence() : $evidence); return (empty($column) || empty($columnsInfo) || !is_array($columnsInfo)) ? null : (array_key_exists($column, $columnsInfo) ? $columnsInfo[$column] : null); } @@ -2337,7 +2402,8 @@ public function getColumnInfo($column, $evidence = null) { * * @return array Evidence structure */ - public function getActionsInfo($evidence = null) { + public function getActionsInfo($evidence = null) + { $actionsInfo = null; if (is_null($evidence)) { $evidence = $this->getEvidence(); @@ -2356,7 +2422,8 @@ public function getActionsInfo($evidence = null) { * * @return array Evidence structure */ - public function getRelationsInfo($evidence = null) { + public function getRelationsInfo($evidence = null) + { $relationsInfo = null; if (is_null($evidence)) { $evidence = $this->getEvidence(); @@ -2375,7 +2442,8 @@ public function getRelationsInfo($evidence = null) { * * @return array Evidence info */ - public function getEvidenceInfo($evidence = null) { + public function getEvidenceInfo($evidence = null) + { $evidencesInfo = null; if (is_null($evidence)) { $evidence = $this->getEvidence(); @@ -2397,7 +2465,8 @@ public function getEvidenceInfo($evidence = null) { * * @return array Evidence info */ - public function getEvidenceName($evidence = null) { + public function getEvidenceName($evidence = null) + { $evidenceName = null; if (is_null($evidence)) { $evidence = $this->getEvidence(); @@ -2413,7 +2482,8 @@ public function getEvidenceName($evidence = null) { * * @param string $destfile path to file */ - public function saveResponseToFile($destfile) { + public function saveResponseToFile($destfile) + { if (strlen($this->lastCurlResponse)) { $this->doCurlRequest($this->apiURL, 'GET', $this->format); } @@ -2425,7 +2495,8 @@ public function saveResponseToFile($destfile) { * * @return array Null or Relations */ - public function getVazby($id = null) { + public function getVazby($id = null) + { if (is_null($id)) { $id = $this->getRecordID(); } @@ -2444,7 +2515,8 @@ public function getVazby($id = null) { * * @return string url */ - public function getAbraFlexiURL() { + public function getAbraFlexiURL() + { $parsed_url = parse_url(str_replace('.' . $this->format, '', $this->apiURL)); $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : ''; $host = isset($parsed_url['host']) ? $parsed_url['host'] : ''; @@ -2463,7 +2535,8 @@ public function getAbraFlexiURL() { * * @return boolean */ - public function setMyKey($myKeyValue) { + public function setMyKey($myKeyValue) + { $res = false; if (is_string($myKeyValue)) { if (substr($myKeyValue, 0, 4) == 'ext:') { @@ -2500,7 +2573,8 @@ public function setMyKey($myKeyValue) { * * @return boolean get flag state */ - public function ignore404($ignore = null) { + public function ignore404($ignore = null) + { if (!is_null($ignore)) { $this->ignoreNotFound = $ignore; } @@ -2518,12 +2592,11 @@ public function ignore404($ignore = null) { * * @return boolean mail sent status */ - public function sendByMail($to, $subject, $body, $cc = null) { + public function sendByMail($to, $subject, $body, $cc = null) + { $this->setPostFields($body); - $this->performRequest(rawurlencode((string) $this->getRecordID()) . '/odeslani-dokladu?to=' . $to . '&subject=' . urlencode($subject) . '&cc=' . $cc , 'PUT', 'xml'); - return $this->lastResponseCode == 200; } @@ -2534,7 +2607,8 @@ public function sendByMail($to, $subject, $body, $cc = null) { * * @return \DateTime | false */ - public static function flexiDateToDateTime(string $flexidate) { + public static function flexiDateToDateTime(string $flexidate) + { if (strstr($flexidate, '+')) { $format = self::$DateFormat . 'O'; } elseif (strstr($flexidate, 'Z')) { @@ -2553,7 +2627,8 @@ public static function flexiDateToDateTime(string $flexidate) { * * @return \DateTime | false */ - public static function flexiDateTimeToDateTime(string $flexidatetime) { + public static function flexiDateTimeToDateTime(string $flexidatetime) + { if (strchr($flexidatetime, '.')) { //NewFormat $format = self::$DateTimeFormat; } else { // Old format @@ -2576,7 +2651,8 @@ public static function flexiDateTimeToDateTime(string $flexidatetime) { * @return string|null filename downloaded or none */ public function getInFormat(string $format, $reportName = null, $lang = null, - $sign = false) { + $sign = false) + { $response = null; if ($this->setFormat($format)) { $urlParams = []; @@ -2615,7 +2691,8 @@ public function getInFormat(string $format, $reportName = null, $lang = null, * @return string|null filename downloaded or none */ public function downloadInFormat(string $format, $destDir = './', - $reportName = null) { + $reportName = null) + { $fileOnDisk = null; $formatBackup = $this->format; if ($this->setFormat($format)) { @@ -2637,7 +2714,8 @@ public function downloadInFormat(string $format, $destDir = './', * * @return int number of records taken */ - public function takeData($data) { + public function takeData($data) + { $keyColumn = $this->getKeyColumn(); if (is_array($data) && array_key_exists($keyColumn, $data) && is_array($data[$keyColumn])) { foreach ($data[$keyColumn] as $recPos => $recordKey) { @@ -2651,7 +2729,6 @@ public function takeData($data) { } } $result = parent::takeData($data); - if ($result && (array_key_exists($keyColumn, $data) || array_key_exists('kod', $data))) { $this->updateApiURL(); } @@ -2666,7 +2743,8 @@ public function takeData($data) { * * @return array */ - public function getReportsInfo() { + public function getReportsInfo() + { $reports = []; $reportsRaw = $this->getFlexiData($this->getEvidenceURL() . '/reports'); if (!empty($reportsRaw) && array_key_exists('reports', $reportsRaw) && !empty($reportsRaw['reports']) && array_key_exists('report', $reportsRaw['reports']) && @@ -2692,7 +2770,8 @@ public function getReportsInfo() { * * @return string authUserId or null in case of problems */ - public function requestAuthSessionID(string $username, string $password, $otp = null) { + public function requestAuthSessionID(string $username, string $password, $otp = null) + { $this->postFields = http_build_query(is_null($otp) ? ['username' => $username, 'password' => $password] : ['username' => $username, 'password' => $password, 'otp' => $otp]); @@ -2711,7 +2790,8 @@ public function requestAuthSessionID(string $username, string $password, $otp = * * @return boolean sign in success */ - public function login() { + public function login() + { $this->authSessionId = $this->requestAuthSessionID($this->user, $this->password); return $this->lastResponseCode == 200; @@ -2727,7 +2807,8 @@ public function login() { * * @return array server response */ - public function logout($username = null) { + public function logout($username = null) + { return $this->performRequest('/status/user/' . (is_null($username) ? $this->user : $username) . '/logout', 'POST'); } @@ -2737,7 +2818,8 @@ public function logout($username = null) { * * @param array $errorResponse result of parseError(); */ - public function error500Reporter($errorResponse) { + public function error500Reporter($errorResponse) + { $ur = str_replace('/c/' . $this->company, '', str_replace($this->url, '', $this->curlInfo['url'])); if (!array_key_exists($ur, $this->reports)) { @@ -2746,10 +2828,8 @@ public function error500Reporter($errorResponse) { $curlname = $tmpdir . '/curl-' . $this->evidence . '-' . $myTime . '.json'; file_put_contents($curlname, json_encode($this->curlInfo, JSON_PRETTY_PRINT)); - $report = new \Ease\Mailer($this->reportRecipient, 'Error report 500 - ' . $ur); - $d = dir($tmpdir); while (false !== ($entry = $d->read())) { if (strstr($entry, $myTime)) { @@ -2760,7 +2840,6 @@ public function error500Reporter($errorResponse) { } } $d->close(); - if ((strstr($this->url, '://localhost') || strstr($this->url, '://127.')) && file_exists('/var/log/flexibee.log')) { @@ -2792,10 +2871,8 @@ public function error500Reporter($errorResponse) { } $licenseInfo = $this->performRequest($this->url . '/default-license.json'); - $report->addItem("\n\n" . json_encode($licenseInfo['license'], JSON_PRETTY_PRINT)); - if ($report->send()) { $this->reports[$ur] = $myTime; } @@ -2809,7 +2886,8 @@ public function error500Reporter($errorResponse) { * * @return string */ - public static function code(string $code) { + public static function code(string $code) + { return ((substr($code, 0, 4) == 'ext:') ? $code : 'code:' . strtoupper(self::uncode($code))); } @@ -2820,7 +2898,8 @@ public static function code(string $code) { * * @return string */ - public static function uncode(string $code) { + public static function uncode(string $code) + { return str_replace(['code:', 'code%3A'], '', $code); } @@ -2831,7 +2910,8 @@ public static function uncode(string $code) { * * @return array data without @ columns */ - public static function arrayCleanUP(array $data) { + public static function arrayCleanUP(array $data) + { return array_filter( $data, function ($key) { @@ -2845,7 +2925,8 @@ function ($key) { * @param string $prefix banner prefix text * @param string $suffix banner suffix text */ - public function logBanner($prefix = null, $suffix = null) { + public function logBanner($prefix = null, $suffix = null) + { parent::logBanner($prefix, 'ServerURL ' . str_replace('://', '://' . $this->user . '@', $this->getApiUrl()) . ' php-abraflexi v' . self::$libVersion . ' (AbraFlexi ' . EvidenceList::$version . ')', $suffix); @@ -2856,7 +2937,8 @@ public function logBanner($prefix = null, $suffix = null) { * * @return string create|read|update|delete or update,insert for some inserted and updated in one transaction */ - public function getLastOperationType() { + public function getLastOperationType() + { return implode(',', array_keys(array_filter($this->responseStats))); } @@ -2865,15 +2947,16 @@ public function getLastOperationType() { * * @return array AbraFlexi error meassages */ - public function getErrors() { + public function getErrors() + { return $this->errors; } /** * Reconnect After unserialization */ - public function __wakeup() { + public function __wakeup() + { $this->curlInit(); } - } diff --git a/src/AbraFlexi/RW.php b/src/AbraFlexi/RW.php index 7503aa6c..09b15a1c 100644 --- a/src/AbraFlexi/RW.php +++ b/src/AbraFlexi/RW.php @@ -16,7 +16,8 @@ * * @url https://demo.flexibee.eu/devdoc/http-operations */ -class RW extends RO { +class RW extends RO +{ /** * Sloupeček obsahující datum vložení záznamu do shopu. @@ -61,18 +62,32 @@ class RW extends RO { */ private $sourceId = null; + /** + * Dry Run mode indicator + * + * @link https://podpora.flexibee.eu/cs/articles/4720123-testovaci-ulozeni-dry-run + * + * @var boolean + */ + public $dryRun = false; + /** * SetUp Object to be ready for work * * @param array $options Object Options (authSessionId,user,password, * url,company,evidence,companyUrl - * prefix,defaultUrlParams,debug,ver + * prefix,defaultUrlParams,debug,ver,dry-run * detail,offline,atomic,filter,ignore404 */ - public function setUp($options = array()) { + public function setUp($options = array()) + { if (array_key_exists('atomic', $options)) { $this->atomic = (boolean) $options['atomic']; } + if (array_key_exists('dry-run', $options)) { + $this->dryRun = boolval($options['dry-run']); + $this->defaultUrlParams['dry-run'] = $this->dryRun ? 'true' : 'false'; + } return parent::setUp($options); } @@ -85,12 +100,15 @@ public function setUp($options = array()) { * * @return array odpověď */ - public function insertToAbraFlexi($data = null) { + public function insertToAbraFlexi($data = null) + { if (is_null($data)) { $data = $this->getData(); } - $this->postFields = $this->getJsonizedData($data, - $this->debug ? JSON_PRETTY_PRINT : 0); + $this->postFields = $this->getJsonizedData( + $data, + $this->debug ? JSON_PRETTY_PRINT : 0 + ); return $this->performRequest('', 'PUT'); } @@ -102,13 +120,20 @@ public function insertToAbraFlexi($data = null) { * * @return array main data part of response */ - public function parseResponse($responseDecoded, $responseCode) { + public function parseResponse($responseDecoded, $responseCode) + { $parsedData = parent::parseResponse($responseDecoded, $responseCode); switch ($responseCode) { + case 200: //The Dry Run response + if ($this->dryRun === false) { + break; // Read operation does not return results + } case 201: //Success Write if (is_array($responseDecoded)) { - $this->responseStats = array_key_exists('stats', - $responseDecoded) ? (isset($responseDecoded['stats'][0]) ? array_map('intval', $responseDecoded['stats'][0]) : array_map('intval', $responseDecoded['stats'])) : null; + $this->responseStats = array_key_exists( + 'stats', + $responseDecoded + ) ? (isset($responseDecoded['stats'][0]) ? array_map('intval', $responseDecoded['stats'][0]) : array_map('intval', $responseDecoded['stats'])) : null; if (isset($responseDecoded[$this->resultField][0]['id'])) { $this->lastInsertedID = intval($responseDecoded[$this->resultField][0]['id']); $this->setMyKey($this->lastInsertedID); @@ -131,7 +156,8 @@ public function parseResponse($responseDecoded, $responseCode) { * * @return int number of errors processed */ - public function parseError(array $responseDecoded) { + public function parseError(array $responseDecoded) + { if (array_key_exists('results', $responseDecoded)) { if (array_key_exists(0, $responseDecoded['results'])) { @@ -175,7 +201,8 @@ public function parseError(array $responseDecoded) { * * @param array $candidates AbraFlexi insert IDs prepared by extractResultIDs() */ - public function assignResultIDs($candidates) { + public function assignResultIDs($candidates) + { foreach ($this->chained as $chid => $chained) { $chainedEvidence = $chained->getEvidence(); $chainedExtid = $chained->getRecordID(); @@ -205,7 +232,8 @@ public function assignResultIDs($candidates) { * * @return array List of [ 'evidence1'=>[ 'original-id'=>numericID,'original-id2'=>numericID2 ], 'evidence2'=> ... ] */ - public function extractResultIDs($resultInfo) { + public function extractResultIDs($resultInfo) + { $candidates = []; foreach ($resultInfo as $insertResult) { $newID = $insertResult['id']; @@ -225,7 +253,8 @@ public function extractResultIDs($resultInfo) { * * @return int */ - public function getLastInsertedId() { + public function getLastInsertedId() + { return $this->lastInsertedID; } @@ -237,13 +266,16 @@ public function getLastInsertedId() { * * @return boolean Response code is 200 ? */ - public function deleteFromAbraFlexi($id = null) { + public function deleteFromAbraFlexi($id = null) + { if (is_null($id)) { $id = $this->getRecordIdent(); } - $this->performRequest($this->getEvidenceUrl() . '/' . self::urlizeId($id), - 'DELETE'); + $this->performRequest( + $this->getEvidenceUrl() . '/' . self::urlizeId($id), + 'DELETE' + ); return $this->lastResponseCode == 200; } @@ -254,7 +286,8 @@ public function deleteFromAbraFlexi($id = null) { * * @return int number of records taken */ - public function takeData($data) { + public function takeData($data) + { if ($this->debug === true) { $fbRelations = []; $fbColumns = $this->getColumnsInfo(); @@ -288,7 +321,8 @@ public function takeData($data) { * * @return array List of missing columns. Empty if all is ok */ - public function controlMandatoryColumns($data = null) { + public function controlMandatoryColumns($data = null) + { if (is_null($data)) { $data = $this->getData(); } @@ -314,7 +348,8 @@ public function controlMandatoryColumns($data = null) { * * @return array List of ReadOnly columns. Empty if all is ok */ - public function controlReadOnlyColumns($data = null) { + public function controlReadOnlyColumns($data = null) + { if (is_null($data)) { $data = $this->getData(); } @@ -340,9 +375,10 @@ public function controlReadOnlyColumns($data = null) { * * @param int $timpestamp * - * @return AbraFlexi\ Date or NULL + * @return \AbraFlexi\ Date or NULL */ - public static function timestampToFlexiDate($timpestamp = null) { + public static function timestampToFlexiDate($timpestamp = null) + { $flexiDate = new Date(); if (!is_null($timpestamp)) { $flexiDate->setTimestamp($timpestamp); @@ -357,7 +393,8 @@ public static function timestampToFlexiDate($timpestamp = null) { * * @return string AbraFlexi DateTime or NULL */ - public static function timestampToFlexiDateTime($timpestamp = null) { + public static function timestampToFlexiDateTime($timpestamp = null) + { $flexiDateTime = null; if (!is_null($timpestamp)) { $date = new \DateTime(); @@ -381,13 +418,20 @@ public static function timestampToFlexiDateTime($timpestamp = null) { * * @return boolean Operation success */ - public function addArrayToBranch($data, $relationPath = 'polozkyDokladu', - $removeAll = false) { + public function addArrayToBranch( + $data, + $relationPath = 'polozkyDokladu', + $removeAll = false + ) { $currentBranchData = $this->getDataValue($relationPath); $branchData = $currentBranchData; $branchData[] = $data; - if (is_array($this->getEvidence()) && array_key_exists('bezPolozek', - $this->getColumnsInfo())) { + if ( + is_array($this->getEvidence()) && array_key_exists( + 'bezPolozek', + $this->getColumnsInfo() + ) + ) { $this->setDataValue('bezPolozek', false); } if ($removeAll === true) { @@ -402,9 +446,13 @@ public function addArrayToBranch($data, $relationPath = 'polozkyDokladu', * @param AbraFlexiRO $object objekt evidence * @param boolean $removeAll flush older items */ - public function addObjectToBranch($object, $removeAll = false) { - $this->addArrayToBranch([$object->getEvidence() => $object->getData()], - 'polozkyDokladu', $removeAll); + public function addObjectToBranch($object, $removeAll = false) + { + $this->addArrayToBranch( + [$object->getEvidence() => $object->getData()], + 'polozkyDokladu', + $removeAll + ); } /** @@ -413,9 +461,12 @@ public function addObjectToBranch($object, $removeAll = false) { * @see https://www.abraflexi.eu/api/dokumentace/ref/uzivatelske-vazby/ * @param string $vazba */ - public function vazbaAdd($vazba) { - $this->addArrayToBranch(['uzivatelska-vazba' => $vazba], - 'uzivatelske-vazby'); + public function vazbaAdd($vazba) + { + $this->addArrayToBranch( + ['uzivatelska-vazba' => $vazba], + 'uzivatelske-vazby' + ); } /** @@ -424,10 +475,13 @@ public function vazbaAdd($vazba) { * @see https://www.abraflexi.eu/api/dokumentace/ref/uzivatelske-vazby/ * @param string $vazba */ - public function vazbaDel($vazba) { + public function vazbaDel($vazba) + { $this->setDataValue('uzivatelska-vazba@action', 'delete'); - $this->addArrayToBranch(['uzivatelska-vazba' => $vazba], - 'uzivatelske-vazby'); + $this->addArrayToBranch( + ['uzivatelska-vazba' => $vazba], + 'uzivatelske-vazby' + ); } /** @@ -441,7 +495,8 @@ public function vazbaDel($vazba) { * * @return string */ - public function getJsonizedData($data = null, $options = 0) { + public function getJsonizedData($data = null, $options = 0) + { if (is_null($data)) { $data = $this->getData(); } @@ -462,7 +517,8 @@ public function getJsonizedData($data = null, $options = 0) { * * @return array */ - public function getDataForJSON($data = null) { + public function getDataForJSON($data = null) + { if (is_null($data)) { $data = $this->getData(); } @@ -484,14 +540,15 @@ public function getDataForJSON($data = null) { * * @return boolean Operation success */ - public function sync($data = null) { + public function sync($data = null) + { $this->insertToAbraFlexi($data); $insertResult = $this->lastResponseCode; if ($insertResult == 201) { $this->reload(); } $loadResult = $this->lastResponseCode; - return ($insertResult + $loadResult) == 401; + return $this->dryRun ? $insertResult == 200 : ($insertResult + $loadResult) == 401; } /** @@ -504,7 +561,8 @@ public function sync($data = null) { * * @return RW|null copied record object or null in case of failure */ - public function copy($source, $overrides = []) { + public function copy($source, $overrides = []) + { $this->sourceId = $source; return $this->sync($overrides) ? $this : null; } @@ -519,11 +577,16 @@ public function copy($source, $overrides = []) { * * @return boolean operation success */ - public function performAction(string $action, $method = 'int') { + public function performAction(string $action, $method = 'int') + { $actionsAvailble = $this->getActionsInfo(); - if (is_array($actionsAvailble) && array_key_exists($action, - $actionsAvailble)) { + if ( + is_array($actionsAvailble) && array_key_exists( + $action, + $actionsAvailble + ) + ) { switch ($actionsAvailble[$action]['actionMakesSense']) { case 'ONLY_WITH_INSTANCE_AND_NOT_IN_EDIT': case 'ONLY_WITH_INSTANCE': //Add instance @@ -544,14 +607,21 @@ public function performAction(string $action, $method = 'int') { break; default: - $result = $this->performRequest($this->evidenceUrlWithSuffix($urlSuffix), - 'GET'); + $result = $this->performRequest( + $this->evidenceUrlWithSuffix($urlSuffix), + 'GET' + ); break; } } else if ($this->throwException === true) { $this->lastResponseCode = 404; - throw new Exception(sprintf(_('Unsupported action "%s" for evidence "%s"'), - $action, $this->getEvidence()), $this); + throw new Exception( + sprintf( + _('Unsupported action "%s" for evidence "%s"'), + $action, $this->getEvidence() + ), + $this + ); } return $result; @@ -564,9 +634,17 @@ public function performAction(string $action, $method = 'int') { * * @return array Insert result */ - public function addExternalID($extId) { - return $this->insertToAbraFlexi(['id' => [$this->getRecordID(), 'ext:' . preg_replace('/^ext:/', - '', $extId)]]); + public function addExternalID($extId) + { + return $this->insertToAbraFlexi([ + 'id' => [ + $this->getRecordID(), 'ext:' . preg_replace( + '/^ext:/', + '', + $extId + ) + ] + ]); } /** @@ -578,10 +656,13 @@ public function addExternalID($extId) { * * @return array operation result */ - public function changeExternalID($selector, $newValue, $forID = null) { + public function changeExternalID($selector, $newValue, $forID = null) + { $change['@removeExternalIds'] = 'ext:' . $selector . ':'; - $change['id'] = [is_null($forID) ? $this->getRecordID() : $forID, - 'ext:' . $selector . ':' . $newValue]; + $change['id'] = [ + is_null($forID) ? $this->getRecordID() : $forID, + 'ext:' . $selector . ':' . $newValue + ]; return $this->insertToAbraFlexi($change); } @@ -592,7 +673,8 @@ public function changeExternalID($selector, $newValue, $forID = null) { * * @return int http response code */ - public function sendUnsent() { + public function sendUnsent() + { $this->performRequest('automaticky-odeslat-neodeslane', 'PUT', 'xml'); return $this->lastResponseCode == 202; } @@ -602,10 +684,10 @@ public function sendUnsent() { */ public function setDataValue(string $columnName, $value) { - if($this->debug === true){ + if ($this->debug === true) { $columnInfo = $this->getColumnInfo($columnName); if ($columnInfo) { - if (array_key_exists('maxLength', $columnInfo) && (mb_strlen((string)$value) > $columnInfo['maxLength'])) { + if (array_key_exists('maxLength', $columnInfo) && (mb_strlen((string) $value) > $columnInfo['maxLength'])) { $this->addStatusMessage($value . ' is too long. Shorting to ' . $columnInfo['maxLength'] . ' characters', 'warning'); $value = substr($value, 0, intval($columnInfo['maxLength'])); } @@ -613,5 +695,5 @@ public function setDataValue(string $columnName, $value) } return parent::setDataValue($columnName, $value); } - -} + +} \ No newline at end of file diff --git a/testing/bootstrap.php b/testing/bootstrap.php index 73f7c838..d4c9e0c4 100644 --- a/testing/bootstrap.php +++ b/testing/bootstrap.php @@ -4,7 +4,7 @@ * AbraFlexi - nastavení testů. * * @author Vítězslav Dvořák - * @copyright 2015-2020 Spoje.Net + * @copyright 2015-2023 Spoje.Net */ /** * Predefined server:One of: