code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
protected function getPaymentTransactionStructure()
{
return [
'return_success_url' => $this->return_success_url,
'return_failure_url' => $this->return_failure_url,
'amount' => $this->transformAmount($this->amount, $this->currency),
'currency' => $this->currency,
'is_payout' => var_export($this->is_payout, true),
'customer_bank_id' => $this->customer_bank_id,
'order_description' => $this->order_description,
'payout_order_id' => $this->payout_order_id,
'payout_bank_country' => $this->payout_bank_country,
'payout_bank_name' => $this->payout_bank_name,
'payout_swift' => $this->payout_swift,
'payout_acc_number' => $this->payout_acc_number,
'payout_bank_address' => $this->payout_bank_address,
'payout_owner_name' => $this->payout_owner_name,
'payout_owner_address' => $this->payout_owner_address,
'customer_email' => $this->customer_email,
'customer_phone' => $this->customer_phone,
'billing_address' => $this->getBillingAddressParamsStructure(),
'shipping_address' => $this->getShippingAddressParamsStructure()
];
} | Return additional request attributes
@return array |
public function parseNotification($notification = [], $authenticate = true)
{
$notificationWalk = [];
array_walk($notification, function ($val, $key) use (&$notificationWalk) {
$key = trim(rawurldecode($key));
$val = trim(rawurldecode($val));
$notificationWalk[$key] = $val;
});
$notification = $notificationWalk;
$this->notificationObj = \Genesis\Utils\Common::createArrayObject($notification);
if ($this->isAPINotification()) {
$this->unique_id = (string)$this->notificationObj->unique_id;
}
if ($this->isWPFNotification()) {
$this->unique_id = (string)$this->notificationObj->wpf_unique_id;
}
if ($authenticate && !$this->isAuthentic()) {
throw new \Genesis\Exceptions\InvalidArgument('Invalid Genesis Notification!');
}
} | Parse and Authenticate the incoming notification from Genesis
@param array $notification - Incoming notification ($_POST)
@param bool $authenticate - Set to true if you want to validate the notification
@throws \Genesis\Exceptions\InvalidArgument() |
public function initReconciliation()
{
$type = '';
if ($this->isAPINotification()) {
$type = 'NonFinancial\Reconcile\Transaction';
} elseif ($this->isWPFNotification()) {
$type = 'WPF\Reconcile';
}
$request = new \Genesis\Genesis($type);
try {
$request->request()->setUniqueId($this->unique_id);
$request->execute();
} catch (\Genesis\Exceptions\ErrorAPI $api) {
// This is reconciliation, don't throw on ErrorAPI
}
return $this->reconciliationObj = $request->response()->getResponseObject();
} | Reconcile with the Payment Gateway to get the latest
status on the transaction
@throws \Genesis\Exceptions\InvalidResponse |
public function isAuthentic()
{
if (!isset($this->unique_id) || !isset($this->notificationObj->signature)) {
throw new \Genesis\Exceptions\InvalidArgument(
'Missing field(s), required for validation!'
);
}
$messageSig = trim($this->notificationObj->signature);
$customerPwd = trim(\Genesis\Config::getPassword());
switch (strlen($messageSig)) {
default:
case 40:
$hashType = 'sha1';
break;
case 128:
$hashType = 'sha512';
break;
}
if ($messageSig === hash($hashType, $this->unique_id . $customerPwd)) {
return true;
}
return false;
} | Verify the signature on the parsed Notification
@return bool
@throws \Genesis\Exceptions\InvalidArgument |
public function isAPINotification()
{
return (bool)(isset($this->notificationObj->unique_id) && !empty($this->notificationObj->unique_id));
} | Is this API notification?
@return bool |
public function isWPFNotification()
{
return (bool)(isset($this->notificationObj->wpf_unique_id) && !empty($this->notificationObj->wpf_unique_id));
} | Is this WPF Notification?
@return bool |
public function generateResponse()
{
$uniqueId = $this->isWPFNotification() ? 'wpf_unique_id' : 'unique_id';
$structure = [
'notification_echo' => [
$uniqueId => $this->unique_id
]
];
$builder = new \Genesis\Builder('xml');
$builder->parseStructure($structure);
return $builder->getDocument();
} | Generate Builder response (Echo) required for acknowledging
Genesis's Notification
@return string |
public function prepareRequestBody($requestData)
{
$options = [
CURLOPT_URL => $requestData['url'],
CURLOPT_TIMEOUT => $requestData['timeout'],
CURLOPT_USERAGENT => $requestData['user_agent'],
CURLOPT_USERPWD => $requestData['user_login'],
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_ENCODING => 'gzip',
CURLOPT_HTTPHEADER => [
'Content-Type: text/xml',
// Workaround to prevent cURL from parsing HTTP 100 as separate request
'Expect:'
],
CURLOPT_HEADER => true,
CURLOPT_FAILONERROR => true,
CURLOPT_FRESH_CONNECT => true,
CURLOPT_RETURNTRANSFER => true,
// SSL/TLS Configuration
CURLOPT_CAINFO => $requestData['ca_bundle'],
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2
];
if ('POST' == strtoupper($requestData['type'])) {
$post = [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $requestData['body']
];
$options = $options + $post;
}
curl_setopt_array($this->curlHandle, $options);
} | Set cURL headers/options, based on the request data
@param array $requestData
@return void |
public function execute()
{
$this->response = curl_exec($this->curlHandle);
$this->checkForErrors();
list($this->responseHeaders, $this->responseBody) = explode("\r\n\r\n", $this->response, 2);
} | Send the request
@return void
@throws |
public function checkForErrors()
{
$errNo = curl_errno($this->curlHandle);
$errStr = curl_error($this->curlHandle);
if ($errNo > 0) {
throw new \Genesis\Exceptions\ErrorNetwork($errStr, $errNo);
}
} | Check whether or not a cURL request is successful
@return string
@throws \Genesis\Exceptions\ErrorNetwork |
public function setConsumerReference($value)
{
if (strlen($value) > $this->getMaxConsumerReferenceLen()) {
throw new ErrorParameter("Consumer reference can be max {$this->getMaxConsumerReferenceLen()} characters.");
}
$this->consumer_reference = $value;
return $this;
} | Unique consumer identifier
@param string $value
@return $this
@throws ErrorParameter |
public function setNationalId($value)
{
if (strlen($value) > $this->getNationalIdLen()) {
throw new ErrorParameter("National Identifier can be max {$this->getNationalIdLen()} characters.");
}
$this->national_id = $value;
return $this;
} | National Identifier number of the customer
@param string $value
@return $this
@throws ErrorParameter |
public function setBirthDate($value)
{
if (!preg_match($this->getBirthDateValidationRegex(), $value) || strtotime($value) === false) {
throw new ErrorParameter('Birth date has to be in format dd-mm-yyyy.');
}
$this->birth_date = $value;
return $this;
} | Unique consumer identifier
@param string $value
@return $this
@throws ErrorParameter |
protected function setRequiredFields()
{
$requiredFields = [
'transaction_id',
'amount',
'currency',
'customer_email',
'holder_name',
'billing_country'
];
$this->requiredFields = \Genesis\Utils\Common::createArrayObject($requiredFields);
$requiredFieldValues = [
'billing_country' => [
'АЕ', 'AT', 'AU', 'BE', 'BG', 'CA', 'CY', 'CZ', 'DE', 'DK', 'EE', 'ES',
'FI', 'FR', 'GB', 'GF', 'GP', 'GR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV',
'MC', 'MQ', 'MT', 'MX', 'NL', 'PL', 'PT', 'RE', 'SE', 'SI', 'SK'
],
'currency' => \Genesis\Utils\Currency::getList()
];
$this->requiredFieldValues = \Genesis\Utils\Common::createArrayObject($requiredFieldValues);
$this->setRequiredFieldsConditional();
} | Set the required fields
@return void |
protected function getPaymentTransactionStructure()
{
return [
'amount' => $this->transformAmount($this->amount, $this->currency),
'currency' => $this->currency,
'customer_email' => $this->customer_email,
'customer_phone' => $this->customer_phone,
'holder_name' => $this->holder_name,
'iban' => $this->iban,
'swift_code' => $this->swift_code,
'account_number' => $this->account_number,
'bank_name' => $this->bank_name,
'bank_city' => $this->bank_city,
'bank_code' => $this->bank_code,
'branch_code' => $this->branch_code,
'branch_check_digit' => $this->branch_check_digit,
'billing_address' => $this->getBillingAddressParamsStructure(),
'shipping_address' => $this->getShippingAddressParamsStructure()
];
} | Return additional request attributes
@return array |
public function parseDocument($xmlDocument)
{
$reader = new \XMLReader();
$reader->open('data:text/plain;base64,' . base64_encode($xmlDocument));
if ($this->skipRootNode) {
$reader->read();
}
$this->stdClassObj = self::readerLoop($reader);
} | Parse a document to an stdClass
@param string $xmlDocument XML Document
@return void |
public function readerLoop($reader)
{
$tree = new \stdClass();
while ($reader->read()) {
switch ($reader->nodeType) {
case \XMLReader::END_ELEMENT:
return $tree;
break;
case \XMLReader::ELEMENT:
$this->processElement($reader, $tree);
if ($reader->hasAttributes) {
$this->processAttributes($reader, $tree);
}
break;
case \XMLReader::TEXT:
case \XMLReader::CDATA:
$tree = \Genesis\Utils\Common::stringToBoolean(
trim($reader->expand()->textContent)
);
break;
}
}
return $tree;
} | Read through the entire document
@param \XMLReader $reader
@return mixed |
public function processElement(&$reader, &$tree)
{
$name = $reader->name;
if (isset($tree->$name)) {
if (is_a($tree->$name, 'stdClass')) {
$currentEl = $tree->$name;
$tree->$name = new \ArrayObject();
$tree->$name->append($currentEl);
}
if (is_a($tree->$name, 'ArrayObject')) {
$tree->$name->append(($reader->isEmptyElement) ? '' : $this->readerLoop($reader));
}
} else {
$tree->$name = ($reader->isEmptyElement) ? '' : $this->readerLoop($reader);
}
} | Process XMLReader element
@param $reader
@param $tree
@SuppressWarnings(PHPMD.ElseExpression) |
public function processAttributes(&$reader, &$tree)
{
$name = $reader->name;
$node = new \stdClass();
$node->attr = new \stdClass();
while ($reader->moveToNextAttribute()) {
$node->attr->$name = $reader->value;
}
if (isset($tree->$name) && is_a($tree->$name, 'ArrayObject')) {
$lastKey = $tree->$name->count() - 1;
$node->value = $tree->$name->offsetGet($lastKey);
$tree->$name->offsetSet($lastKey, $node);
} else {
$node->value = isset($tree->$name) ? $tree->$name : '';
$tree->$name = $node;
}
} | Process element attributes
@param \XMLReader $reader
@param \stdClass $tree
@SuppressWarnings(PHPMD.ElseExpression) |
public function getAllCommands()
{
// Avoid fatal errors for "Class 'oxConsoleCommand' not found" in case of old Commands present
if (!class_exists('oxConsoleCommand'))
class_alias(Command::class, 'oxConsoleCommand');
$commands = $this->getCommandsFromCore();
$commandsFromModules = $this->getCommandsFromModules();
$commandsFromComposer = $this->getCommandsFromComposer();
return array_merge(
$commands,
$commandsFromModules,
$commandsFromComposer
);
} | Get all available command objects.
Command objects are collected from the following sources:
1) All core commands from `OxidProfessionalServices\OxidConsole\Command` namespace;
2) All commands from modules matching the following criteria:
a) Are placed under the directory `Command` within a module;
b) PHP Class file ends with `Command` as suffix of the class;
c) PHP Class extends `Symfony\Component\Console\Command\Command`.
@return Command[] |
private function getCommandsFromModules()
{
$oConfig = Registry::getConfig();
if (! class_exists(ModuleList::class)) {
print "ERROR: Oxid ModuleList class can not be loaded, please run vendor/bin/oe-eshop-unified_namespace_generator";
} else {
try {
$moduleList = oxNew(ModuleList::class);
$modulesDir = $oConfig->getModulesDir();
$moduleList->getModulesFromDir($modulesDir);
} catch (\Throwable $exception) {
print "Shop is not able to list modules\n";
print $exception->getMessage();
return [];
}
}
$paths = $this->getPathsOfAvailableModules();
$pathToPhpFiles = $this->getPhpFilesMatchingPatternForCommandFromGivenPaths(
$paths
);
$classes = $this->getAllClassesFromPhpFiles($pathToPhpFiles);
$comanndClasses = $this->getCommandCompatibleClasses($classes);
return $this->getObjectsFromClasses($comanndClasses);
} | Collect all available commands from modules.
Dynamically scan all modules and include available command objects.
@return array |
private function getPathsOfAvailableModules()
{
$config = Registry::getConfig();
$modulesRootPath = $config->getModulesDir();
$modulePaths = $config->getConfigParam('aModulePaths');
if (!is_dir($modulesRootPath))
return [];
if (!is_array($modulePaths))
return [];
$fullModulePaths = array_map(function ($modulePath) use ($modulesRootPath) {
return $modulesRootPath . $modulePath;
}, array_values($modulePaths));
return array_filter($fullModulePaths, function ($fullModulePath) {
return is_dir($fullModulePath);
});
} | Return list of paths to all available modules.
@return string[] |
private function getPhpFilesMatchingPatternForCommandFromGivenPath($path)
{
$folders = ['Commands','commands','Command'];
foreach ($folders as $f) {
$cPath = $path . DIRECTORY_SEPARATOR . $f . DIRECTORY_SEPARATOR;
if (!is_dir($cPath)) {
continue;
}
$files = glob("$cPath*[cC]ommand\.php");
return $files;
}
return [];
} | Return list of PHP files matching `Command` specific pattern.
@param string $path Path to collect files from
@return string[] |
private function getPhpFilesMatchingPatternForCommandFromGivenPaths($paths)
{
return $this->getFlatArray(array_map(function ($path) {
return $this->getPhpFilesMatchingPatternForCommandFromGivenPath($path);
}, $paths));
} | Helper method for `getPhpFilesMatchingPatternForCommandFromGivenPath`
@param string[] $paths
@return string[] |
private function getAllClassesFromPhpFile($pathToPhpFile)
{
$classesBefore = get_declared_classes();
try {
require_once $pathToPhpFile;
} catch (\Throwable $exception) {
print "Can not add Command $pathToPhpFile:\n";
print $exception->getMessage() . "\n";
}
$classesAfter = get_declared_classes();
$newClasses = array_diff($classesAfter, $classesBefore);
if(count($newClasses) > 1) {
//try to find the correct class name to use
//this avoids warnings when module developer use there own command base class, that is not instantiable
$name = basename($pathToPhpFile,'.php');
foreach ($newClasses as $newClass) {
if ($newClass == $name){
return [$newClass];
}
}
}
return $newClasses;
} | Get list of defined classes from given PHP file.
@param string $pathToPhpFile
@return string[] |
private function getAllClassesFromPhpFiles($pathToPhpFiles)
{
return $this->getFlatArray(array_map(function ($pathToPhpFile) {
return $this->getAllClassesFromPhpFile($pathToPhpFile);
}, $pathToPhpFiles));
} | Helper method for `getAllClassesFromPhpFile`
@param string[] $pathToPhpFiles
@return string[] |
private function getObjectsFromClasses($classes)
{
$objects = array_map(function ($class) {
try {
return new $class;
} catch (\Throwable $ex) {
print "Can not add command from class $class:\n";
print $ex->getMessage() . "\n";
}
}, $classes);
$objects = array_filter($objects, function($o){return !is_null($o);} );
return $objects;
} | Convert given list of classes to objects.
@param string[] $classes
@return mixed[] |
public function getHydratorForEntity($value)
{
$entityMetadata = $this->getMetadataMap()[ClassUtils::getRealClass(get_class($value))];
$objectManagerClass = $this->getDoctrineHydratorConfig()[$entityMetadata['hydrator']]['object_manager'];
return new DoctrineHydrator($this->getServiceLocator()->get($objectManagerClass), true);
} | Look up the object manager for the given entity and create a basic hydrator |
public function extract($value)
{
if (is_null($value)) {
return $value;
}
$entityValues = $this->getHydratorForEntity($value)->extract($value);
$entityMetadata = $this->getMetadataMap()[ClassUtils::getRealClass(get_class($value))];
$link = new Link('self');
$link->setRoute($entityMetadata['route_name']);
$link->setRouteParams([
$entityMetadata['route_identifier_name'] => $entityValues[$entityMetadata['entity_identifier_name']]
]);
$linkCollection = new LinkCollection();
$linkCollection->add($link);
$halEntity = new HalEntity(new stdClass());
$halEntity->setLinks($linkCollection);
return $halEntity;
} | Return a HAL entity with just a self link |
public function setBillingCountry($value)
{
switch ($value) {
case 'DE':
case 'AT':
if (empty($this->iban) === false) {
$this->setIban($this->iban);
}
break;
case 'SE':
case 'FI':
$this->setIban('');
$this->setBic('');
break;
}
return parent::setBillingCountry($value);
} | @param $value
@return Entercash
@throws ErrorParameter |
public function setIban($value)
{
switch ($this->billing_country) {
case 'DE':
$this->validateIban(self::PATTERN_DE_IBAN, $value);
break;
case 'AT':
$this->validateIban(self::PATTERN_AT_IBAN, $value);
break;
case 'SE':
case 'FI':
$this->throwBankAttributesNotSupported();
break;
}
return parent::setIban($value);
} | @param $value
@return Entercash
@throws ErrorParameter |
protected function getPaymentTransactionStructure()
{
return [
'usage' => $this->usage,
'remote_ip' => $this->remote_ip,
'return_success_url' => $this->return_success_url,
'return_failure_url' => $this->return_failure_url,
'amount' => $this->transformAmount($this->amount, $this->currency),
'currency' => $this->currency,
'consumer_reference' => $this->consumer_reference,
'customer_email' => $this->customer_email,
'iban' => $this->iban,
'bic' => $this->bic,
'billing_address' => $this->getBillingAddressParamsStructure(),
'shipping_address' => $this->getShippingAddressParamsStructure()
];
} | Return additional request attributes
@return array |
public function setDocumentId($documentId)
{
if (preg_match($this->getDocumentIdRegex(), $documentId)) {
$this->document_id = $documentId;
return $this;
}
throw new InvalidArgument(
'document_id must be a string with 10 alphanumeric letters.' .
'5 letters, followed by 4 numbers, followed by 1 letter or number. Example: ABCDE1234F'
);
} | @param $documentId
@return $this
@throws InvalidArgument |
protected function populateStructure()
{
$treeStructure = [
'retrieval_request_request' => [
'arn' => $this->arn,
'original_transaction_unique_id' => $this->original_transaction_unique_id
]
];
$this->treeStructure = \Genesis\Utils\Common::createArrayObject($treeStructure);
} | Create the request's Tree structure
@return void |
protected function getRiskParamsStructure()
{
return [
'ssn' => $this->risk_ssn,
'mac_address' => $this->risk_mac_address,
'session_id' => $this->risk_session_id,
'user_id' => $this->risk_user_id,
'user_level' => $this->risk_user_level,
'email' => $this->risk_email,
'phone' => $this->risk_phone,
'remote_ip' => $this->risk_remote_ip,
'serial_number' => $this->risk_serial_number,
'pan_tail' => $this->risk_pan_tail,
'bin' => $this->risk_bin,
'first_name' => $this->risk_first_name,
'last_name' => $this->risk_last_name,
'country' => $this->risk_country,
'pan' => $this->risk_pan,
'forwarded_ip' => $this->risk_forwarded_ip,
'username' => $this->risk_username,
'password' => $this->risk_password,
'bin_name' => $this->risk_bin_name,
'bin_phone' => $this->risk_bin_phone
];
} | Builds an array list with all Risk Params
@return array |
protected function setRequiredFields()
{
parent::setRequiredFields();
$requiredFields = [
'transaction_id',
'amount',
'currency',
'return_success_url',
'return_failure_url',
'billing_country'
];
$this->requiredFields = \Genesis\Utils\Common::createArrayObject($requiredFields);
} | Set the required fields
@return void |
protected function populateStructure()
{
$treeStructure = [
'blacklist_request' => [
'card_number' => $this->card_number,
'terminal_token' => $this->terminal_token
]
];
$this->treeStructure = \Genesis\Utils\Common::createArrayObject($treeStructure);
} | Create the request's Tree structure
@return void |
public function populateNodes($structure)
{
try {
$this->output = json_encode($structure);
} catch (\Exception $e) {
throw new \Genesis\Exceptions\InvalidArgument('Invalid data/tree');
}
} | Convert multi-dimensional array to JSON object
@param array $structure
@throws \Genesis\Exceptions\InvalidArgument
@return void |
protected function setRequiredFields()
{
$requiredFields = [
'transaction_id',
'remote_ip',
'amount',
'currency',
'return_success_url',
'return_failure_url',
'payment_method_category',
'billing_country',
'shipping_country'
];
$this->requiredFields = \Genesis\Utils\Common::createArrayObject($requiredFields);
$requiredFieldValues = [
'payment_method_category' => [
self::PAYMENT_METHOD_CATEGORY_PAY_LATER,
self::PAYMENT_METHOD_CATEGORY_PAY_OVER_TIME
],
'billing_country' => static::getAllowedCountries(),
'shipping_country' => static::getAllowedCountries()
];
$this->requiredFieldValues = \Genesis\Utils\Common::createArrayObject($requiredFieldValues);
} | Set the required fields
@return void |
protected function getPaymentTransactionStructure()
{
return array_merge(
parent::getPaymentTransactionStructure(),
[
'customer_email' => $this->customer_email,
'customer_phone' => $this->customer_phone,
'payment_method_category' => $this->payment_method_category,
'customer_gender' => $this->customer_gender,
'billing_address' => $this->getBillingAddressParamsStructure(),
'shipping_address' => $this->getShippingAddressParamsStructure(),
'return_success_url' => $this->return_success_url,
'return_failure_url' => $this->return_failure_url
]
);
} | Return additional request attributes
@return array |
public function addItem(Item $item)
{
// set currency, so amounts transformations can be done
$item->setCurrency($this->currency);
array_push($this->items, $item);
return $this;
} | Add item
@param Item $item
@return $this |
public function toArray()
{
return [
'order_tax_amount' => CurrencyUtils::amountToExponent($this->getOrderTaxAmount(), $this->currency),
'items' => array_map(
function ($item) {
return ['item' => $item->toArray()];
},
$this->items
)
];
} | Return items request attributes
@return array |
protected function getPaymentTransactionStructure()
{
return [
'amount' => $this->transformAmount($this->amount, $this->currency),
'currency' => $this->currency,
'card_holder' => $this->card_holder,
'card_number' => $this->card_number,
'cvv' => $this->cvv,
'expiration_month' => $this->expiration_month,
'expiration_year' => $this->expiration_year,
'customer_email' => $this->customer_email,
'customer_phone' => $this->customer_phone,
'document_id' => $this->document_id,
'birth_date' => $this->birth_date,
'billing_address' => $this->getBillingAddressParamsStructure(),
'shipping_address' => $this->getShippingAddressParamsStructure()
];
} | Return additional request attributes
@return array |
public function setCustomerEmail($value)
{
if ($value !== null && filter_var($value, FILTER_VALIDATE_EMAIL) === false) {
throw new ErrorParameter('Please, enter a valid email');
}
$this->customer_email = $value;
return $this;
} | @param string $value
@return $this
@throws ErrorParameter |
protected function setRequiredFields()
{
$requiredFields = [
'transaction_id',
'card_type',
'redeem_type',
'amount',
'currency',
'card_holder',
'card_number',
'expiration_month',
'expiration_year'
];
$this->requiredFields = \Genesis\Utils\Common::createArrayObject($requiredFields);
$requiredFieldValues = array_merge(
[
'card_type' => CardTypes::getCardTypes(),
'redeem_type' => RedeemTypes::getRedeemTypes(),
'currency' => Currency::getList()
],
$this->getCCFieldValueFormatValidators()
);
$this->requiredFieldValues = \Genesis\Utils\Common::createArrayObject($requiredFieldValues);
} | Set the required fields
@return void |
protected function getPaymentTransactionStructure()
{
return [
'card_type' => $this->card_type,
'redeem_type' => $this->redeem_type,
'amount' => $this->transformAmount($this->amount, $this->currency),
'currency' => $this->currency,
'card_holder' => $this->card_holder,
'card_number' => $this->card_number,
'cvv' => $this->cvv,
'expiration_month' => $this->expiration_month,
'expiration_year' => $this->expiration_year,
'customer_email' => $this->customer_email,
'customer_phone' => $this->customer_phone,
'birth_date' => $this->birth_date,
'billing_address' => $this->getBillingAddressParamsStructure(),
'shipping_address' => $this->getShippingAddressParamsStructure(),
'dynamic_descriptor_params' => $this->getDynamicDescriptorParamsStructure()
];
} | Return additional request attributes
@return array |
protected static function _tableExists($sTable)
{
$oConfig = Registry::getConfig();
$sDbName = $oConfig->getConfigParam('dbName');
$sQuery = "
SELECT 1
FROM information_schema.tables
WHERE table_schema = ?
AND table_name = ?
";
return (bool)DatabaseProvider::getDb()->getOne($sQuery, array($sDbName, $sTable));
} | Table exists in database?
@param string $sTable Table name
@return bool |
protected static function _columnExists($sTable, $sColumn)
{
$oConfig = Registry::getConfig();
$sDbName = $oConfig->getConfigParam('dbName');
$sSql = 'SELECT 1
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = ?
AND TABLE_NAME = ?
AND COLUMN_NAME = ?';
$oDb = DatabaseProvider::getDb();
return (bool)$oDb->getOne($sSql, array($sDbName, $sTable, $sColumn));
} | Column exists in specific table?
@param string $sTable Table name
@param string $sColumn Column name
@return bool |
protected function getPaymentTransactionStructure()
{
return [
'reference_id' => $this->reference_id,
'amount' => $this->transformAmount($this->amount, $this->currency),
'currency' => $this->currency
];
} | Return additional request attributes
@return array |
public function execute()
{
set_error_handler([$this, 'processErrors'], E_WARNING);
$stream = fopen($this->requestData['url'], 'r', false, $this->streamContext);
$this->responseBody = stream_get_contents($stream);
$this->responseHeaders = $http_response_header;
$this->response = implode("\r\n", $http_response_header) . "\r\n\r\n" . $this->responseBody;
restore_error_handler();
} | Send the request
@return void |
public static function getPHPVersion()
{
// PHP_VERSION_ID is available as of PHP 5.2.7, if the current version is older than that - emulate it
if (!defined('PHP_VERSION_ID')) {
list($major, $minor, $release) = explode('.', PHP_VERSION);
/**
* Define PHP_VERSION_ID if its not present (unsupported version)
*
* format: major minor release
*/
define('PHP_VERSION_ID', (($major * 10000) + ($minor * 100) + $release));
}
return (int)PHP_VERSION_ID;
} | Helper to get the current PHP version
@return int |
public static function pascalToSnakeCase($input)
{
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
foreach ($matches[0] as &$match) {
$match = ($match == strtoupper($match)) ? strtolower($match) : lcfirst($match);
}
return implode('_', $matches[0]);
} | Convert PascalCase string to a SnakeCase
useful for argument parsing
@param string $input
@return string |
public static function resolveDynamicMethod($input)
{
$snakeCase = explode('_', self::pascalToSnakeCase($input));
$result = [
current(
array_slice($snakeCase, 0, 1)
),
implode(
'_',
array_slice($snakeCase, 1)
)
];
return $result;
} | Get PascalCase to action/target array
@param $input
@return array |
public static function emptyValueRecursiveRemoval($haystack)
{
foreach ($haystack as $key => $value) {
if (is_array($value)) {
$haystack[$key] = self::emptyValueRecursiveRemoval($haystack[$key]);
}
if (empty($haystack[$key])) {
unset($haystack[$key]);
}
}
return $haystack;
} | Helper function - iterate over array ($haystack) and
remove every key with empty value
@param array $haystack - input array
@return array |
public static function isValidArray($arr)
{
if (!is_array($arr) || empty($arr) || count($arr) < 1) {
return false;
}
return true;
} | Check if the passed argument is:
- Array
- Its not empty
@param array $arr incoming array
@return bool |
public static function isArrayKeyExists($key, $arr)
{
if (!self::isValidArray($arr)) {
return false;
}
return array_key_exists($key, $arr);
} | Check if the passed key exists in the supplied array
@param string $key
@param array $arr
@return bool |
public static function getSortedArrayByValue($arr)
{
$duplicate = self::copyArray($arr);
if ($duplicate === null) {
return null;
}
asort($duplicate);
return $duplicate;
} | Sorts an array by value and returns a new instance
@param array $arr
@return array |
public static function appendItemsToArrayObj(&$arrObj, $key, $values)
{
if (! $arrObj instanceof \ArrayObject) {
return null;
}
$arr = $arrObj->getArrayCopy();
$commonArrKeyValues =
Common::isArrayKeyExists($key, $arr)
? $arr[$key]
: [];
$arr[$key] = array_merge($commonArrKeyValues, $values);
return $arrObj = self::createArrayObject($arr);
} | Appends items to an ArrayObject by key
@param \ArrayObject $arrObj
@param string $key
@param array $values
@return \ArrayObject|null |
public static function isValidXMLName($tag)
{
if (!is_array($tag)) {
return preg_match('/^[a-z_]+[a-z0-9\:\-\.\_]*[^:]*$/i', $tag, $matches) && reset($matches) == $tag;
}
return false;
} | Check if the passed argument is a valid XML tag name
@param string $tag
@return bool |
public static function stringToBoolean($string)
{
$flag = filter_var($string, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if ($flag) {
return true;
} elseif (is_null($flag)) {
return $string;
}
return false;
} | Evaluate a boolean expression from String
or return the string itself
@param $string
@return bool | string |
public static function isBase64Encoded($input)
{
if ($input && @base64_encode(@base64_decode($input, true)) === $input) {
return true;
}
return false;
} | Check if a string is base64 Encoded
@param string $input Data to verify if its valid base64
@return bool |
public static function arrayContainsArrayItems($arr)
{
if (!self::isValidArray($arr)) {
return false;
}
foreach ($arr as $item) {
if (self::isValidArray($item)) {
return true;
}
}
return false;
} | Check if an array has array items
@param array $arr
@return bool |
public static function isClassAbstract($className)
{
if (!class_exists($className)) {
return false;
}
$reflectionClass = new \ReflectionClass($className);
return $reflectionClass->isAbstract();
} | Determines if the given class is Instantiable or not
Helps to prevent from creating an instance of an abstract class
@param string $className
@return bool |
public static function endsWith($str, $suffix)
{
return stripos($str, $suffix) === strlen($str) - strlen($suffix);
} | Checks if $str ends with $suffix.
@param $str
@param $suffix
@return bool |
protected function setRequiredFieldsConditional()
{
$requiredFieldsConditional = [
'currency' => [
'IDR' => ['bank_code'],
'CNY' => ['bank_branch', 'bank_name'],
'THB' => ['bank_name']
]
];
$this->requiredFieldsConditional = \Genesis\Utils\Common::createArrayObject($requiredFieldsConditional);
$requiredFieldValuesConditional = [
'currency' => [
'CNY' => [
[
'bank_account_number' => new RegexValidator('/^[0-9]{19}$/')
]
]
]
];
$this->requiredFieldValuesConditional = \Genesis\Utils\Common::createArrayObject($requiredFieldValuesConditional);
} | Set the required fields conditional
@return void |
protected function getPaymentTransactionStructure()
{
return [
'amount' => $this->transformAmount($this->amount, $this->currency),
'currency' => $this->currency,
'customer_email' => $this->customer_email,
'customer_phone' => $this->customer_phone,
'return_success_url' => $this->return_success_url,
'return_failure_url' => $this->return_failure_url,
'bank_code' => $this->bank_code,
'bank_name' => $this->bank_name,
'bank_branch' => $this->bank_branch,
'bank_account_name' => $this->bank_account_name,
'bank_account_number' => $this->bank_account_number,
'billing_address' => $this->getBillingAddressParamsStructure(),
'shipping_address' => $this->getShippingAddressParamsStructure()
];
} | Return additional request attributes
@return array |
public function setPaymentType($paymentType)
{
$allowedPaymentTypes = [
self::PAYMENT_TYPE_ONLINE_BANKING, self::PAYMENT_TYPE_QR_PAYMENT, self::PAYMENT_TYPE_QUICK_PAYMENT
];
if (in_array($paymentType, $allowedPaymentTypes)) {
$this->payment_type = $paymentType;
return $this;
}
throw new InvalidArgument(
'Invalid value for payment_type. Allowed values are ' . implode(', ', $allowedPaymentTypes)
);
} | @param $paymentType
@return $this
@throws InvalidArgument |
protected function getPaymentTransactionStructure()
{
return [
'amount' => $this->transformAmount($this->amount, $this->currency),
'currency' => $this->currency,
'bank_code' => $this->bank_code,
'return_success_url' => $this->return_success_url,
'return_failure_url' => $this->return_failure_url,
'customer_email' => $this->customer_email,
'customer_phone' => $this->customer_phone,
'payment_type' => $this->payment_type,
'document_id' => $this->document_id,
'billing_address' => $this->getBillingAddressParamsStructure(),
'shipping_address' => $this->getShippingAddressParamsStructure()
];
} | Return additional request attributes
@return array |
protected function setRequiredFields()
{
$requiredFields = [
'transaction_id',
'amount',
'currency',
'card_holder',
'card_number',
'expiration_month',
'expiration_year'
];
$this->requiredFields = \Genesis\Utils\Common::createArrayObject($requiredFields);
$requiredFieldValues = array_merge(
[
'currency' => \Genesis\Utils\Currency::getList()
],
$this->getCCFieldValueFormatValidators()
);
$this->requiredFieldValues = \Genesis\Utils\Common::createArrayObject($requiredFieldValues);
$requiredFieldsConditional = [
'notification_url' => ['return_success_url', 'return_failure_url'],
'return_success_url' => ['notification_url', 'return_failure_url'],
'return_failure_url' => ['notification_url', 'return_success_url']
];
$this->requiredFieldsConditional = \Genesis\Utils\Common::createArrayObject($requiredFieldsConditional);
$requiredFieldsGroups = [
'synchronous' => ['notification_url', 'return_success_url', 'return_failure_url'],
'asynchronous' => ['mpi_eci']
];
$this->requiredFieldsGroups = \Genesis\Utils\Common::createArrayObject($requiredFieldsGroups);
} | Set the required fields
@return void |
protected function getPaymentTransactionStructure()
{
return [
'gaming' => $this->gaming,
'moto' => $this->moto,
'notification_url' => $this->notification_url,
'return_success_url' => $this->return_success_url,
'return_failure_url' => $this->return_failure_url,
'amount' => $this->transformAmount($this->amount, $this->currency),
'currency' => $this->currency,
'card_holder' => $this->card_holder,
'card_number' => $this->card_number,
'cvv' => $this->cvv,
'expiration_month' => $this->expiration_month,
'expiration_year' => $this->expiration_year,
'customer_email' => $this->customer_email,
'customer_phone' => $this->customer_phone,
'document_id' => $this->document_id,
'birth_date' => $this->birth_date,
'billing_address' => $this->getBillingAddressParamsStructure(),
'shipping_address' => $this->getShippingAddressParamsStructure(),
'mpi_params' => $this->getMpiParamsStructure(),
'risk_params' => $this->getRiskParamsStructure(),
'dynamic_descriptor_params' => $this->getDynamicDescriptorParamsStructure()
];
} | Return additional request attributes
@return array |
public static function verify()
{
// PHP interpreter version
self::checkSystemVersion();
// BCMath
self::isFunctionExists('bcmul', self::getErrorMessage('bcmath'));
self::isFunctionExists('bcdiv', self::getErrorMessage('bcmath'));
// Filter
self::isFunctionExists('filter_var', self::getErrorMessage('filter'));
// Hash
self::isFunctionExists('hash', self::getErrorMessage('hash'));
// XMLReader
self::isClassExists('XMLReader', self::getErrorMessage('xmlreader'));
// XMLWriter
if (\Genesis\Config::getInterface('builder') == 'xml') {
self::isClassExists('XMLWriter', self::getErrorMessage('xmlwriter'));
}
// cURL
if (\Genesis\Config::getInterface('network') == 'curl') {
self::isFunctionExists('curl_init', self::getErrorMessage('curl'));
}
} | Check if the current system fulfils the project's dependencies
@throws \Exception |
public static function checkSystemVersion()
{
if (\Genesis\Utils\Common::compareVersions(self::$minPHPVersion, '<')) {
throw new \Exception(self::getErrorMessage('system'));
}
} | Check the PHP interpreter version we're currently running
@throws \Exception |
public static function getErrorMessage($name)
{
$messages = [
'system' => 'Unsupported PHP version, please upgrade!' . PHP_EOL .
'This library requires PHP version ' . self::$minPHPVersion . ' or newer.',
'bcmath' => 'BCMath extension is required!' . PHP_EOL .
'Please install the extension or rebuild with "--enable-bcmath" option.',
'filter' => 'Filter extensions is required!' . PHP_EOL .
'Please install the extension or rebuild with "--enable-filter" option.',
'hash' => 'Hash extension is required!' . PHP_EOL .
'Please install the extension or rebuild with "--enable-hash" option.',
'xmlreader' => 'XMLReader extension is required!' . PHP_EOL .
'Please install the extension or rebuild with "--enable-xmlreader" option.',
'xmlwriter' => 'XMLWriter extension is required!' . PHP_EOL .
'Please install the extension or rebuild with "--enable-xmlwriter" option.',
'curl' => 'cURL interface is selected, but its not installed on your system!' . PHP_EOL .
'Please install the extension or select "stream" as your network interface.'
];
if (array_key_exists($name, $messages)) {
return $messages[$name];
}
return '[' . $name . '] Missing project dependency!';
} | Get error message for certain type
@param string $name
@return string |
protected function verifyConditionalValuesRequirements()
{
if (!isset($this->requiredFieldValuesConditional)) {
return;
}
$fields = $this->requiredFieldValuesConditional->getArrayCopy();
foreach ($fields as $parentFieldName => $parentFieldDependencies) {
if (!isset($this->$parentFieldName)) {
continue;
}
foreach ($parentFieldDependencies as $parentFieldValue => $childFieldsDependency) {
if ($this->$parentFieldName !== $parentFieldValue) {
continue;
}
$childFieldGroupValuesValidated = false;
foreach ($childFieldsDependency as $childFieldDependency) {
$childFieldValuesValidated = true;
foreach ($childFieldDependency as $childFieldName => $childFieldValues) {
if ($childFieldValues instanceof RequestValidator) {
try {
$childFieldValues->run($this, $childFieldName);
} catch (\Genesis\Exceptions\InvalidArgument $e) {
$childFieldValuesValidated = false;
}
continue;
}
if (CommonUtils::isValidArray($childFieldValues)) {
if (!in_array($this->$childFieldName, $childFieldValues)) {
$childFieldValuesValidated = false;
}
continue;
}
if ($this->$childFieldName !== $childFieldValues) {
$childFieldValuesValidated = false;
}
}
if ($childFieldValuesValidated) {
$childFieldGroupValuesValidated = true;
break;
}
}
if (!$childFieldGroupValuesValidated) {
throw new \Genesis\Exceptions\ErrorParameter(
sprintf(
'%s with value %s is depending on group of params with specific values. ' .
'Please, refer to the official API documentation for %s transaction type.',
$parentFieldName,
$parentFieldValue,
$this->getTransactionType()
)
);
}
}
}
} | Verify that all fields (who depend on previously populated fields)
are populated with expected values
@throws \Genesis\Exceptions\ErrorParameter
@SuppressWarnings(PHPMD.CyclomaticComplexity)
@SuppressWarnings(PHPMD.NPathComplexity) |
protected function populateStructure()
{
$treeStructure = [
'payment_transaction' => [
'transaction_type' => $this->getTransactionType(),
'transaction_id' => $this->transaction_id,
'usage' => $this->usage,
'remote_ip' => $this->remote_ip
]
];
$treeStructure['payment_transaction'] += $this->getPaymentTransactionStructure();
$this->treeStructure = \Genesis\Utils\Common::createArrayObject($treeStructure);
} | Create the request's Tree structure
@return void |
public function populateNodes($data)
{
if (!\Genesis\Utils\Common::isValidArray($data)) {
throw new \Genesis\Exceptions\InvalidArgument('Invalid data structure');
}
// Ensure that the Array position is 0
reset($data);
$this->iterateArray(key($data), reset($data));
// Finish the document
$this->context->endDocument();
} | Insert tree-structured array as nodes in XMLWriter
and end the current Document.
@param array $data - tree-structured array
@throws \Genesis\Exceptions\InvalidArgument
@return void |
public function iterateArray($name, $data)
{
if (\Genesis\Utils\Common::isValidXMLName($name)) {
$this->context->startElement($name);
}
foreach ($data as $key => $value) {
if (is_null($value)) {
continue;
}
// Note: XMLWriter discards Attribute writes if they are written
// after an Element, so make sure the attributes are at the top
if ($key === '@attributes') {
$this->writeAttribute($value);
continue;
}
if ($key === '@cdata') {
$this->writeCData($value);
continue;
}
if ($key === '@value') {
$this->writeText($value);
continue;
}
$this->writeElement($key, $value);
}
if (\Genesis\Utils\Common::isValidXMLName($name)) {
$this->context->endElement();
}
} | Recursive iteration over array
@param string $name name of the current leave
@param array $data value of the current leave
@return void |
public function writeAttribute($value)
{
if (is_array($value)) {
foreach ($value as $attrName => $attrValue) {
$this->context->writeAttribute($attrName, $attrValue);
}
}
} | Write Element's Attribute
@param $value |
public function writeCData($value)
{
if (is_array($value)) {
foreach ($value as $attrValue) {
$this->context->writeCData($attrValue);
}
} else {
$this->context->writeCData($value);
}
} | Write Element's CData
@param $value
@SuppressWarnings(PHPMD.ElseExpression) |
public function writeText($value)
{
if (is_array($value)) {
foreach ($value as $attrValue) {
$this->context->text($attrValue);
}
} else {
$this->context->text($value);
}
} | Write Element's Text
@param $value
@SuppressWarnings(PHPMD.ElseExpression) |
public function writeElement($key, $value)
{
if (is_array($value)) {
$this->iterateArray($key, $value);
} else {
$value = \Genesis\Utils\Common::booleanToString($value);
$this->context->writeElement($key, $value);
}
} | Write XML Element
@param $key
@param $value
@SuppressWarnings(PHPMD.ElseExpression) |
protected function populateStructure()
{
$treeStructure = [
'payment_transaction' => [
'transaction_type' => \Genesis\API\Constants\Transaction\Types::PAYBYVOUCHER_YEEPAY,
'transaction_id' => $this->transaction_id,
'card_type' => $this->card_type,
'redeem_type' => $this->redeem_type,
'remote_ip' => $this->remote_ip,
'amount' => $this->transform(
'amount',
[
$this->amount,
$this->currency
]
),
'currency' => $this->currency,
'product_name' => $this->product_name,
'product_category' => $this->product_category,
'customer_name' => $this->customer_name,
'customer_email' => $this->customer_email,
'customer_phone' => $this->customer_phone,
'customer_id_number' => $this->customer_id_number,
'customer_bank_id' => $this->customer_bank_id,
'bank_account_number' => $this->bank_account_number
]
];
$this->treeStructure = \Genesis\Utils\Common::createArrayObject($treeStructure);
} | Create the request's Tree structure
@return void |
protected function initConfiguration()
{
$this->config = \Genesis\Utils\Common::createArrayObject(
[
'protocol' => 'https',
'port' => 443,
'type' => 'GET',
'format' => 'plain'
]
);
$this->initApiGatewayConfiguration('retrieve_abn_ideal_banks', false);
} | Set the per-request configuration
@return void |
public static function range($start, $count)
{
if ($count < 0) {
throw new OutOfRangeException('$count must be not be negative.');
}
return new Linq(range($start, $start + $count - 1));
} | Generates a sequence of integral numbers within a specified range.
@param int $start The value of the first integer in the sequence.
@param int $count The number of sequential integers to generate.
@return Linq An sequence that contains a range of sequential int numbers.
@throws \OutOfRangeException |
public function skip($count)
{
// If its an array iterator we must check the arrays bounds are greater than the skip count.
// This is because the LimitIterator will use the seek() method which will throw an exception if $count > array.bounds.
$innerIterator = $this->iterator;
if ($innerIterator instanceof \ArrayIterator) {
if ($count >= $innerIterator->count()) {
return new Linq([]);
}
}
if (!($innerIterator instanceof \Iterator)) {
// IteratorIterator wraps $innerIterator because it is Traversable but not an Iterator.
// (see https://bugs.php.net/bug.php?id=52280)
$innerIterator = new \IteratorIterator($innerIterator);
}
return new Linq(new \LimitIterator($innerIterator, $count, -1));
} | Bypasses a specified number of elements and then returns the remaining elements.
@param int $count The number of elements to skip before returning the remaining elements.
@return Linq A Linq object that contains the elements that occur after the specified index. |
public function take($count)
{
if ($count == 0) {
return new Linq([]);
}
$innerIterator = $this->iterator;
if (!($innerIterator instanceof \Iterator)) {
// IteratorIterator wraps $this->iterator because it is Traversable but not an Iterator.
// (see https://bugs.php.net/bug.php?id=52280)
$innerIterator = new \IteratorIterator($innerIterator);
}
return new Linq(new \LimitIterator($innerIterator, 0, $count));
} | Returns a specified number of contiguous elements from the start of a sequence
@param int $count The number of elements to return.
@return Linq A Linq object that contains the specified number of elements from the start. |
public function aggregate(callable $func, $seed = null)
{
$result = null;
$first = true;
if ($seed !== null) {
$result = $seed;
$first = false;
}
foreach ($this->iterator as $current) {
if (!$first) {
$result = $func($result, $current);
} else {
$result = $current;
$first = false;
}
}
if ($first) {
throw new \RuntimeException("The input sequence contains no elements.");
}
return $result;
} | Applies an accumulator function over a sequence.
The aggregate method makes it simple to perform a calculation over a sequence of values.
This method works by calling $func one time for each element.
The first element of source is used as the initial aggregate value if $seed parameter is not specified.
If $seed is specified, this value will be used as the first value.
@param callable $func An accumulator function to be invoked on each element.
@param mixed $seed
@throws \RuntimeException if the input sequence contains no elements.
@return mixed Returns the final result of $func. |
public function chunk($chunksize)
{
if ($chunksize < 1) {
throw new \InvalidArgumentException("'{$chunksize}' is not a valid chunk size.");
}
return Linq::from(new ChunkIterator($this->iterator, $chunksize));
} | Splits the sequence in chunks according to $chunksize.
@param int $chunksize Specifies how many elements are grouped together per chunk.
@throws \InvalidArgumentException
@return Linq |
public function all(callable $func)
{
foreach ($this->iterator as $current) {
$match = LinqHelper::getBoolOrThrowException($func($current));
if (!$match) {
return false;
}
}
return true;
} | Determines whether all elements satisfy a condition.
@param callable $func A function to test each element for a condition.
@return bool True if every element passes the test in the specified func, or if the sequence is empty; otherwise, false. |
public function any(callable $func = null)
{
foreach ($this->iterator as $current) {
if ($func === null) {
return true;
}
$match = LinqHelper::getBoolOrThrowException($func($current));
if ($match) {
return true;
}
}
return false;
} | Determines whether any element exists or satisfies a condition by invoking $func.
@param callable $func A function to test each element for a condition or NULL to determine if any element exists.
@return bool True if no $func given and the source sequence contains any elements or True if any elements passed the test in the specified func; otherwise, false. |
public function count()
{
if ($this->iterator instanceof Countable) {
return $this->iterator->count();
}
return iterator_count($this->iterator);
} | Counts the elements of this Linq sequence.
@return int |
public function average(callable $func = null)
{
$resultTotal = 0;
$itemCount = 0;
$source = $this->getSelectIteratorOrInnerIterator($func);
foreach ($source as $item) {
if (!is_numeric($item)) {
throw new UnexpectedValueException("Cannot calculate an average on a none numeric value");
}
$resultTotal += $item;
$itemCount++;
}
return $itemCount == 0 ? 0 : ($resultTotal / $itemCount);
} | Computes the average of all numeric values. Uses $func to obtain the value on each element.
@param callable $func A func that returns any numeric type (int, float etc.)
@throws \UnexpectedValueException if an item of the sequence is not a numeric value.
@return double Average of items |
public function sum(callable $func = null)
{
$sum = 0;
$iterator = $this->getSelectIteratorOrInnerIterator($func);
foreach ($iterator as $value) {
if (!is_numeric($value)) {
throw new UnexpectedValueException("sum() only works on numeric values.");
}
$sum += $value;
}
return $sum;
} | Gets the sum of all items or by invoking a transform function on each item to get a numeric value.
@param callable $func A func that returns any numeric type (int, float etc.) from the given element, or NULL to use the element itself.
@throws \UnexpectedValueException if any element is not a numeric value.
@return double The sum of all items. |
public function min(callable $func = null)
{
$min = null;
$iterator = $this->getSelectIteratorOrInnerIterator($func);
foreach ($iterator as $value) {
if (!is_numeric($value) && !is_string($value) && !($value instanceof \DateTime)) {
throw new UnexpectedValueException("min() only works on numeric values, strings and DateTime objects.");
}
if (is_null($min)) {
$min = $value;
} elseif ($min > $value) {
$min = $value;
}
}
if ($min === null) {
throw new \RuntimeException("Cannot calculate min() as the Linq sequence contains no elements.");
}
return $min;
} | Gets the minimum item value of all items or by invoking a transform function on each item to get a numeric value.
@param callable $func A func that returns any numeric type (int, float etc.) from the given element, or NULL to use the element itself.
@throws \RuntimeException if the sequence contains no elements
@throws \UnexpectedValueException
@return double Minimum item value |
public function max(callable $func = null)
{
$max = null;
$iterator = $this->getSelectIteratorOrInnerIterator($func);
foreach ($iterator as $value) {
if (!is_numeric($value) && !is_string($value) && !($value instanceof \DateTime)) {
throw new UnexpectedValueException("max() only works on numeric values, strings and DateTime objects.");
}
if (is_null($max)) {
$max = $value;
} elseif ($max < $value) {
$max = $value;
}
}
if ($max === null) {
throw new \RuntimeException("Cannot calculate max() as the Linq sequence contains no elements.");
}
return $max;
} | Returns the maximum item value according to $func
@param callable $func A func that returns any numeric type (int, float etc.)
@throws \RuntimeException if the sequence contains no elements
@throws \UnexpectedValueException if any element is not a numeric value or a string.
@return double Maximum item value |
public function concat($second)
{
LinqHelper::assertArgumentIsIterable($second, "second");
$allItems = new \ArrayIterator([$this->iterator, $second]);
return new Linq(new SelectManyIterator($allItems));
} | Concatenates this Linq object with the given sequence.
@param array|\Iterator $second A sequence which will be concatenated with this Linq object.
@throws InvalidArgumentException if the given sequence is not traversable.
@return Linq A new Linq object that contains the concatenated elements of the input sequence and the original Linq sequence. |
public function intersect($second)
{
LinqHelper::assertArgumentIsIterable($second, "second");
return new Linq(new IntersectIterator($this->iterator, LinqHelper::getIteratorOrThrow($second)));
} | Intersects the Linq sequence with second Iterable sequence.
@param \Iterator|array An iterator to intersect with:
@return Linq intersected items |
public function except($second)
{
LinqHelper::assertArgumentIsIterable($second, "second");
return new Linq(new ExceptIterator($this->iterator, LinqHelper::getIteratorOrThrow($second)));
} | Returns all elements except the ones of the given sequence.
@param array|\Iterator $second
@return Linq Returns all items of this not occuring in $second |
public function toArray(callable $keySelector = null, callable $valueSelector = null)
{
if ($keySelector === null && $valueSelector === null) {
return iterator_to_array($this, false);
} elseif ($keySelector == null) {
return iterator_to_array(new SelectIterator($this->getIterator(), $valueSelector), false);
} else {
$array = [];
foreach ($this as $value) {
$key = $keySelector($value);
$array[$key] = $valueSelector == null ? $value : $valueSelector($value);
}
return $array;
}
} | Creates an Array from this Linq object with key/value selector(s).
@param callable $keySelector a func that returns the array-key for each element.
@param callable $valueSelector a func that returns the array-value for each element.
@return array An array with all values. |
protected function getShippingAddressParamsStructure()
{
return [
'first_name' => $this->shipping_first_name,
'last_name' => $this->shipping_last_name,
'address1' => $this->shipping_address1,
'address2' => $this->shipping_address2,
'zip_code' => $this->shipping_zip_code,
'city' => $this->shipping_city,
'state' => $this->shipping_state,
'country' => $this->shipping_country
];
} | Builds an array list with all Params
@return array |