sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
function paymentButton(Payment $payment, $brand = "csob", $extensions = array()) {
$payId = $payment->getPayId();
if (!$payId) {
throw new Exception('Given Payment object does not have a PayId. Please provide a Payment object that was returned from paymentInit() method.');
}
$payload = array(
"merchantId" => $this->config->merchantId,
"payId" => $payId,
"brand" => $brand,
"dttm" => $this->getDTTM(),
);
$this->writeToLog("payment/button started with PayId $payId");
try {
$payload["signature"] = $this->signRequest($payload);
$ret = $this->sendRequest(
"payment/button",
$payload,
"POST",
array("payId", "dttm", "resultCode", "resultMessage", "redirect"),
array("merchantId", "payId", "brand", "dttm", "signature"),
false,
false,
$extensions
);
} catch (Exception $e) {
$this->writeToLog("Fail, got exception: " . $e->getCode().", " . $e->getMessage());
throw $e;
}
$this->writeToLog("payment/button OK");
return $ret;
}
|
Performs a payment/button API call.
You need a Payment object that was already processed via paymentInit() method
(or was injected with a payId that you received from other source).
In response, you'll receive an array with [redirect], which should be
another array with [method] and [url] items. Redirect your user to that address
to complete the payment.
@param Payment $payment
@param string $brand "csob" or "era"
@param Extension[]|Extension $extensions
@return array|string
|
entailment
|
function customRequest($methodUrl, $inputPayload, $expectedOutputFields = array(), $extensions = array(), $method = "POST", $logOutput = false, $ignoreInvalidReturnSignature = false) {
if (array_key_exists('dttm', $inputPayload) and !$inputPayload['dttm']) {
$inputPayload['dttm'] = $this->getDTTM();
}
if (array_key_exists('merchantId', $inputPayload) and !$inputPayload['merchantId']) {
$inputPayload['merchantId'] = $this->config->merchantId;
}
$signature = $this->signRequest($inputPayload);
$inputPayload['signature'] = $signature;
$this->writeToLog("custom request to $methodUrl - start");
try {
$ret = $this->sendRequest(
$methodUrl,
$inputPayload,
$method,
$expectedOutputFields,
array_keys($inputPayload),
false,
$ignoreInvalidReturnSignature,
$extensions
);
} catch (Exception $e) {
$this->writeToLog("Fail, got exception: " . $e->getCode().", " . $e->getMessage());
throw $e;
}
$this->writeToLog("custom request to $methodUrl - OK");
if ($logOutput) {
$this->writeToTraceLog(print_r($ret, true));
}
return $ret;
}
|
Sends an arbitrary request to bank's API with any parameters.
Use this method to call various masterpass/* API methods or any methods of
API versions that may come in future and are not implemented in this library yet.
$inputPayload is an associative array with data in order in which they should be signed.
You can leave *dttm* and *merchantId* empty or null, their values will be filled automatically,
however you can't omit them completely, since they are required in the signature.
Signature field will be added automatically.
$expectedOutputFields should be ordinary array of field names in order they appear in the response.
Their order in the array is important to verify response signature. You can leave this empty, the
base string will be created on order as the keys appear in the response. However, it can't be guaranteed
it is the correct order. If you want it to be more reliable, I recommend to define it.
Example - testing post connection:
```php
$client->customRequest(
'echo',
array(
'merchantId' => null,
'dttm' => null
)
);
```
@param string $methodUrl API method name, without leading slash, ie. "payment/init"
@param array $inputPayload Input payload in form of associative array. Order of items is significant.
@param array $expectedOutputFields Expected field names of response in order in which they should be returned.
@param Extension[]|Extension $extensions
@param string $method HTTP method
@param bool $logOutput Should be the complete output logged into debug log?
@param bool $ignoreInvalidReturnSignature If set to true, then in case of invalid signature of returned data,
no exception will be thrown and method will return received data as usual. Then, you should handle the situation by yourself.
Do not use this option on regular basis, it is intended only as workaround for cases when returned data or its signature is more complex
and its verification fails for some reason.
@return array|string
|
entailment
|
function customerInfo($customerId, $returnIfHasCardsOnly = true) {
$customerId = $this->getCustomerId($customerId);
$this->writeToLog("customer/info started for customer $customerId");
if (!$customerId) {
$this->writeToLog("no customer Id give, aborting");
return null;
}
$payload = array(
"merchantId" => $this->config->merchantId,
"customerId" => $customerId,
"dttm" => $this->getDTTM()
);
$payload["signature"] = $this->signRequest($payload);
$result = 0;
$resMessage = "";
try {
$ret = $this->sendRequest(
"customer/info",
$payload,
"GET",
array("customerId", "dttm", "resultCode", "resultMessage"),
array("merchantId", "customerId", "dttm", "signature")
);
} catch (Exception $e) {
// Valid call returns non-0 resultCode, which leads to exception
$resMessage = $e->getMessage();
switch ($e->getCode()) {
case self::CUST_CARDS:
case self::CUST_NO_CARDS:
case self::CUST_NOT_FOUND:
$result = $e->getCode();
break;
default:
throw $e;
// this is really some error
}
}
$this->writeToLog("Result: $result, $resMessage");
if ($returnIfHasCardsOnly) {
return ($result == self::CUST_CARDS);
}
return $result;
}
|
Performs customer/info API call.
Use this method to check if customer with given ID has any saved cards.
If he does, you can show some icon or change default payment method in
e-shop or do some other action. This is just an auxiliary method and
is not neccessary at all.
@param string|array|Payment $customerId Customer ID, Payment object or array
as returned from paymentInit
@param bool $returnIfHasCardsOnly
@return bool|int If $returnIfHasCardsOnly is set to true, method returns
boolean indicating whether given customerID has any saved cards. If it is
set to false, then method returns one of CUSTOMER_*** constants which can
be used to distinguish more precisely whether customer just hasn't saved
any cards or was not found at all.
|
entailment
|
function receiveReturningCustomer($input = null) {
$returnDataNames = array(
"payId",
"dttm",
"resultCode",
"resultMessage",
"paymentStatus",
"?authCode",
"merchantData",
// "signature"
);
if (!$input) {
if (isset($_GET["payId"])) $input = $_GET;
elseif (isset($_POST["payId"])) $input = $_POST;
}
if (!$input) {
return null;
}
$this->writeToTraceLog("Received data from returning customer: ".str_replace("\n", " ", print_r($input, true)));
$nullFields = array_fill_keys($returnDataNames, null);
$input += $nullFields;
$signatureOk = $this->verifyResponseSignature($input, $input["signature"], $returnDataNames);
if (!$signatureOk) {
$this->writeToTraceLog("Signature is invalid.");
$this->writeToLog("Returning customer: payId $input[payId], has invalid signature.");
throw new Exception("Signature is invalid.");
}
$merch = @base64_decode($input["merchantData"]);
if ($merch) {
$input["merchantData"] = $merch;
}
$mess = "Returning customer: payId ".$input["payId"].", authCode " . (isset($input["authCode"]) ? $input["authCode"] : '(not set)') . ", payment status ".$input["paymentStatus"];
if ($input["merchantData"]) {
$mess .= ", merchantData ".$input["merchantData"];
}
$this->writeToLog($mess);
return $input;
}
|
Processes the data that are sent together with customer when he
returns back from payment gateway.
Call this method on your returnUrl to extract all data from request,
validate signature, decode merchant data from base64 and return
it all as an array. Method automatically reads data from GET or POST.
@param array|null $input If return data is not in GET or POST, supply
your own array with accordingly named variables.
@return array|null Array with received data or null if no data is present.
@throws Exception When data is present but signature is incorrect.
|
entailment
|
function setLog($log) {
if (!$log) {
$this->logFile = null;
$this->logCallback = null;
} elseif (is_callable($log)) {
$this->logFile = null;
$this->logCallback = $log;
} else {
Files::create($log);
$this->logFile = $log;
$this->logCallback = null;
}
return $this;
}
|
Sets logging for bussiness-logic level messages.
@param string|callback $log String filename or callback that forwards
messages to your own logging system.
@return Client
|
entailment
|
function setTraceLog($log) {
if (!$log) {
$this->traceLogFile = null;
$this->traceLogCallback = null;
} elseif (is_callable($log)) {
$this->traceLogFile = null;
$this->traceLogCallback = $log;
} else {
Files::create($log);
$this->traceLogFile = $log;
$this->traceLogCallback = null;
}
return $this;
}
|
Sets logging for exact contents of communication
@param string|callback $log String filename or callback that forwards
messages to your own logging system.
@return Client
|
entailment
|
function writeToLog($message) {
if ($this->logFile) {
$timestamp = date("Y-m-d H:i:s");
$timestamp = str_pad($timestamp, 20);
if (isset($_SERVER["REMOTE_ADDR"])) {
$ip = $_SERVER["REMOTE_ADDR"];
} else {
$ip = "Unknown IP";
}
$ip = str_pad($ip, 15);
$taggedMessage = "$timestamp $ip $message\n";
file_put_contents($this->logFile, $taggedMessage, FILE_APPEND);
}
if ($this->logCallback) {
call_user_func_array($this->logCallback, array($message));
}
}
|
@ignore
@param string $message
|
entailment
|
function writeToTraceLog($message) {
if ($this->traceLogFile) {
$timestamp = date("Y-m-d H:i:s");
$timestamp = str_pad($timestamp, 20);
if (isset($_SERVER["REMOTE_ADDR"])) {
$ip = $_SERVER["REMOTE_ADDR"];
} else {
$ip = "Unknown IP";
}
$ip = str_pad($ip, 15);
$taggedMessage = "$timestamp $ip $message\n";
file_put_contents($this->traceLogFile, $taggedMessage, FILE_APPEND);
}
if ($this->traceLogCallback) {
call_user_func_array($this->traceLogCallback, array($message));
}
}
|
@ignore
@param string $message
|
entailment
|
protected function getPayId($payment) {
if (!is_string($payment) and $payment instanceof Payment) {
$payment = $payment->getPayId();
if (!$payment) {
throw new Exception("Given Payment object does not have payId. Please call paymentInit() first.");
}
}
if (is_array($payment) and isset($payment["payId"])) {
$payment = $payment["payId"];
}
if (!is_string($payment) or strlen($payment) != 15) {
throw new Exception("Given Payment ID is not valid - it should be a string with length 15 characters.");
}
return $payment;
}
|
Get payId as string and validate it.
@ignore
@param Payment|string|array $payment String, Payment object or array as returned from paymentInit call
@return string
@throws Exception
|
entailment
|
protected function getCustomerId($payment) {
if (!is_string($payment) and $payment instanceof Payment) {
$payment = $payment->customerId;
}
if (is_array($payment) and isset($payment["customerId"])) {
$payment = $payment["customerId"];
}
if (!is_string($payment)) {
throw new Exception("Given Customer ID is not valid.");
}
return $payment;
}
|
Get customerId as string and validate it.
@ignore
@param Payment|string|array $payment String, Payment object or array as returned from paymentInit call
@return string
@throws Exception
|
entailment
|
protected function signRequest($arrayToSign) {
$stringToSign = Crypto::createSignatureBaseFromArray($arrayToSign);
$keyFile = $this->config->privateKeyFile;
$signature = Crypto::signString(
$stringToSign,
$keyFile,
$this->config->privateKeyPassword
);
$this->writeToTraceLog("Signing string \"$stringToSign\" using key $keyFile, result: ".$signature);
return $signature;
}
|
Signs array payload
@param array $arrayToSign
@return string Base64 encoded signature
@ignore
|
entailment
|
protected function sendRequest(
$apiMethod,
$payload,
$usePostMethod = true,
$responseFieldsOrder = null,
$requestFieldsOrder = null,
$returnUrlOnly = false,
$allowInvalidReturnSignature = false,
$extensions = array()
) {
$url = $this->getApiMethodUrl($apiMethod);
$method = $usePostMethod;
$this->writeToTraceLog("Will send request to method $apiMethod");
if (!$usePostMethod or $usePostMethod === "GET") {
$method = "GET";
if (!$requestFieldsOrder) {
$requestFieldsOrder = $responseFieldsOrder;
}
$parametersToUrl = $requestFieldsOrder ? $requestFieldsOrder : array_keys($payload);
foreach($parametersToUrl as $param) {
if (isset($payload[$param])) {
$url .= "/" . urlencode($payload[$param]);
}
}
}
if ($method === true) {
$method = "POST";
}
if ($extensions) {
$extensions = Arrays::arrayize($extensions);
}
if ($extensions) {
$payload["extensions"] = array();
/** @var Extension $extension */
foreach ($extensions as $extension) {
if (!($extension instanceof Extension)) {
throw new Exception('Given argument is not Extension object.');
}
$addedData = $extension->createRequestArray($this);
if ($addedData) {
$payload["extensions"][] = $addedData;
}
}
}
if ($returnUrlOnly) {
$this->writeToTraceLog("Returned final URL: " . $url);
return $url;
}
$ch = \curl_init($url);
$this->writeToTraceLog("URL to send request to: " . $url);
if ($method === "POST" or $method === "PUT") {
$encodedPayload = json_encode($payload);
if (json_last_error()) {
$msg = 'Request data could not be encoded to JSON: ' . json_last_error();
if (function_exists('json_last_error_msg')) {
$msg .= ' - ' . json_last_error_msg();
}
$this->writeToTraceLog($msg);
throw new Exception($msg, 1);
}
$this->writeToTraceLog("JSON payload: ".$encodedPayload);
\curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
\curl_setopt($ch, CURLOPT_POSTFIELDS, $encodedPayload);
}
if (!$this->config->sslCertificatePath) {
\curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
} else {
if (is_dir($this->config->sslCertificatePath)) {
\curl_setopt($ch, CURLOPT_CAPATH, $this->config->sslCertificatePath);
} else {
\curl_setopt($ch, CURLOPT_CAINFO, $this->config->sslCertificatePath);
}
}
\curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
\curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json;charset=UTF-8'
));
$result = \curl_exec($ch);
if (\curl_errno($ch)) {
$this->writeToTraceLog("CURL failed: " . \curl_errno($ch) . " " . \curl_error($ch));
throw new Exception("Failed sending data to API: ".\curl_errno($ch)." ".\curl_error($ch));
}
$this->writeToTraceLog("API response: $result");
$httpCode = \curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode != 200) {
$this->writeToTraceLog("Failed: returned HTTP code $httpCode");
throw new Exception(
"API returned HTTP code $httpCode, which is not code 200."
. ($httpCode == 400 ? " Probably wrong signature, check crypto keys." : "")
);
}
\curl_close($ch);
$decoded = @json_decode($result, true);
if ($decoded === null) {
$this->writeToTraceLog("Failed: returned value is not parsable JSON");
throw new Exception("API did not return a parseable JSON string: \"".$result."\"");
}
if (!isset($decoded["resultCode"])) {
$this->writeToTraceLog("Failed: API did not return response with resultCode");
throw new Exception("API did not return a response containing resultCode.");
}
if (!isset($decoded["signature"]) or !$decoded["signature"]) {
$this->writeToTraceLog("Failed: missing response signature");
throw new Exception("Result does not contain signature.");
}
$signature = $decoded["signature"];
try {
$verificationResult = $this->verifyResponseSignature($decoded, $signature, $responseFieldsOrder);
} catch (Exception $e) {
$this->writeToTraceLog("Failed: error occured when verifying signature.");
throw $e;
}
if (!$verificationResult) {
if (!$allowInvalidReturnSignature) {
$this->writeToTraceLog("Failed: signature is incorrect.");
throw new Exception("Result signature is incorrect. Please make sure that bank's public key in file specified in config is correct and up-to-date.");
} else {
$this->writeToTraceLog("Signature is incorrect, but method was called with \$allowInvalidReturnSignature = true, so we'll ignore it.");
}
}
if ($decoded["resultCode"] != "0") {
$this->writeToTraceLog("Failed: resultCode ".$decoded["resultCode"].", message ".$decoded["resultMessage"]);
throw new Exception("API returned an error: resultCode \"" . $decoded["resultCode"] . "\", resultMessage: ".$decoded["resultMessage"], $decoded["resultCode"]);
}
if ($extensions) {
$extensionsById = array();
foreach ($extensions as $extension) {
$extensionsById[$extension->getExtensionId()] = $extension;
}
$extensionsDataDecoded = isset($decoded["extensions"]) ? $decoded["extensions"] : array();
foreach ($extensionsDataDecoded as $extensionData) {
$extensionId = $extensionData['extension'];
if (isset($extensionsById[$extensionId])) {
/** @var Extension $extensionObject */
$extensionObject = $extensionsById[$extensionId];
$extensionObject->setResponseData($extensionData);
$signatureResult = $extensionObject->verifySignature($extensionData, $this);
if (!$signatureResult) {
$this->writeToTraceLog("Signature of extension $extensionId is incorrect.");
if ($extension->getStrictSignatureVerification()) {
throw new Exception("Result signature of extension $extensionId is incorrect. Please make sure that bank's public key in file specified in config is correct and up-to-date.");
} else {
$extension->setSignatureCorrect(false);
}
} else {
$extension->setSignatureCorrect(true);
}
}
}
}
$this->writeToTraceLog("OK");
return $decoded;
}
|
Send prepared request.
@param string $apiMethod
@param array $payload
@param bool|string $usePostMethod True = post, false = get, string = exact method
@param array $responseFieldsOrder
@param array $requestFieldsOrder
@param bool $returnUrlOnly
@param bool $allowInvalidReturnSignature Set to true if you want to ignore the fact
that the signature of returned data was incorrect, so that you can receive the returned data anyway
and handle the situation by yourself. If false, an exception will be thrown instead of returning the received data.
@param Extension[]|Extension $extensions
@return array|string
@ignore
|
entailment
|
public function asArray() {
$a = array();
$a['premiseId'] = +$this->premiseId;
$a['cashRegisterId'] = $this->cashRegisterId;
$a['totalPrice'] = self::formatPriceValue($this->totalPrice);
if ($this->delegatedVatId) {
$a['delegatedVatId'] = $this->delegatedVatId;
}
if ($this->priceZeroVat) {
$a['priceZeroVat'] = self::formatPriceValue($this->priceZeroVat);
}
if ($this->priceStandardVat) {
$a['priceStandardVat'] = self::formatPriceValue($this->priceStandardVat);
}
if ($this->vatStandard) {
$a['vatStandard'] = self::formatPriceValue($this->vatStandard);
}
if ($this->priceFirstReducedVat) {
$a['priceFirstReducedVat'] = self::formatPriceValue($this->priceFirstReducedVat);
}
if ($this->vatFirstReduced) {
$a['vatFirstReduced'] = self::formatPriceValue($this->vatFirstReduced);
}
if ($this->priceSecondReducedVat) {
$a['priceSecondReducedVat'] = self::formatPriceValue($this->priceSecondReducedVat);
}
if ($this->vatSecondReduced) {
$a['vatSecondReduced'] = self::formatPriceValue($this->vatSecondReduced);
}
if ($this->priceTravelService) {
$a['priceTravelService'] = self::formatPriceValue($this->priceTravelService);
}
if ($this->priceUsedGoodsStandardVat) {
$a['priceUsedGoodsStandardVat'] = self::formatPriceValue($this->priceUsedGoodsStandardVat);
}
if ($this->priceUsedGoodsFirstReduced) {
$a['priceUsedGoodsFirstReduced'] = self::formatPriceValue($this->priceUsedGoodsFirstReduced);
}
if ($this->priceUsedGoodsSecondReduced) {
$a['priceUsedGoodsSecondReduced'] = self::formatPriceValue($this->priceUsedGoodsSecondReduced);
}
if ($this->priceSubsequentSettlement) {
$a['priceSubsequentSettlement'] = self::formatPriceValue($this->priceSubsequentSettlement);
}
if ($this->priceUsedSubsequentSettlement) {
$a['priceUsedSubsequentSettlement'] = self::formatPriceValue($this->priceUsedSubsequentSettlement);
}
return $a;
}
|
Export as array
@return array
|
entailment
|
static function fromArray($array) {
$data = new EETData();
foreach (self::$keyNames as $key) {
if (array_key_exists($key, $array)) {
$data->$key = $array[$key];
}
}
$data->rawData = $array;
return $data;
}
|
Creates EETData object from array received from API
@param $array
@return EETData
|
entailment
|
public function getInputData() {
$a = array(
'extension' => $this->extensionId,
'dttm' => null,
'data' => $this->data->asArray(),
'verificationMode' => $this->verificationMode ? 'true' : 'false'
);
return $a;
}
|
Builds input data array
@return array
|
entailment
|
public function createRequestArray(Client $client) {
$sourceArray = $this->getInputData();
if (!$sourceArray) {
return null;
}
$config = $client->getConfig();
/*
if (!array_key_exists('dttm', $sourceArray)) {
$sourceArray = array(
'dttm' => $this->getDTTM()
) + $sourceArray;
} elseif (!$sourceArray['dttm']) {
$sourceArray['dttm'] = $this->getDTTM();
}
if (!array_key_exists('extension', $sourceArray)) {
$sourceArray = array(
'extension' => $this->getExtensionId()
) + $sourceArray;
} elseif (!$sourceArray['extension']) {
$sourceArray['extension'] = $this->getExtensionId();
}*/
if (array_key_exists('dttm', $sourceArray) and !$sourceArray['dttm']) {
$sourceArray['dttm'] = $client->getDTTM();
}
if (array_key_exists('extension', $sourceArray) and !$sourceArray['extension']) {
$sourceArray['extension'] = $this->getExtensionId();
}
$baseString = $this->getRequestSignatureBase($sourceArray);
$client->writeToTraceLog('Signing request of extension ' . $this->extensionId . ', base string is:' . "\n" . $baseString);
$signature = Crypto::signString($baseString, $config->privateKeyFile, $config->privateKeyPassword);
$sourceArray['signature'] = $signature;
return $sourceArray;
}
|
Creates array for request.
If requests for your extension are signed incorrectly because of
wrong order of parts of the base string, check that order of keys in
your input data given to setInputData() is the same as in extension's documentation on CSOB wiki,
or extend this class and reimplement getRequestSignatureBase() method.
@param Client $client
@return array
|
entailment
|
public function verifySignature($receivedData, Client $client) {
$signature = isset($receivedData['signature']) ? $receivedData['signature'] : '';
if (!$signature) {
return false;
}
$responseWithoutSignature = $receivedData;
unset($responseWithoutSignature["signature"]);
$baseString = $this->getResponseSignatureBase($responseWithoutSignature);
$config = $client->getConfig();
$client->writeToTraceLog('Verifying signature of response of extension ' . $this->extensionId . ', base string is:' . "\n" . $baseString);
return Crypto::verifySignature($baseString, $signature, $config->bankPublicKeyFile);
}
|
Verifies signature.
@param array $receivedData
@param Client $client
@return bool
|
entailment
|
public function getResponseSignatureBase($responseWithoutSignature) {
$keys = $this->getExpectedResponseKeysOrder();
if ($keys) {
$baseString = Crypto::createSignatureBaseWithOrder($responseWithoutSignature, $keys, false);
} else {
$baseString = Crypto::createSignatureBaseFromArray($responseWithoutSignature, false);
}
return $baseString;
}
|
Returns base string for verifying signature of response.
If verifying signature fails because its base string has parts
in incorrect order, check that the order of keys given to
setExpectedResponseKeysOrder() is the same as in CSOB wiki,
or reimplement this method with a better one.
@param array $responseWithoutSignature
@return string
|
entailment
|
public function getInputData() {
if ($this->data) {
return array(
'extension' => $this->extensionId,
'dttm' => null,
'data' => $this->data->asArray(),
);
}
return null;
}
|
Builds input data array
@return array
|
entailment
|
static public function fromArray($array) {
$status = new EETReport();
$status->rawData = $array;
if (array_key_exists('eetStatus', $array)) {
$status->eetStatus = $array['eetStatus'];
}
if (array_key_exists('data', $array)) {
$status->data = EETData::fromArray($array['data']);
}
if (array_key_exists('verificationMode', $array)) {
$status->verificationMode = $array['verificationMode'] ? true : false;
}
if (array_key_exists('vatId', $array)) {
$status->vatId = $array['vatId'];
}
if (array_key_exists('receiptNumber', $array)) {
$status->receiptNumber = $array['receiptNumber'];
}
if (array_key_exists('receiptTime', $array)) {
$status->receiptTime = new DateTime($array['receiptTime']);
}
if (array_key_exists('evidenceMode', $array)) {
$status->evidenceMode = $array['evidenceMode'];
}
if (array_key_exists('uuid', $array)) {
$status->uuid = $array['uuid'];
}
if (array_key_exists('sendTime', $array)) {
$status->sendTime = new DateTime($array['sendTime']);
}
if (array_key_exists('acceptTime', $array)) {
$status->acceptTime = new DateTime($array['acceptTime']);
}
if (array_key_exists('bkp', $array)) {
$status->bkp = $array['bkp'];
}
if (array_key_exists('pkp', $array)) {
$status->pkp = $array['pkp'];
}
if (array_key_exists('fik', $array)) {
$status->fik = $array['fik'];
}
if (array_key_exists('rejectTime', $array)) {
$status->rejectTime = new DateTime($array['rejectTime']);
}
if (array_key_exists('error', $array) and $array['error']) {
$status->error = new EETError($array['error']['code'], $array['error']['desc']);
}
if (array_key_exists('warning', $array) and is_array($array['warning'])) {
foreach ($array['warning'] as $warningData) {
$status->warning[] = new EETWarning($warningData['code'], $warningData['desc']);
}
}
return $status;
}
|
Creates an EETStatus object from received data array
@param array $array
@return EETReport
|
entailment
|
public function getSignatureBase() {
$fields = array();
if ($this->eetStatus !== null) {
$fields[] = $this->eetStatus;
}
if ($this->data) {
$fields[] = $this->data->getSignatureBase();
}
if ($this->verificationMode !== null) {
$fields[] = $this->verificationMode ? 'true' : 'false';
}
if ($this->vatId) {
$fields[] = $this->vatId;
}
if ($this->receiptNumber) {
$fields[] = $this->receiptNumber;
}
if ($this->receiptTime) {
if (isset($this->rawData['receiptTime']) and $this->rawData['receiptTime']) {
$fields[] = $this->rawData['receiptTime'];
} else {
$fields[] = self::formatTime($this->receiptTime);
}
}
if ($this->evidenceMode !== null) {
$fields[] = $this->evidenceMode;
}
if ($this->uuid !== null) {
$fields[] = $this->uuid;
}
if ($this->sendTime) {
if (isset($this->rawData['sendTime']) and $this->rawData['sendTime']) {
$fields[] = $this->rawData['sendTime'];
} else {
$fields[] = self::formatTime($this->sendTime);
}
}
if ($this->acceptTime) {
if (isset($this->rawData['acceptTime']) and $this->rawData['acceptTime']) {
$fields[] = $this->rawData['acceptTime'];
} else {
$fields[] = self::formatTime($this->acceptTime);
}
}
if ($this->bkp) {
$fields[] = $this->bkp;
}
if ($this->pkp) {
$fields[] = $this->pkp;
}
if ($this->fik) {
$fields[] = $this->fik;
}
if ($this->rejectTime) {
if (isset($this->rawData['rejectTime']) and $this->rawData['rejectTime']) {
$fields[] = $this->rawData['rejectTime'];
} else {
$fields[] = self::formatTime($this->rejectTime);
}
}
if ($this->error) {
$fields[] = $this->error->getSignatureBase();
}
if ($this->warning) {
foreach ($this->warning as $w) {
$fields[] = $w->getSignatureBase();
}
}
return implode('|', $fields);
}
|
@inheritdoc
@return string
|
entailment
|
public function setResponseData($data) {
$this->responseData = $data;
if (isset($data['report'])) {
$this->report = EETReport::fromArray($data['report']);
}
$this->cancels = array();
if (isset($data['cancel'])) {
foreach ($data['cancel'] as $cancel) {
$this->cancels[] = EETReport::fromArray($cancel);
}
}
}
|
@inheritdoc
@param array $data
@return void
|
entailment
|
public function getResponseSignatureBase($dataArray) {
$base = array();
$base[] = $dataArray['extension'];
$base[] = $dataArray['dttm'];
if ($this->report) {
$base[] = $this->report->getSignatureBase();
}
if ($this->cancels) {
foreach ($this->cancels as $cancel) {
$base[] = $cancel->getSignatureBase();
}
}
return implode('|', $base);
}
|
@inheritdoc
@param array $dataArray
@return string
|
entailment
|
function addCartItem($name, $quantity, $totalAmount, $description = "") {
if (count($this->cart) >= 2) {
throw new Exception("This version of banks's API supports only up to 2 cart items in single payment, you can't add any more items.");
}
if (!is_numeric($quantity) or $quantity < 1) {
throw new Exception("Invalid quantity: $quantity. It must be numeric and >= 1");
}
$name = trim(Strings::shorten($name, 20, "", true, true));
$description = trim(Strings::shorten($description, 40, "", true, true));
$this->cart[] = array(
"name" => $name,
"quantity" => $quantity,
"amount" => intval(round($totalAmount)),
"description" => $description
);
return $this;
}
|
Add one cart item.
You are required to add one or two cart items (at least on API v1).
Remember that $totalAmount must be given in **hundredth of currency units**
(cents for USD or EUR, "halíře" for CZK)
@param string $name Name that customer will see
(will be automatically trimmed to 20 characters)
@param number $quantity
@param number $totalAmount Total price (total sum for all $quantity),
in **hundredths** of currency unit
@param string $description Aux description (trimmed to 40 chars max)
@return Payment Fluent interface
@throws Exception When more than 2nd cart item is to be added or other argument is invalid
|
entailment
|
public function setMerchantData($data, $alreadyEncoded = false) {
if (!$alreadyEncoded) {
$data = base64_encode($data);
}
if (strlen($data) > 255) {
throw new Exception("Merchant data can not be longer than 255 characters after base64 encoding.");
}
$this->merchantData = $data;
return $this;
}
|
Set some arbitrary data you will receive back when customer returns
@param string $data
@param bool $alreadyEncoded True if given $data is already encoded to Base64
@return Payment Fluent interface
@throws Exception When the data is too long and can't be encoded.
|
entailment
|
function setRecurrentPayment($recurrent = true) {
$this->payOperation = $recurrent ? self::OPERATION_RECURRENT : self::OPERATION_PAYMENT;
trigger_error('setRecurrentPayment() is deprecated, use setOneClickPayment() instead.', E_USER_DEPRECATED);
return $this;
}
|
Mark this payment as a template for recurrent payments.
Basically, this is a lazy method for setting $payOperation to OPERATION_RECURRENT.
@param bool $recurrent
@deprecated Deprecated and replaced by setOneClickPayment
@return \OndraKoupil\Csob\Payment
|
entailment
|
function setOneClickPayment($oneClick = true) {
$this->payOperation = $oneClick ? self::OPERATION_ONE_CLICK : self::OPERATION_PAYMENT;
return $this;
}
|
Mark this payment as one-click payment template
Basically, this is a lazy method for setting $payOperation to OPERATION_ONE_CLICK
@param bool $oneClick
@return $this
|
entailment
|
function checkAndPrepare(Config $config) {
$this->merchantId = $config->merchantId;
$this->dttm = date(Client::DATE_FORMAT);
if (!$this->payOperation) {
$this->payOperation = self::OPERATION_PAYMENT;
}
if (!$this->payMethod) {
$this->payMethod = "card";
}
if (!$this->currency) {
$this->currency = "CZK";
}
if (!$this->language) {
$this->language = "CZ";
}
if (!$this->ttlSec or !is_numeric($this->ttlSec)) {
$this->ttlSec = 1800;
}
if ($this->closePayment === null) {
$this->closePayment = $config->closePayment ? true : false;
}
if (!$this->returnUrl) {
$this->returnUrl = $config->returnUrl;
}
if (!$this->returnUrl) {
throw new Exception("A ReturnUrl must be set - either by setting \$returnUrl property, or by specifying it in Config.");
}
if (!$this->returnMethod) {
$this->returnMethod = $config->returnMethod;
}
if (!$this->description) {
$this->description = $config->shopName.", ".$this->orderNo;
}
$this->description = Strings::shorten($this->description, 240, "...");
$this->customerId = Strings::shorten($this->customerId, 50, "", true, true);
if (!$this->cart) {
throw new Exception("Cart is empty. Please add one or two items into cart using addCartItem() method.");
}
if (!$this->orderNo or !preg_match('~^[0-9]{1,10}$~', $this->orderNo)) {
throw new Exception("Invalid orderNo - it must be a non-empty numeric value, 10 characters max.");
}
$sumOfItems = array_sum(Arrays::transform($this->cart, true, "amount"));
$this->totalAmount = $sumOfItems;
return $this;
}
|
Validate and initialise properties. This method is called
automatically in proper time, you never have to call it on your own.
@param Config $config
@throws Exception
@return Payment Fluent interface
@ignore
|
entailment
|
function signAndExport(Client $client) {
$arr = array();
$config = $client->getConfig();
foreach($this->fieldsInOrder as $f) {
$val = $this->$f;
if ($val === null) {
$val = "";
}
$arr[$f] = $val;
}
foreach ($this->auxFieldsInOrder as $f) {
$val = $this->$f;
if ($val !== null) {
$arr[$f] = $val;
}
}
$stringToSign = $this->getSignatureString();
$client->writeToTraceLog('Signing payment request, base for the signature:' . "\n" . $stringToSign);
$signed = Crypto::signString($stringToSign, $config->privateKeyFile, $config->privateKeyPassword);
$arr["signature"] = $signed;
return $arr;
}
|
Add signature and export to array. This method is called automatically
and you don't need to call is on your own.
@param Client $client
@return array
@ignore
|
entailment
|
function getSignatureString() {
$parts = array();
foreach($this->fieldsInOrder as $f) {
$val = $this->$f;
if ($val === null) {
$val = "";
}
elseif (is_bool($val)) {
if ($val) {
$val = "true";
} else {
$val = "false";
}
} elseif (is_array($val)) {
// There are never more than 2 levels, we don't need recursive walk
$valParts = array();
foreach($val as $v) {
if (is_scalar($v)) {
$valParts[] = $v;
} else {
$valParts[] = implode("|", $v);
}
}
$val = implode("|", $valParts);
}
$parts[] = $val;
}
foreach ($this->auxFieldsInOrder as $f) {
$val = $this->$f;
if ($val !== null) {
$parts[] = $val;
}
}
return implode("|", $parts);
}
|
Convert to string that serves as base for signing.
@return string
@ignore
|
entailment
|
static function signString($string, $privateKeyFile, $privateKeyPassword = "") {
if (!function_exists("openssl_get_privatekey")) {
throw new CryptoException("OpenSSL extension in PHP is required. Please install or enable it.");
}
if (!file_exists($privateKeyFile) or !is_readable($privateKeyFile)) {
throw new CryptoException("Private key file \"$privateKeyFile\" not found or not readable.");
}
$keyAsString = file_get_contents($privateKeyFile);
$privateKeyId = openssl_get_privatekey($keyAsString, $privateKeyPassword);
if (!$privateKeyId) {
throw new CryptoException("Private key could not be loaded from file \"$privateKeyFile\". Please make sure that the file contains valid private key in PEM format.");
}
$ok = openssl_sign($string, $signature, $privateKeyId, self::HASH_METHOD);
if (!$ok) {
throw new CryptoException("Signing failed.");
}
$signature = base64_encode ($signature);
openssl_free_key ($privateKeyId);
return $signature;
}
|
Signs a string
@param string $string
@param string $privateKeyFile Path to file with your private key (the .key file from https://iplatebnibrana.csob.cz/keygen/ )
@param string $privateKeyPassword Password to the key, if it was generated with one. Leave empty if you created the key at https://iplatebnibrana.csob.cz/keygen/
@return string Signature encoded with Base64
@throws CryptoException When signing fails or key file path is not valid
|
entailment
|
static function verifySignature($textToVerify, $signatureInBase64, $publicKeyFile) {
if (!function_exists("openssl_get_privatekey")) {
throw new CryptoException("OpenSSL extension in PHP is required. Please install or enable it.");
}
if (!file_exists($publicKeyFile) or !is_readable($publicKeyFile)) {
throw new CryptoException("Public key file \"$publicKeyFile\" not found or not readable.");
}
$keyAsString = file_get_contents($publicKeyFile);
$publicKeyId = openssl_get_publickey($keyAsString);
$signature = base64_decode($signatureInBase64);
$res = openssl_verify($textToVerify, $signature, $publicKeyId, self::HASH_METHOD);
openssl_free_key($publicKeyId);
if ($res == -1) {
throw new CryptoException("Verification of signature failed: ".openssl_error_string());
}
return $res ? true : false;
}
|
Verifies signature of a string
@param string $textToVerify The text that was signed
@param string $signatureInBase64 The signature encoded with Base64
@param string $publicKeyFile Path to file where bank's public key is saved
(you can obtain it from bank's app https://iposman.iplatebnibrana.csob.cz/posmerchant
or from their package on GitHub)
@return bool True if signature is correct
@throws CryptoException When some cryptographic operation fails and key file path is not valid
|
entailment
|
static function createSignatureBaseFromArray($array, $returnAsArray = false) {
$linearizedArray = self::createSignatureBaseRecursion($array);
if ($returnAsArray) {
return $linearizedArray;
}
return implode('|', $linearizedArray);
}
|
Vytvoří z array (i víceúrovňového) string pro výpočet podpisu.
@param array $array
@param bool $returnAsArray
@return string|array
|
entailment
|
static function createSignatureBaseWithOrder($data, $order, $returnAsArray = false) {
$result = array();
foreach ($order as $key) {
$optional = false;
if ($key[0] == '?') {
$optional = true;
$key = substr($key, 1);
}
$keyPath = explode('.', $key);
$pos = $data;
$found = true;
foreach ($keyPath as $keyPathComponent) {
if (array_key_exists($keyPathComponent, $pos)) {
$pos = $pos[$keyPathComponent];
} else {
$found = false;
break;
}
}
if ($found) {
if (is_array($pos)) {
$result = array_merge($result, self::createSignatureBaseFromArray($pos, true));
} else {
$result[] = $pos;
}
} else {
if (!$optional) {
$result[] = '';
}
}
}
if ($returnAsArray) {
return $result;
}
return implode('|', $result);
}
|
Generická implementace linearizace pole s dopředu zadaným požadovaným pořadím.
V $order by mělo být požadované pořadí položek formou stringových "keypath".
Keypath je název klíče v poli $data, pokud je víceúrovňové, klíče jsou spojeny tečkou.
Pokud keypath začíná znakem otazník, považuje se za nepovinnou a není-li taková
položka nalezena, z výsledku se vynechá. V opačném případě se vloží prázdný řetězec.
Pokud keypath odkazuje na další array, to se vloží postupně položka po položce.
Příklad:
```php
$data = array(
'foo' => 'bar',
'arr' => array(
'a' => 'A',
'b' => 'B'
)
);
$order = array(
'foo',
'arr.a',
'somethingRequired',
'?somethingOptional',
'foo',
'arr.x',
'foo',
'arr'
);
$result = Crypto::createSignatureBaseWithOrder($data, $order, false);
$result == array('bar', 'A', '', 'bar', '', 'bar', 'A', 'B');
```
@param array $data Pole s daty
@param array $order Požadované pořadí položek.
@param bool $returnAsArray
@return array
|
entailment
|
protected function registerClientScript()
{
$js = [];
$view = $this->getView();
TinyMceAsset::register($view);
if ($tinyAssetBundle = TinyMceAsset::register($view)) {
$xCopy = new xCopy();
$assetPath = $tinyAssetBundle->basePath;
// Language pack
$languagesPack = Yii::getAlias('@dominus77/tinymce/assets/languages_pack');
$xCopy->copyFolder($languagesPack, $assetPath, true, true);
// Plugins
$pluginsPack = Yii::getAlias('@dominus77/tinymce/assets/plugins_pack');
$xCopy->copyFolder($pluginsPack, $assetPath, true, true);
// Skins
$skinsPack = Yii::getAlias('@dominus77/tinymce/assets/skins_pack');
$xCopy->copyFolder($skinsPack, $assetPath, true, true);
}
$id = $this->options['id'] ? $this->options['id'] : $this->getId();
$this->clientOptions['selector'] = "#{$id}";
$this->clientOptions['language'] = isset($this->clientOptions['language']) ? $this->clientOptions['language'] : $this->language;
if ($this->fileManager !== false) {
/** @var $fm \dominus77\tinymce\components\FileManager */
$fm = Yii::createObject(array_merge($this->fileManager, [
'tinyMceSettings' => $this->clientOptions,
'parentView' => $view]));
$fm->init();
$fm->registerAsset();
$this->clientOptions['file_picker_callback'] = $fm->getFilePickerCallback();
}
$options = Json::encode($this->clientOptions);
$js[] = "tinymce.init({$options});";
if ($this->triggerSaveOnBeforeValidateForm) {
$js[] = "$('#{$id}').parents('form').on('beforeValidate', function() { tinymce.triggerSave(); });";
}
$view->registerJs(implode("\n", $js));
}
|
Registers tinyMCE js plugin
@throws \yii\base\InvalidConfigException
|
entailment
|
public function buscar(Request $request, AtendimentoService $atendimentoService)
{
$envelope = new Envelope();
$usuario = $this->getUser();
$unidade = $usuario->getLotacao()->getUnidade();
$numero = $request->get('numero');
$atendimentos = $atendimentoService->buscaAtendimentos($unidade, $numero);
$envelope->setData($atendimentos);
return $this->json($envelope);
}
|
Busca os atendimentos a partir do número da senha.
@param Request $request
@Route("/buscar", name="novosga_monitor_buscar", methods={"GET"})
|
entailment
|
public function transferir(
Request $request,
AtendimentoService $atendimentoService,
ServicoService $servicoService,
Atendimento $atendimento,
TranslatorInterface $translator
) {
$envelope = new Envelope();
$usuario = $this->getUser();
$unidade = $usuario->getLotacao()->getUnidade();
$this->checkAtendimento($unidade, $atendimento, $translator);
$data = json_decode($request->getContent(), true);
$transferirForm = $this->createTransferirForm($request, $servicoService);
$transferirForm->submit($data);
if (!$transferirForm->isValid()) {
throw new Exception($translator->trans('error.invalid_form', [], self::DOMAIN));
}
$servicoUnidade = $transferirForm->get('servico')->getData();
$prioridade = $transferirForm->get('prioridade')->getData();
$atendimentoService->transferir(
$atendimento,
$unidade,
$servicoUnidade->getServico(),
$prioridade
);
return $this->json($envelope);
}
|
Transfere o atendimento para outro serviço e prioridade.
@param Request $request
@Route("/transferir/{id}", name="novosga_monitor_transferir", methods={"POST"})
|
entailment
|
public function reativar(
Request $request,
Atendimento $atendimento,
AtendimentoService $atendimentoService,
TranslatorInterface $translator
) {
$envelope = new Envelope();
$usuario = $this->getUser();
$unidade = $usuario->getLotacao()->getUnidade();
$statuses = [AtendimentoService::SENHA_CANCELADA, AtendimentoService::NAO_COMPARECEU];
if ($atendimento->getUnidade()->getId() !== $unidade->getId()) {
throw new Exception($translator->trans('error.reactive.invalid_unity', [], self::DOMAIN));
}
if (!in_array($atendimento->getStatus(), $statuses)) {
throw new Exception($translator->trans('error.reactive.invalid_status', [], self::DOMAIN));
}
$atendimentoService->reativar($atendimento, $unidade);
return $this->json($envelope);
}
|
Reativa o atendimento para o mesmo serviço e mesma prioridade.
Só pode reativar atendimentos que foram: Cancelados ou Não Compareceu.
@param Request $request
@Route("/reativar/{id}", name="novosga_monitor_reativar", methods={"POST"})
|
entailment
|
public function cancelar(
Request $request,
AtendimentoService $atendimentoService,
Atendimento $atendimento,
TranslatorInterface $translator
) {
$envelope = new Envelope();
$usuario = $this->getUser();
$unidade = $usuario->getLotacao()->getUnidade();
$this->checkAtendimento($unidade, $atendimento, $translator);
$atendimentoService->cancelar($atendimento);
return $this->json($envelope);
}
|
Atualiza o status da senha para cancelado.
@param Request $request
@Route("/cancelar/{id}", name="novosga_monitor_cancelar", methods={"POST"})
|
entailment
|
private function getManagerOptions()
{
if (!$this->language) {
$this->language = $this->tinyMceSettings['language'];
}
$managerOptions = [
'callback' => $this->getId(),
];
if (!empty($this->filter)) {
$managerOptions['filter'] = $this->filter;
}
if (!empty($this->language)) {
$managerOptions['lang'] = $this->language;
}
if (!empty($this->multiple)) {
$managerOptions['multiple'] = $this->multiple;
}
if (!empty($this->path)) {
$managerOptions['path'] = $this->path;
}
$managerOptions[0] = '/' . $this->controller . "/manager";
$this->managerUrl = Yii::$app->urlManager->createUrl($managerOptions);
return $managerOptions;
}
|
Manager Options
@return array
|
entailment
|
public function load($path)
{
$key = sha1($path);
$value = $this->cache->get($key);
if ($value !== null) {
return $value;
}
$this->cache->set($key, $value = $this->loader->load($path));
return $value;
}
|
{@inheritdoc}
|
entailment
|
public function load($path)
{
try {
return $this->firstLoader->load($path);
} catch (SchemaLoadingException $e) {
return $this->secondLoader->load($path);
}
}
|
{@inheritdoc}
|
entailment
|
public function load($path)
{
$uri = 'file://' . $path;
if (!file_exists($uri)) {
throw SchemaLoadingException::notFound($uri);
}
return $this->jsonDecoder->decode(file_get_contents($uri));
}
|
{@inheritdoc}
|
entailment
|
public function decode($schema)
{
try {
return Yaml::parse($schema, Yaml::PARSE_OBJECT_FOR_MAP | Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE);
} catch (ParseException $e) {
throw new DecodingException(sprintf('Invalid Yaml: %s', $e->getMessage()), $e->getCode(), $e);
}
}
|
{@inheritdoc}
|
entailment
|
protected function getResponseData($path, $default = null)
{
$array = $this->response;
if (!empty($path)) {
$keys = explode('.', $path);
foreach ($keys as $key) {
if (isset($array[$key])) {
$array = $array[$key];
} else {
return $default;
}
}
}
return $array;
}
|
Attempts to pull value from array using dot notation.
@param string $path
@param string $default
@return mixed
|
entailment
|
public function get($pointer)
{
$value = $this->traverse($pointer);
if ($value instanceof NonExistentValue) {
throw InvalidPointerException::nonexistentValue($value->getValue(), $value->getPointer());
}
return $value;
}
|
@param string $pointer
@return mixed
@throws InvalidPointerException
|
entailment
|
public function set($pointer, $data)
{
if ($pointer === '') {
throw new \InvalidArgumentException('Cannot replace the object with set.');
}
$pointer = $this->parse($pointer);
$replace = array_pop($pointer);
$target = &$this->getTarget($pointer);
if (is_array($target)) {
if ($replace === '-') {
$target[] = $data;
} else {
$target[$replace] = $data;
}
} elseif (is_object($target)) {
$target->$replace = $data;
} else {
throw InvalidPointerException::invalidTarget($target);
}
}
|
@param string $pointer
@param mixed $data
@return void
@throws InvalidPointerException
@throws \InvalidArgumentException
|
entailment
|
public function remove($pointer)
{
if ($pointer === '') {
throw new \InvalidArgumentException('Cannot remove the object.');
}
$pointer = $this->parse($pointer);
$remove = array_pop($pointer);
$target = &$this->getTarget($pointer);
if (is_array($target)) {
unset($target[$remove]);
} elseif (is_object($target)) {
unset($target->$remove);
} else {
throw InvalidPointerException::invalidTarget($target);
}
}
|
@param string $pointer
@return void
|
entailment
|
private function &getTarget(array $pointer)
{
$target = &$this->json;
foreach ($pointer as $segment) {
if (is_array($target)) {
$target =& $target[$segment];
} else {
$target =& $target->$segment;
}
}
return $target;
}
|
@param array $pointer
@return mixed
|
entailment
|
private function traverse($pointer)
{
$parsedPointer = $this->parse($pointer);
$json = $this->json;
foreach ($parsedPointer as $segment) {
if ($json instanceof Reference) {
if (!$json->has($segment)) {
return new NonExistentValue($segment, $pointer);
}
$json = $json->get($segment);
} elseif (is_object($json)) {
// who does this?
if ($segment === '' && property_exists($json, '_empty_')) {
$segment = '_empty_';
}
if (!property_exists($json, $segment)) {
return new NonExistentValue($segment, $pointer);
}
$json = $json->$segment;
} elseif (is_array($json)) {
if (!array_key_exists($segment, $json)) {
return new NonExistentValue($segment, $pointer);
}
$json = $json[$segment];
} else {
return new NonExistentValue($segment, $pointer);
}
}
return $json;
}
|
Returns the value referenced by the pointer or a NonExistentValue if the value does not exist.
@param string $pointer The pointer
@return mixed
|
entailment
|
private function parse($pointer)
{
if (!is_string($pointer)) {
throw InvalidPointerException::invalidType(gettype($pointer));
}
if (!isset($pointer[0])) {
return [];
}
// If the pointer is a url fragment, it needs to be url decoded.
if ($pointer[0] === '#') {
$pointer = urldecode(substr($pointer, 1));
}
// For convenience add the beginning slash if it's missing.
if (isset($pointer[0]) && $pointer[0] !== '/') {
$pointer = '/' . $pointer;
}
$pointer = array_slice(explode('/', $pointer), 1);
return str_replace(['~1', '~0'], ['/', '~'], $pointer);
}
|
Parses a JSON Pointer as defined in the specification.
@see https://tools.ietf.org/html/rfc6901#section-4
@param string $pointer
@return array
@throws InvalidPointerException
|
entailment
|
public function dereference($schema, $uri = '')
{
return $this->crawl($schema, $uri, function ($schema, $pointer, $ref, $scope) {
$resolved = new Reference($ref, $scope, is_internal_ref($ref) ? $schema : null);
return merge_ref($schema, $resolved, $pointer);
});
}
|
{@inheritdoc}
|
entailment
|
private function prepareArguments($schema, $uri)
{
if (is_string($schema)) {
$uri = $schema;
$schema = resolve_fragment($uri, $this->loadExternalRef($uri));
$uri = strip_fragment($uri);
}
return [$schema, $uri];
}
|
@param object|string $schema
@param string $uri
@return array
|
entailment
|
private function crawl($schema, $uri, callable $resolver)
{
list($schema, $uri) = $this->prepareArguments($schema, $uri);
foreach (schema_extract($schema, 'League\JsonReference\is_ref') as $pointer => $ref) {
$scope = $this->scopeResolver->resolve($schema, $pointer, $uri);
$schema = $resolver($schema, $pointer, $ref, $scope);
}
return $schema;
}
|
@param string|object $schema
@param string $uri
@param callable $resolver
@return object
|
entailment
|
private function loadExternalRef($reference)
{
list($prefix, $path) = parse_external_ref($reference);
return $this->loaderManager->getLoader($prefix)->load($path);
}
|
Load an external ref and return the JSON object.
@param string $reference
@return object
|
entailment
|
public function dereference($schema, $uri = '')
{
$key = self::key($schema, $uri);
return $this->remember($key, function () use ($schema, $uri) {
return $this->dereferencer->dereference($schema, $uri);
});
}
|
{@inheritdoc}
|
entailment
|
private function remember($key, Closure $callback)
{
$value = $this->cache->get($key);
if ($value !== null) {
return $value;
}
$this->cache->set($key, $value = $callback());
return $value;
}
|
@param string $key
@param Closure $callback
@return object
|
entailment
|
private static function key($schema, $uri)
{
if ($uri !== '') {
return sha1($uri);
}
return sha1(is_string($schema) ? $schema : json_encode($schema));
}
|
@param string|object $schema
@param string $uri
@return string
|
entailment
|
public function getType($class)
{
foreach ($this->handlers as list($service_id, $handler_class)) {
if ($handler_class !== $class) {
continue;
}
$handler = $this->container->get($service_id);
if ($handler instanceof FormHandlerInterface) {
return new HandlerTypeAdapter($handler);
}
return $handler;
}
throw new InvalidHandlerTypeException($class);
}
|
{@inheritdoc}
|
entailment
|
public function load($path)
{
if (!array_key_exists($path, $this->schemas)) {
throw SchemaLoadingException::notFound($path);
}
$schema = $this->schemas[$path];
if (is_string($schema)) {
return $this->jsonDecoder->decode($schema);
} elseif (is_object($schema)) {
return $schema;
} else {
throw SchemaLoadingException::create($path);
}
}
|
{@inheritdoc}
|
entailment
|
public function decode($schema)
{
$data = json_decode($schema, $this->assoc, $this->depth, $this->options);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new DecodingException(sprintf('Invalid JSON: %s', json_last_error_msg()));
}
return $data;
}
|
{@inheritdoc}
|
entailment
|
public function load($path)
{
$uri = $this->prefix . $path;
$ch = curl_init($uri);
curl_setopt_array($ch, $this->curlOptions);
list($response, $statusCode) = $this->getResponseBodyAndStatusCode($ch);
curl_close($ch);
if ($statusCode >= 400 || !$response) {
throw JsonReference\SchemaLoadingException::create($uri);
}
return $this->jsonDecoder->decode($response);
}
|
{@inheritdoc}
|
entailment
|
private function getResponseBodyAndStatusCode($ch)
{
$response = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
return [$response, $statusCode];
}
|
@param resource $ch
@return array
|
entailment
|
public function resolve($schema, $currentPointer, $currentScope)
{
$current = $schema;
foreach (explode('/', $currentPointer) as $segment) {
if (isset($current->$segment)) {
$current = $current->$segment;
}
$id = isset($current->{$this->keyword}) ? $current->{$this->keyword} : null;
if (is_string($id)) {
$currentScope = resolve_uri($id, $currentScope);
}
}
return $currentScope;
}
|
{@inheritdoc}
|
entailment
|
public function getLoader($prefix)
{
if (!$this->hasLoader($prefix)) {
throw new \InvalidArgumentException(sprintf('A loader is not registered for the prefix "%s"', $prefix));
}
return $this->loaders[$prefix];
}
|
Get the loader for the given prefix.
@param string $prefix
@return LoaderInterface
@throws \InvalidArgumentException
|
entailment
|
private function registerDefaultWebLoaders()
{
if (function_exists('curl_init')) {
$this->loaders['https'] = new CurlWebLoader('https://');
$this->loaders['http'] = new CurlWebLoader('http://');
} else {
$this->loaders['https'] = new FileGetContentsWebLoader('https://');
$this->loaders['http'] = new FileGetContentsWebLoader('http://');
}
}
|
Register the default web loaders. If the curl extension is loaded,
the CurlWebLoader will be used. Otherwise the FileGetContentsWebLoader
will be used. You can override this by registering your own loader
for the 'http' and 'https' protocols.
|
entailment
|
public function apply(Request $request, ParamConverter $configuration)
{
$options = $configuration->getOptions();
$service_id = isset($options['service_id'])
? $options['service_id']
: $this->getServiceIdForClassName($configuration);
$handler = $this->container->get($service_id);
$class = $this->handlers[$service_id];
if (!$handler instanceof FormHandlerInterface || get_class($handler) !== $class) {
return;
}
$request->attributes->set($configuration->getName(), $handler);
}
|
{@inheritdoc}
|
entailment
|
public function resolve()
{
if (isset($this->resolved)) {
return $this->resolved;
}
$pointer = new Pointer($this->schema);
if (is_internal_ref($this->ref) && $pointer->has($this->ref)) {
return $this->resolved = $pointer->get($this->ref);
}
return $this->dereferencer()->dereference(resolve_uri($this->ref, $this->scope));
}
|
Resolve the reference and return the data.
@return mixed
|
entailment
|
public function get($property)
{
if (!$this->has($property)) {
throw new \InvalidArgumentException(sprintf('Unknown property "%s"', $property));
}
$schema = $this->resolve();
return pointer($schema)->get($property);
}
|
@param string $property
@return mixed
@throws \InvalidArgumentException
|
entailment
|
public function getIterator()
{
// Recursively resolve until we hit a real schema
//because you can't use get_object_vars on a reference.
$schema = $this->resolve();
while ($schema instanceof Reference) {
$schema = $schema->resolve();
}
if (!is_object($schema) && !is_array($schema)) {
throw new \InvalidArgumentException(
sprintf('Expected an object or array, got "%s"', gettype($schema))
);
}
return new \ArrayIterator(is_object($schema) ? get_object_vars($schema) : $schema);
}
|
Retrieve an external iterator
@link http://php.net/manual/en/iteratoraggregate.getiterator.php
@return \Traversable An instance of an object implementing <b>Iterator</b> or
<b>Traversable</b>
@since 5.0.0
|
entailment
|
protected function createAccessToken(array $response, AbstractGrant $grant)
{
return new \Stevenmaguire\OAuth2\Client\Token\AccessToken($response);
}
|
Creates an access token from a response.
The grant that was used to fetch the response can be used to provide
additional context.
@param array $response
@param AbstractGrant $grant
@return AccessToken
|
entailment
|
public function setDomain($domain)
{
try {
$this->domain = (string) $domain;
} catch (Exception $e) {
throw new InvalidArgumentException(
'Value provided as domain is not a string'
);
}
return $this;
}
|
Updates the provider domain with a given value.
@throws InvalidArgumentException
@param string $domain
@return Salesforce
|
entailment
|
public function load($path)
{
$uri = $this->prefix . $path;
set_error_handler(function () use ($uri) {
throw SchemaLoadingException::create($uri);
});
$response = file_get_contents($uri);
restore_error_handler();
if (!$response) {
throw SchemaLoadingException::create($uri);
}
return $this->jsonDecoder->decode($response);
}
|
{@inheritdoc}
|
entailment
|
public function process()
{
if (Yii::$app->db->getTableSchema($this->table) == null) {
throw new \yii\base\InvalidConfigException('"' . $this->table . '" not found in database. Make sure the db migration is properly done and the table is created.');
}
$success = true;
$items = Queue::find()->where(['and', ['sent_time' => NULL], ['<', 'attempts', $this->maxAttempts], ['<=', 'time_to_send', date('Y-m-d H:i:s')]])->orderBy(['created_at' => SORT_ASC])->limit($this->mailsPerRound);
foreach ($items->each() as $item) {
if ($message = $item->toMessage()) {
$attributes = ['attempts', 'last_attempt_time'];
if ($this->send($message)) {
$item->sent_time = new \yii\db\Expression('NOW()');
$attributes[] = 'sent_time';
} else {
$success = false;
}
$item->attempts++;
$item->last_attempt_time = new \yii\db\Expression('NOW()');
$item->updateAttributes($attributes);
}
}
// Purge messages now?
if ($this->autoPurge) {
$this->purge();
}
return $success;
}
|
Sends out the messages in email queue and update the database.
@return boolean true if all messages are successfully sent out
|
entailment
|
public function queue($time_to_send = 'now')
{
if($time_to_send == 'now') {
$time_to_send = time();
}
$item = new Queue();
$item->subject = $this->getSubject();
$item->attempts = 0;
$item->swift_message = base64_encode(serialize($this));
$item->time_to_send = date('Y-m-d H:i:s', $time_to_send);
return $item->save();
}
|
Enqueue the message storing it in database.
@param timestamp $time_to_send
@return boolean true on success, false otherwise
|
entailment
|
public static function invalidButtonPosition($message = null)
{
$defaultMessage = sprintf('Tried giving the button to a player that is not sat down.');
$message = null === $message ? $defaultMessage : $message;
return new static($message);
}
|
@param null $message
@return static
|
entailment
|
public static function notRegistered(Client $player, Table $table, $message = null)
{
$defaultMessage = sprintf('%s is not registered to table: "%s"', $player, $table->id()->toString());
$message = is_null($message) ? $defaultMessage : $message;
return new static($message);
}
|
@param Client $player
@param Table $table
@param string $message
@return static
|
entailment
|
public function remove(ChipPot $removeChipPot)
{
return $this->reject(function (ChipPot $chipPot) use ($removeChipPot) {
return $chipPot->equals($removeChipPot);
})->values();
}
|
@var ChipPot
@return ChipPotCollection
|
entailment
|
public static function invalidArgument($message = null)
{
$defaultMessage = sprintf('Invalid argument passed in GameParameters.');
$message = null === $message ? $defaultMessage : $message;
return new static($message);
}
|
@param null $message
@return static
|
entailment
|
public static function setUp(UuidInterface $id, string $name, GameParameters $rules)
{
return new self($id, $name, $rules);
}
|
@param UuidInterface $id
@param string $name
@param GameParameters $rules
@return CashGame
|
entailment
|
public function createService(ServiceLocatorInterface $serviceLocator)
{
$moduleConfig = $serviceLocator->get('config')['dompdf_module'];
$options = [
'temp_dir' => $moduleConfig['temporary_directory'],
'font_dir' => $moduleConfig['font_directory'],
'font_cache' => $moduleConfig['font_cache_directory'],
'chroot' => $moduleConfig['chroot'],
'log_output_file' => $moduleConfig['log_output_file'],
'default_media_type' => $moduleConfig['default_media_type'],
'default_paper_size' => $moduleConfig['default_paper_size'],
'default_font' => $moduleConfig['default_font'],
'dpi' => $moduleConfig['dpi'],
'font_height_ratio' => $moduleConfig['font_height_ratio'],
'is_php_enabled' => $moduleConfig['enable_php'],
'is_remote_enabled' => $moduleConfig['enable_remote'],
'is_javascript_enabled' => $moduleConfig['enable_javascript'],
'is_html5_parser_enabled' => $moduleConfig['enable_html5parser'],
'is_font_subsetting_enabled' => $moduleConfig['enable_fontsubsetting'],
'debug_png' => $moduleConfig['debug_png'],
'debug_keep_temp' => $moduleConfig['debug_keep_temp'],
'debug_css' => $moduleConfig['debug_css'],
'debug_layout' => $moduleConfig['debug_layout'],
'debug_layout_lines' => $moduleConfig['debug_layout_lines'],
'debug_layout_blocks' => $moduleConfig['debug_layout_blocks'],
'debug_layout_inline' => $moduleConfig['debug_layout_inline'],
'debug_layout_padding_box' => $moduleConfig['debug_layout_padding_box'],
'pdf_backend' => $moduleConfig['pdf_backend'],
'pdflib_license' => $moduleConfig['pdflib_license']
];
return new Dompdf(new Options($options));
}
|
Creates an instance of Dompdf.
@param ServiceLocatorInterface $serviceLocator
@return Dompdf
|
entailment
|
public function hasAction(int $actionValue): bool
{
$count = $this
->filter(function (Action $action) use ($actionValue) {
return $action->action() === $actionValue;
})
->count();
return $count > 0 ? true : false;
}
|
@param int $actionValue
@return bool
|
entailment
|
public function render($nameOrModel, $values = null)
{
if (!($nameOrModel instanceof PdfModel)) {
throw new InvalidArgumentException(sprintf(
'%s expects a PdfModel as the first argument; received "%s"',
__METHOD__,
(is_object($nameOrModel) ? get_class($nameOrModel) : gettype($nameOrModel))
));
}
$html = $this->getHtmlRenderer()->render($nameOrModel, $values);
$paperSize = $nameOrModel->getOption('paperSize');
$paperOrientation = $nameOrModel->getOption('paperOrientation');
$basePath = $nameOrModel->getOption('basePath');
$pdf = $this->getEngine();
$pdf->setPaper($paperSize, $paperOrientation);
$pdf->setBasePath($basePath);
$pdf->loadHtml($html);
$pdf->render();
return $pdf->output();
}
|
{@inheritdoc}
|
entailment
|
public static function createRoyalFlush(CardCollection $cards, Hand $hand): self
{
return new static(
self::ROYAL_FLUSH,
[0],
$cards,
'Royal Flush',
$hand
);
}
|
@param CardCollection $cards
@return SevenCardResult
|
entailment
|
public static function createStraightFlush(CardCollection $cards, Hand $hand): self
{
$highCard = $cards->sortByValue()->take(-1);
$definition = sprintf('Straight Flush to %s', $highCard->first()->name());
return new static(
self::STRAIGHT_FLUSH,
[$highCard->first()->value()],
$cards,
$definition,
$hand
);
}
|
@param CardCollection $cards
@return SevenCardResult
|
entailment
|
public static function createFourOfAKind(CardCollection $cards, Hand $hand): self
{
$cardGroups = $cards->groupByValue();
$firstGroup = $cardGroups->first()->first();
$kickerGroup = $cardGroups->last()->first();
$definition = sprintf('4 of a Kind - %ss', $firstGroup->name());
return new static(
self::FOUR_OF_A_KIND,
[$firstGroup->value(), $kickerGroup->value()],
$cards,
$definition,
$hand
);
}
|
@param CardCollection $cards
@return SevenCardResult
|
entailment
|
public static function createFullHouse(CardCollection $cards, Hand $hand): self
{
$cardGroups = $cards->groupByValue()->take(2);
$firstCardGroup = $cardGroups->first()->first();
$lastCardGroup = $cardGroups->last()->first();
$definition = sprintf(
'Full House - %ss over %ss',
$firstCardGroup->name(),
$lastCardGroup->name()
);
return new static(
self::FULL_HOUSE,
[$firstCardGroup->value(), $lastCardGroup->value()],
$cards,
$definition,
$hand
);
}
|
@param CardCollection $cards
@return SevenCardResult
|
entailment
|
public static function createFlush(CardCollection $cards, Hand $hand): self
{
$highCard = $cards->sortByValue()->take(-1);
$definition = sprintf('Flush to %s', $highCard->first()->name());
return new static(
self::FLUSH,
[$highCard->first()->value()],
$cards,
$definition,
$hand
);
}
|
@param CardCollection $cards
@return SevenCardResult
|
entailment
|
public static function createStraight(CardCollection $cards, Hand $hand): self
{
$highCard = $cards->sortByValue()->take(-1);
$definition = sprintf('Straight to %s', $highCard->first()->name());
return new static(
self::STRAIGHT,
[$highCard->first()->value()],
$cards,
$definition,
$hand
);
}
|
@param CardCollection $cards
@return SevenCardResult
|
entailment
|
public static function createThreeOfAKind(CardCollection $cards, Hand $hand): self
{
$cardGroups = $cards->groupByValue();
$firstCard = $cardGroups->get(0)->first();
$kicker = $cardGroups->get(1)->first();
$definition = sprintf('3 of a Kind - %ss', $firstCard->name());
return new static(
self::THREE_OF_A_KIND,
[$firstCard->value(), $kicker->value()],
$cards,
$definition,
$hand
);
}
|
@param CardCollection $cards
@return SevenCardResult
|
entailment
|
public static function createTwoPair(CardCollection $cards, Hand $hand): self
{
$cardGroups = $cards->groupByValue();
$firstCard = $cardGroups->get(0)->first();
$secondCard = $cardGroups->get(1)->first();
$kickerCard = $cardGroups->get(2)->first();
$definition = sprintf(
'Two Pair - %ss and %ss',
$firstCard->name(),
$secondCard->name()
);
return new static(
self::TWO_PAIR,
[$firstCard->value(), $secondCard->value(), $kickerCard->value()],
$cards,
$definition,
$hand
);
}
|
@param CardCollection $cards
@return SevenCardResult
|
entailment
|
public static function createOnePair(CardCollection $cards, Hand $hand): self
{
$cardGroups = $cards->groupByValue();
$pair = $cardGroups->get(0)->first();
$kicker = $cardGroups->get(1)->first();
$definition = sprintf('Pair of %ss', $pair->name());
return new static(
self::ONE_PAIR,
[$pair->value(), $kicker->value()],
$cards,
$definition,
$hand
);
}
|
@param CardCollection $cards
@return SevenCardResult
|
entailment
|
public static function createHighCard(CardCollection $cards, Hand $hand): self
{
$cardValues = $cards->sortByValue()->values();
$highCard = $cardValues->get(4);
$definition = sprintf('High Card - %s', $highCard->name());
return new static(
self::HIGH_CARD,
$cardValues->map(function (Card $card) {
return $card->value();
})->toArray(),
$cards,
$definition,
$hand
);
}
|
@param CardCollection $cards
@return SevenCardResult
|
entailment
|
public function addChips(Chips $chips, Player $player): ChipPot
{
$existingChips = $this->chips()->get($player->name()) ?? Chips::zero();
$this->chips->put($player->name(), Chips::fromAmount($existingChips->amount() + $chips->amount()));
if ($this->players()->findByName($player->name()) === null) {
$this->players->push($player);
}
return $this;
}
|
@param Chips $chips
@param Player $player
@return ChipPot
|
entailment
|
public function equals(ChipPot $object): bool
{
return static::class === get_class($object)
&& $this->chips() === $object->chips()
&& $this->players() === $object->players()
&& $this->total() === $object->total();
}
|
@param ChipPot $object
@return bool
|
entailment
|
public static function playerHasNoHand(Player $player, $message = null)
{
$defaultMessage = sprintf('%s has not been dealt into this round', $player);
$message = null === $message ? $defaultMessage : $message;
return new static($message);
}
|
@param Player $player
@param null|string $message
@return static
|
entailment
|
public static function notEnoughChipsInChipStack(Player $player, Chips $chips, $message = null)
{
$defaultMessage = sprintf('%s does not have enough chips to bet %d', $player, $chips->amount());
$message = null === $message ? $defaultMessage : $message;
return new static($message);
}
|
@param Player $player
@param Chips $chips
@param null|string $message
@return static
|
entailment
|
public static function playerStillNeedsToAct(Player $player, $message = null)
{
$defaultMessage = sprintf('%s still needs to act.', $player);
$message = null === $message ? $defaultMessage : $message;
return new static($message);
}
|
@param Player $player
@param null|string $message
@return static
|
entailment
|
public static function flopHasBeenDealt($message = null)
{
$defaultMessage = 'The Flop has already been dealt!';
$message = null === $message ? $defaultMessage : $message;
return new static($message);
}
|
@param null|string $message
@return static
|
entailment
|
public static function turnHasBeenDealt($message = null)
{
$defaultMessage = 'The Turn has already been dealt!';
$message = null === $message ? $defaultMessage : $message;
return new static($message);
}
|
@param null|string $message
@return static
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.