code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
public static function getCountryName($iso_code)
{
if (isset(self::$countries[$iso_code])) {
return self::$countries[$iso_code];
}
return false;
} | Get a country's name by its ISO Code
@param $iso_code - country's iso code
@return mixed - string if code is present, false otherwise |
protected function getPaymentTransactionStructure()
{
return [
'amount' => $this->transformAmount($this->amount, $this->currency),
'currency' => $this->currency,
'iban' => $this->iban,
'bic' => $this->bic,
'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 setBic($value)
{
if (in_array(strlen($value), $this->getAllowedBicSizes()) === false) {
throw new ErrorParameter(
'Bic must be with one of these lengths: ' . implode(', ', $this->getAllowedBicSizes())
);
}
$this->bic = $value;
return $this;
} | SWIFT/BIC code of the customer’s bank
@param $value
@return $this
@throws ErrorParameter |
public function run($sTimestamp = null, OutputInterface $oOutput = null)
{
if (null === $sTimestamp) {
$sTimestamp = AbstractQuery::getCurrentTimestamp();
}
foreach ($this->getQueries() as $oQuery) {
$oQuery->getTimestamp() < $sTimestamp
? $this->_goUp($oQuery, $oOutput)
: $this->_goDown($oQuery, $oOutput);
}
} | Run migration
@param string|null $sTimestamp The time at which the migrations aims. Only migrations up to this point are being executed
@param OutputInterface|null $oOutput Out handler for console output |
protected function _goUp(AbstractQuery $oQuery, outputInterface $oOutput = null)
{
if ($this->isExecuted($oQuery)) {
return false;
}
if ($oOutput) {
$oOutput->writeLn(
sprintf(
'[DEBUG] Migrating up %s %s',
$oQuery->getTimestamp(),
$oQuery->getClassName()
)
);
}
$oQuery->up();
$this->setExecuted($oQuery);
return true;
} | Executes an UP Migration
@param AbstractQuery $oQuery The query object that is being executed
@param OutputInterface $oOutput The output handler for the console output that might be generated
@return bool |
protected function _goDown(AbstractQuery $oQuery, OutputInterface $oOutput = null)
{
if (!$this->isExecuted($oQuery)) {
return false;
}
if ($oOutput) {
$oOutput->writeLn(
sprintf(
'[DEBUG] Migrating down %s %s',
$oQuery->getTimestamp(),
$oQuery->getClassName()
)
);
}
$oQuery->down();
$this->setUnexecuted($oQuery);
return true;
} | Executes a DOWN Migration
@param AbstractQuery $oQuery The query object that is being executed
@param OutputInterface $oOutput The output handler for the console output that might be generated
@return bool |
public function isExecuted(AbstractQuery $oQuery)
{
foreach ($this->_aExecutedQueryNames as $executedQuery) {
if ($oQuery->getFilename() == $executedQuery['version']) {
return true;
}
}
return false;
} | Is query already executed?
@param AbstractQuery $oQuery The query object that is being checked for
@return bool |
public function setExecuted(AbstractQuery $oQuery)
{
$sSQL = 'REPLACE INTO oxmigrationstatus SET version = ?';
DatabaseProvider::getDb()->execute($sSQL, array($oQuery->getFilename()));
} | Set query as executed
@param AbstractQuery $oQuery The query object that is being set to executed |
public function setUnexecuted(AbstractQuery $oQuery)
{
$sSQL = 'DELETE FROM oxmigrationstatus WHERE version = ?';
DatabaseProvider::getDb()->execute($sSQL, array($oQuery->getFilename()));
} | Set query as not executed
@param AbstractQuery $oQuery The query object that is being set to not executed |
protected function _buildMigrationQueries()
{
if (!is_dir($this->_sMigrationQueriesDir)) {
return false;
}
$oDirectory = new \RecursiveDirectoryIterator($this->_sMigrationQueriesDir);
$oFlattened = new \RecursiveIteratorIterator($oDirectory);
$aFiles = new \RegexIterator($oFlattened, AbstractQuery::REGEXP_FILE);
foreach ($aFiles as $sFilePath) {
include_once $sFilePath;
$sClassName = $this->_getClassNameFromFilePath($sFilePath);
/** @var AbstractQuery $oQuery */
$oQuery = oxNew($sClassName);
$this->addQuery($oQuery);
}
return true;
} | Load and build migration files
@throws MigrationException
@return bool |
protected function _getClassNameFromFilePath($sFilePath)
{
$sFileName = basename($sFilePath);
$aMatches = array();
if (!preg_match(AbstractQuery::REGEXP_FILE, $sFileName, $aMatches)) {
throw new MigrationException('Could not extract class name from file name');
}
return $aMatches[2] . 'migration';
} | Get migration queries class name parsed from file path
@param string $sFilePath The path of the file to extract the class name from
@throws MigrationException
@return string Class name in lower case most cases |
public function execute(InputInterface $input, OutputInterface $output)
{
$clearAllCache = !$input->getOption('smarty') && !$input->getOption('files') && !$input->getOption('oxcache');
$cachePath = $this->_appendDirectorySeparator(Registry::getConfig()->getConfigParam('sCompileDir'));
if (!is_dir($cachePath)) {
$output->writeLn("Seems that compile directory '$cachePath' does not exist");
exit(1);
}
if (($clearAllCache || $input->getOption('oxcache')) && class_exists('oxCache')) {
$output->writeLn('Clearing oxCache...');
Registry::get('oxCache')->reset(false);
} else {
$output->writeLn('Skipping oxCache...');
}
if ($clearAllCache || $input->getOption('smarty')) {
$output->writeLn('Clearing smarty cache...');
$this->_clearDirectory($cachePath . 'smarty');
} else {
$output->writeLn('Skipping smarty cache...');
}
if ($clearAllCache || $input->getOption('files')) {
$output->writeLn('Clearing files cache...');
$this->_clearDirectory($cachePath, array('.htaccess', 'smarty'));
} else {
$output->writeLn('Skipping files cache...');
}
$output->writeLn('Cache cleared successfully');
} | {@inheritdoc} |
protected function _clearDirectory($sDir, $aKeep = array())
{
$sDir = $this->_appendDirectorySeparator($sDir);
foreach (glob($sDir . '*') as $sFilePath) {
$sFileName = basename($sFilePath);
if (in_array($sFileName, $aKeep)) {
continue;
}
is_dir($sFilePath)
? $this->_removeDirectory($sFilePath)
: unlink($sFilePath);
}
} | Clear files in given directory, except those which
are in $aKeep array
@param string $sDir
@param array $aKeep |
protected function _removeDirectory($sPath)
{
if (!is_dir($sPath)) {
return;
}
$oIterator = new \RecursiveDirectoryIterator($sPath, \RecursiveDirectoryIterator::SKIP_DOTS);
$oFiles = new \RecursiveIteratorIterator($oIterator, \RecursiveIteratorIterator::CHILD_FIRST);
foreach ($oFiles as $oFile) {
if ($oFile->getFilename() == '.' || $oFile->getFilename() === '..') {
continue;
}
$oFile->isDir()
? rmdir($oFile->getRealPath())
: unlink($oFile->getRealPath());
}
rmdir($sPath);
} | Remove directory
@param string $sPath |
public function execute(InputInterface $input, OutputInterface $output)
{
$this->input = $input;
$sMigrationsDir = OX_BASE_PATH . 'migration' . DIRECTORY_SEPARATOR;
$sTemplatePath = $this->_getTemplatePath();
$sMigrationName = $this->_parseMigrationNameFromInput();
if (!$sMigrationName) {
$questionHelper = $this->getHelper('question');
$question = new Question('Enter short description for migration: ');
do {
$words = explode(" ", $questionHelper->ask($input, $output, $question));
$sMigrationName = $this->_buildMigrationName($words);
} while (!$sMigrationName);
}
$sMigrationFileName = AbstractQuery::getCurrentTimestamp() . '_' . strtolower($sMigrationName) . '.php';
$sMigrationFilePath = $sMigrationsDir . $sMigrationFileName;
/** @var Smarty $oSmarty */
$oSmarty = Registry::get('oxUtilsView')->getSmarty();
$oSmarty->php_handling = SMARTY_PHP_PASSTHRU;
$oSmarty->assign('sMigrationName', $sMigrationName);
$sContent = $oSmarty->fetch($sTemplatePath);
file_put_contents($sMigrationFilePath, $sContent);
$output->writeLn("Sucessfully generated $sMigrationFileName");
} | {@inheritdoc} |
protected function _buildMigrationName(array $words)
{
$sMigrationName = '';
foreach ($words as $word) {
if (!$word) {
continue;
}
$sMigrationName .= ucfirst($word);
}
return $sMigrationName;
} | Build migration name from tokens
@param array $words
@return string |
protected function getPaymentTransactionStructure()
{
return [
'amount' => $this->transformAmount($this->amount, $this->currency),
'currency' => $this->currency,
'customer_account_id' => $this->customer_account_id,
'return_url' => $this->return_url,
'customer_email' => $this->customer_email,
'customer_phone' => $this->customer_phone,
'billing_address' => $this->getBillingAddressParamsStructure(),
'shipping_address' => $this->getShippingAddressParamsStructure()
];
} | Return additional request attributes
@return array |
protected function verifyRequiredField($field, $value)
{
if (empty($value)) {
throw new \Genesis\Exceptions\ErrorParameter(
sprintf(
'Empty (null) item required parameter: %s',
$field
)
);
}
} | Verify required field
@param $field
@param $value
@throws \Genesis\Exceptions\ErrorParameter |
protected function verifyNonNegativeField($field, $value)
{
if (!empty($value) && $value <= 0) {
throw new \Genesis\Exceptions\ErrorParameter(
sprintf(
'Item parameter %s is set to %s, but expected to be positive number',
$field,
$value
)
);
}
} | Verify non-negative filed
@param $field
@param $value
@throws \Genesis\Exceptions\ErrorParameter |
protected function verifyNegativeField($field, $value)
{
if (!empty($value) && $value > 0) {
throw new \Genesis\Exceptions\ErrorParameter(
sprintf(
'Item parameter %s is set to %s, but expected to be negative number',
$field,
$value
)
);
}
} | Verify negative filed
@param $field
@param $value
@throws \Genesis\Exceptions\ErrorParameter |
protected function verifyUnitPriceField($value)
{
$this->verifyRequiredField('unit_price', $value);
if (in_array($this->item_type, [self::ITEM_TYPE_DISCOUNT, self::ITEM_TYPE_STORE_CREDIT])) {
$this->verifyNegativeField('unit_price', $value);
return;
}
$this->verifyNonNegativeField('unit_price', $value);
} | Verify unit_price filed
@param $value
@throws \Genesis\Exceptions\ErrorParameter |
public function setQuantity($value)
{
$this->verifyRequiredField('quantity', $value);
$this->verifyNonNegativeField('quantity', $value);
$this->quantity = $value;
return $this;
} | Set quantity
@param $value
@return $this
@throws \Genesis\Exceptions\ErrorParameter |
public function setItemType($value)
{
$this->verifyRequiredField('item_type', $value);
// check if it is valid type
$item_types = array(
self::ITEM_TYPE_PHYSICAL,
self::ITEM_TYPE_DISCOUNT,
self::ITEM_TYPE_SHIPPING_FEE,
self::ITEM_TYPE_DIGITAL,
self::ITEM_TYPE_GIFT_CARD,
self::ITEM_TYPE_STORE_CREDIT,
self::ITEM_TYPE_SURCHARGE
);
if (!in_array($value, $item_types)) {
throw new \Genesis\Exceptions\ErrorParameter(
sprintf(
'Required item parameter item_type is set to %s, but expected to be one of (%s)',
$value,
implode(
', ',
CommonUtils::getSortedArrayByValue($item_types)
)
)
);
}
$this->item_type = $value;
return $this;
} | Set item type
@param $value
@return $this
@throws \Genesis\Exceptions\ErrorParameter |
public function setQuantityUnit($value)
{
if (!empty($value) && strlen($value) > 8) {
throw new \Genesis\Exceptions\ErrorParameter(
sprintf(
'Item parameter quantity_unit is set to %s, but expected to be string with max length 8 characters',
$value
)
);
}
$this->quantity_unit = $value;
return $this;
} | Set item quantity unit
@param $value
@return $this
@throws \Genesis\Exceptions\ErrorParameter |
public function getTotalAmount()
{
$total_amount = $this->unit_price * $this->quantity;
if (!empty($this->total_discount_amount)) {
return $total_amount - $this->total_discount_amount;
}
return $total_amount;
} | Calculate order item total amount
@return integer |
public function getTotalTaxAmount()
{
// Convert to minor units for more accurate calculations
$total_amount = CurrencyUtils::amountToExponent($this->getTotalAmount(), $this->currency);
$tax_rate = CurrencyUtils::amountToExponent($this->tax_rate, $this->currency);
$total_tax_amount = ceil(
$total_amount - ( ($total_amount * 10000) / (10000 + $tax_rate) )
);
return CurrencyUtils::exponentToAmount($total_tax_amount, $this->currency);
} | Calculate order item total tax amount.
Round it up to next whole number
@return integer |
public function toArray()
{
return [
'name' => $this->name,
'item_type' => $this->item_type,
'quantity' => $this->quantity,
'unit_price' => CurrencyUtils::amountToExponent($this->unit_price, $this->currency),
'tax_rate' => CurrencyUtils::amountToExponent($this->tax_rate, $this->currency),
'total_discount_amount' => CurrencyUtils::amountToExponent($this->total_discount_amount, $this->currency),
'total_amount' => CurrencyUtils::amountToExponent($this->getTotalAmount(), $this->currency),
'total_tax_amount' => CurrencyUtils::amountToExponent($this->getTotalTaxAmount(), $this->currency),
'reference' => $this->reference,
'image_url' => $this->image_url,
'product_url' => $this->product_url,
'quantity_unit' => $this->quantity_unit,
'product_identifiers' => $this->getProductIdentifiersParamsStructure(),
'merchant_data' => $this->getMerchantDataParamsStructure()
];
} | Convert item to array
@return array |
public static function getAll()
{
$aShopIds = DatabaseProvider::getDb()->getCol('SELECT oxid FROM oxshops');
$aConfigs = array();
foreach ($aShopIds as $mShopId) {
// Note: not using static::get() for avoiding checking of is shop id valid
$aConfigs[] = new ShopConfig($mShopId);
}
return $aConfigs;
} | Returns config arrays for all shops
@return ShopConfig[] |
public static function get($mShopId)
{
$sSQL = 'SELECT 1 FROM oxshops WHERE oxid = %s';
$oDb = DatabaseProvider::getDb();
if (!$oDb->getOne(sprintf($sSQL, $oDb->quote($mShopId)))) { // invalid shop id
// Not using oxConfig::_isValidShopId() because its not static, but YES it should be
return null;
}
return new ShopConfig($mShopId);
} | Get config object of given shop id
@param string|integer $mShopId
@return ShopConfig|null |
public function init()
{
// Duplicated init protection
if ($this->_blInit) {
return;
}
$this->_blInit = true;
$this->_loadVarsFromFile();
$this->_setDefaults();
$this->storedVarTypes = $this->getStoredVarTypes();
try {
$sShopID = $this->getShopId();
$blConfigLoaded = $this->_loadVarsFromDb($sShopID);
// loading shop config
if (empty($sShopID) || !$blConfigLoaded) {
throw oxNew(ConnectionException::class, "Unable to load shop config values from database");
}
// loading theme config options
$this->_loadVarsFromDb(
$sShopID, null, Config::OXMODULE_THEME_PREFIX . $this->getConfigParam('sTheme')
);
$this->_aConfigParamsParentTheme = $this->_aConfigParams;
// checking if custom theme (which has defined parent theme) config options should be loaded over parent theme (#3362)
if ($this->getConfigParam('sCustomTheme')) {
$this->_loadVarsFromDb(
$sShopID, null, Config::OXMODULE_THEME_PREFIX . $this->getConfigParam('sCustomTheme')
);
}
// loading modules config
$this->_loadVarsFromDb($sShopID, null, Config::OXMODULE_MODULE_PREFIX);
$aOnlyMainShopVars = array('blMallUsers', 'aSerials', 'IMD', 'IMA', 'IMS');
$this->_loadVarsFromDb($this->getBaseShopId(), $aOnlyMainShopVars);
} catch (ConnectionException $oEx) {
$oEx->debugOut();
Registry::getUtils()->showMessageAndExit($oEx->getString());
}
} | {@inheritdoc}
@return null|void |
protected function getStoredVarTypes()
{
$db = \oxDb::getDb(\oxDb::FETCH_MODE_ASSOC);
$sQ = "select CONCAT(oxvarname,'+',oxmodule) as mapkey, oxvartype from oxconfig where oxshopid = ?";
$allRows = $db->getAll($sQ, [$this->_iShopId]);
$map = [];
foreach($allRows as $row) {
$map[$row['mapkey']] = $row['oxvartype'];
}
return $map;
} | Getting all the stored variable type info from database
to be able to check if there was a type change
this helps to improve performance when saving a huge amount of config values (e.g. module:fix or config importers) |
public function saveShopConfVar($sVarType, $sVarName, $sVarVal, $sShopId = null, $sModule = '')
{
$sShopId = $sShopId === null ? $this->_iShopId : $sShopId;
if ($sShopId == $this->_iShopId) {
$storedType = $this->getShopConfType($sVarName, $sModule);
if ($sModule == Config::OXMODULE_THEME_PREFIX . $this->getConfigParam('sTheme')){
$storedValue = $this->_aConfigParamsParentTheme[$sVarName];
} else {
$storedValue = $this->getConfigParam($sVarName);
}
if ($sVarType == 'bool') {
//some modules that have all kinds of bool representations in metadata.php may cause
//$sVarVal to something else then a boolean, converting the value like parent::saveShopConfVar
//would do so we can compare it to the strored representation
$sVarVal = (($sVarVal == 'true' || $sVarVal) && $sVarVal && strcasecmp($sVarVal, "false"));
}
if ($sVarType == $storedType && $sVarVal == $storedValue) {
return false;
}
}
parent::saveShopConfVar($sVarType, $sVarName, $sVarVal, $sShopId, $sModule);
return true;
} | overwritten method for performance reasons
@param $sVarType
@param $sVarName
@param $sVarVal
@param null $sShopId
@param string $sModule
@return bool |
public function setLifetime($lifetime)
{
$lifetime = intval($lifetime);
if ($lifetime < 1 || $lifetime > 44640) {
throw new InvalidArgument('Valid value ranges between 1 minute and 31 days given in minutes');
}
$this->lifetime = $lifetime;
return $this;
} | Number of minutes determining how long the WPF will be valid.
Will be set to 30 minutes by default.
Valid value ranges between 1 minute and 31 days given in minutes
@param int $lifetime
@throws InvalidArgument
@return $this |
public function addTransactionType($name, $parameters = [])
{
$this->verifyTransactionType($name, $parameters);
$structure = [
'transaction_type' => [
'@attributes' => [
'name' => $name
],
$parameters
]
];
array_push($this->transaction_types, $structure);
return $this;
} | Add transaction type to the list of available types
@param string $name
@param array $parameters
@return $this |
protected function verifyTransactionType($transactionType, $parameters = [])
{
if (!Types::isValidWPFTransactionType($transactionType)) {
throw new \Genesis\Exceptions\ErrorParameter(
sprintf(
'Transaction type (%s) is not valid. Valid WPF transactions are: %s.',
$transactionType,
implode(', ', Types::getWPFTransactionTypes())
)
);
}
$txnCustomRequiredParams = Types::getCustomRequiredParameters(
$transactionType
);
if (!CommonUtils::isValidArray($txnCustomRequiredParams)) {
return;
}
$txnCustomRequiredParams = static::validateNativeCustomParameters($transactionType, $txnCustomRequiredParams);
if (CommonUtils::isValidArray($txnCustomRequiredParams) && !CommonUtils::isValidArray($parameters)) {
throw new \Genesis\Exceptions\ErrorParameter(
sprintf(
'Custom transaction parameters (%s) are required and none are set.',
implode(', ', array_keys($txnCustomRequiredParams))
)
);
}
foreach ($txnCustomRequiredParams as $customRequiredParam => $customRequiredParamValues) {
$this->validateRequiredParameter(
$transactionType,
$customRequiredParam,
$customRequiredParamValues,
$parameters
);
}
} | Verify that transaction type parameters are populated correctly
@param string $transactionType
@param array $parameters
@throws \Genesis\Exceptions\ErrorParameter |
protected function validateNativeCustomParameters($transactionType, $txnCustomRequiredParams)
{
foreach ($txnCustomRequiredParams as $customRequiredParam => $customRequiredParamValues) {
if (property_exists($this, $customRequiredParam)) {
$this->validateRequiredParameter(
$transactionType,
$customRequiredParam,
$customRequiredParamValues,
[ $customRequiredParam => $this->{$customRequiredParam} ]
);
unset($txnCustomRequiredParams[$customRequiredParam]);
}
}
return $txnCustomRequiredParams;
} | @param string $transactionType
@param array $txnCustomRequiredParams
@return array |
private function checkIsParamSet($transactionType, $parameters, $paramValues)
{
if (!in_array($parameters, $paramValues)) {
throw new \Genesis\Exceptions\ErrorParameter(
sprintf(
'Invalid value (%s) for required parameter: %s (Transaction type: %s)',
$parameters,
$paramValues,
$transactionType
)
);
}
} | @param string $transactionType
@param array $parameters
@param mixed $paramValues
@throws \Genesis\Exceptions\ErrorParameter |
protected function checkEmptyRequiredParamsFor(
$transactionType,
$customRequiredParam,
$txnParameters = []
) {
if (CommonUtils::isArrayKeyExists($customRequiredParam, $txnParameters) &&
!empty($txnParameters[$customRequiredParam])
) {
return;
}
foreach ($txnParameters as $parameter) {
if (CommonUtils::isArrayKeyExists($customRequiredParam, $parameter) &&
!empty($parameter[$customRequiredParam])
) {
return;
}
}
throw new \Genesis\Exceptions\ErrorParameter(
sprintf(
'Empty (null) required parameter: %s for transaction type %s',
$customRequiredParam,
$transactionType
)
);
} | Performs a check there is an empty required param for the passed transaction type
@param string $transactionType
@param string $customRequiredParam
@param array $txnParameters
@throws \Genesis\Exceptions\ErrorParameter |
public function setLanguage($language = \Genesis\API\Constants\i18n::EN)
{
// Strip the input down to two letters
$language = substr(strtolower($language), 0, 2);
if (!\Genesis\API\Constants\i18n::isValidLanguageCode($language)) {
throw new \Genesis\Exceptions\InvalidArgument(
'The provided argument is not a valid ISO-639-1 language code!'
);
}
$this->setApiConfig(
'url',
$this->buildRequestURL(
'wpf',
sprintf('%s/wpf', $language),
false
)
);
return $this;
} | Add ISO 639-1 language code to the URL
@param string $language iso code of the language
@return $this
@throws \Genesis\Exceptions\InvalidArgument |
protected function setRequiredFields()
{
$requiredFields = [
'transaction_id',
'amount',
'currency',
'description',
'notification_url',
'return_success_url',
'return_failure_url',
'return_cancel_url',
'transaction_types'
];
$this->requiredFields = \Genesis\Utils\Common::createArrayObject($requiredFields);
$requiredFieldsConditional = [
'remember_card' => [
true => [
'customer_email'
]
],
'consumer_id' => [
'customer_email'
]
];
$this->requiredFieldsConditional = CommonUtils::createArrayObject($requiredFieldsConditional);
} | Set the required fields
@return void |
protected function populateStructure()
{
$treeStructure = [
'wpf_payment' => [
'transaction_id' => $this->transaction_id,
'amount' => $this->transform(
'amount',
[
$this->amount,
$this->currency
]
),
'currency' => $this->currency,
'usage' => $this->usage,
'description' => $this->description,
'consumer_id' => $this->consumer_id,
'customer_email' => $this->customer_email,
'customer_phone' => $this->customer_phone,
'notification_url' => $this->notification_url,
'return_success_url' => $this->return_success_url,
'return_failure_url' => $this->return_failure_url,
'return_cancel_url' => $this->return_cancel_url,
'billing_address' => $this->getBillingAddressParamsStructure(),
'shipping_address' => $this->getShippingAddressParamsStructure(),
'remember_card' => var_export($this->remember_card, true),
'transaction_types' => $this->transaction_types,
'lifetime' => $this->lifetime,
'risk_params' => $this->getRiskParamsStructure(),
'dynamic_descriptor_params' => $this->getDynamicDescriptorParamsStructure()
]
];
$this->treeStructure = \Genesis\Utils\Common::createArrayObject($treeStructure);
} | Create the request's Tree structure
@return void |
public static function isValidTransactionType($type)
{
$transactionTypes = \Genesis\Utils\Common::getClassConstants(__CLASS__);
return in_array(strtolower($type), $transactionTypes);
} | Check whether this is a valid (known) transaction type
@param string $type
@return bool |
public static function getSplitPaymentsTrxTypes()
{
return [
self::SALE,
self::SALE_3D,
self::TCS,
self::FASHIONCHEQUE,
self::INTERSOLVE
];
} | Get valid split payment transaction types
@return array |
public static function isPayByVoucher($type)
{
$transactionTypesList = [
self::PAYBYVOUCHER_YEEPAY,
self::PAYBYVOUCHER_SALE
];
return in_array(strtolower($type), $transactionTypesList);
} | Check whether this is a valid (known) transaction type
@param string $type
@return bool |
public static function canCapture($type)
{
$transactionTypesList = [
self::AUTHORIZE,
self::AUTHORIZE_3D,
self::KLARNA_AUTHORIZE
];
return in_array(strtolower($type), $transactionTypesList);
} | @param string $type
@return bool |
public static function canRefund($type)
{
$transactionTypesList = [
self::CAPTURE,
self::CASHU,
self::INIT_RECURRING_SALE,
self::INIT_RECURRING_SALE_3D,
self::INPAY,
self::P24,
self::PAYPAL_EXPRESS,
self::PPRO,
self::SALE,
self::SALE_3D,
self::SOFORT,
self::TRUSTLY_SALE,
self::FASHIONCHEQUE,
self::KLARNA_CAPTURE,
self::ZIMPLER,
self::ENTERCASH,
self::INSTANT_TRANSFER,
self::PAYU,
self::BITPAY_SALE,
self::NEOSURF,
self::SAFETYPAY
];
return in_array(strtolower($type), $transactionTypesList);
} | @param string $type
@return bool |
public static function canVoid($type)
{
$transactionTypesList = [
self::AUTHORIZE,
self::AUTHORIZE_3D,
self::TRUSTLY_SALE,
self::TCS,
self::FASHIONCHEQUE,
self::INTERSOLVE
];
return in_array(strtolower($type), $transactionTypesList);
} | @param string $type
@return bool |
public static function isCapture($type)
{
$transactionTypesList = [
self::CAPTURE,
self::KLARNA_CAPTURE
];
return in_array(strtolower($type), $transactionTypesList);
} | @param $type
@return bool |
public static function isRefund($type)
{
$transactionTypesList = [
self::REFUND,
self::SDD_REFUND,
self::KLARNA_REFUND,
self::BITPAY_REFUND
];
return in_array(strtolower($type), $transactionTypesList);
} | @param $type
@return bool |
public static function getCustomRequiredParameters($type)
{
$method = 'for' . Common::snakeCaseToCamelCase($type);
if (!method_exists(CustomRequiredParameters::class, $method)) {
return false;
}
return CustomRequiredParameters::$method();
} | Get custom required parameters with values per transaction
@param string $type
@return array|bool |
protected function populateStructure()
{
$treeStructure = [
'reconcile' => [
'arn' => $this->arn,
'transaction_id' => $this->transaction_id,
'unique_id' => $this->unique_id
]
];
$this->treeStructure = \Genesis\Utils\Common::createArrayObject($treeStructure);
} | Create the request's Tree structure
@return void |
protected function getRequestClass($request)
{
$parts = explode('\\', $request);
$lastIndex = count($parts) - 1;
switch ($parts[$lastIndex]) {
case 'Void':
$parts[$lastIndex] = 'Cancel';
break;
case 'AVS':
case 'INPay':
case 'ABNiDEAL':
$this->throwDeprecatedTransactionType();
break;
case 'Payin':
case 'Payout':
if ($this->getParentClass($parts, $lastIndex) === 'Citadel') {
$this->throwDeprecatedTransactionType();
}
break;
case 'oBeP':
if ($this->getParentClass($parts, $lastIndex) === 'PayByVouchers') {
$this->throwDeprecatedTransactionType();
}
break;
}
return sprintf(
'\Genesis\API\Request\%s',
implode('\\', $parts)
);
} | @param string $request
@return string
@throws \Genesis\Exceptions\DeprecatedMethod |
public function execute()
{
// Build the previously set data
$this->networkCtx->setApiCtxData(
$this->requestCtx
);
// Send the request
$this->networkCtx->sendRequest();
// Set the request context
$this->responseCtx->setRequestCtx(
$this->requestCtx
);
// Parse the response
$this->responseCtx->parseResponse(
$this->networkCtx->getResponseBody()
);
} | Send the request
@throws Exceptions\ErrorAPI
@throws Exceptions\InvalidArgument
@throws Exceptions\InvalidResponse |
protected function setRequiredFields()
{
parent::setRequiredFields();
$requiredFieldValues = [
'billing_country' => [
'AD', 'AT', 'BE', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'EL', 'ES', 'NL',
'IE', 'IS', 'LT', 'LV', 'LU', 'MT', 'DE', 'NO', 'PL', 'PT', 'SM', 'SK',
'SI', 'CH', 'SE', 'HU', 'GB', 'IT', 'US', 'CA', 'JP', 'UA', 'BY', 'RU'
],
'currency' => \Genesis\Utils\Currency::getList()
];
$this->requiredFieldValues = \Genesis\Utils\Common::createArrayObject($requiredFieldValues);
} | Set the required fields
@return void |
protected function getPaymentTransactionStructure()
{
return [
'usage' => $this->usage,
'remote_ip' => $this->remote_ip,
'amount' => $this->transformAmount($this->amount, $this->currency),
'currency' => $this->currency,
'reference_id' => $this->reference_id
];
} | Return additional request attributes
@return array |
protected function getPaymentTransactionStructure()
{
return [
'usage' => $this->usage,
'remote_ip' => $this->remote_ip,
'return_url' => $this->return_url,
'amount' => $this->transformAmount($this->amount, $this->currency),
'currency' => $this->currency,
'customer_email' => $this->customer_email,
'billing_address' => $this->getBillingAddressParamsStructure(),
'shipping_address' => $this->getShippingAddressParamsStructure()
];
} | Return additional request attributes
@return array |
protected function conditions(AbstractSearch $search, array $matches, $negate)
{
$actor = $search->getActor();
// might be better as `id IN (subquery)`?
$method = $negate ? 'whereNotExists' : 'whereExists';
$search->getQuery()->$method(function ($query) use ($actor, $matches) {
$query->selectRaw('1')
->from('discussion_user')
->whereColumn('discussions.id', 'discussion_id')
->where('user_id', $actor->id)
->where('subscription', $matches[1] === 'follow' ? 'follow' : 'ignore');
});
} | {@inheritdoc} |
public static function amountToExponent($amount, $iso)
{
$iso = strtoupper($iso);
if (array_key_exists($iso, self::$iso4217)) {
$exp = intval(self::$iso4217[$iso]['exponent']);
if ($exp > 0) {
return bcmul($amount, pow(10, $exp), 0);
}
}
return strval($amount);
} | Convert amount to ISO-4217 minor currency unit
@param $amount - amount to convert
@param $iso - iso code of the currency
@return mixed - using string as we don't want to cast it without knowing how much precision
is required |
public static function exponentToAmount($amount, $iso)
{
$iso = strtoupper($iso);
if (array_key_exists($iso, self::$iso4217)) {
$exp = intval(self::$iso4217[$iso]['exponent']);
if ($exp > 0) {
return bcdiv($amount, pow(10, $exp), $exp);
}
}
return strval($amount);
} | Convert ISO-4217 minor currency unit to amount
@param $amount - amount to convert
@param $iso - iso code of the currency
@return string - using string as we don't want to cast it without knowing how much precision
is required |
public function getDocument()
{
$this->processRequestParameters();
if ($this->treeStructure instanceof \ArrayObject) {
$this->builderContext = new \Genesis\Builder();
$this->builderContext->parseStructure($this->treeStructure->getArrayCopy());
return $this->builderContext->getDocument();
}
return null;
} | Generate the XML output
@return string - XML Document with request data |
protected function sanitizeStructure()
{
if ($this->treeStructure instanceof \ArrayObject) {
$this->treeStructure->exchangeArray(
CommonUtils::emptyValueRecursiveRemoval(
$this->treeStructure->getArrayCopy()
)
);
}
} | Remove empty keys/values from the structure
@return void |
protected function checkRequirements()
{
$this->verifyFieldRequirements();
$this->verifyFieldValuesRequirements();
$this->verifyGroupRequirements();
$this->verifyConditionalRequirements();
$this->verifyConditionalFields();
} | Perform field validation
@throws \Genesis\Exceptions\ErrorParameter
@return void |
protected function verifyFieldRequirements()
{
if (isset($this->requiredFields)) {
$this->requiredFields->setIteratorClass('RecursiveArrayIterator');
$iterator = new \RecursiveIteratorIterator($this->requiredFields->getIterator());
foreach ($iterator as $fieldName) {
if (empty($this->$fieldName)) {
throw new \Genesis\Exceptions\ErrorParameter(
sprintf('Empty (null) required parameter: %s', $fieldName)
);
}
}
}
} | Verify that all required fields are populated
@throws \Genesis\Exceptions\ErrorParameter |
protected function verifyFieldValuesRequirements()
{
if (!isset($this->requiredFieldValues)) {
return;
}
$iterator = $this->requiredFieldValues->getArrayCopy();
foreach ($iterator as $fieldName => $validator) {
if ($validator instanceof RequestValidator) {
$validator->run($this, $fieldName);
continue;
}
if (CommonUtils::isValidArray($validator)) {
if (!in_array($this->$fieldName, $validator)) {
throw new \Genesis\Exceptions\ErrorParameter(
sprintf(
'Required parameter %s is set to %s, but expected to be one of (%s)',
$fieldName,
$this->$fieldName,
implode(
', ',
CommonUtils::getSortedArrayByValue($validator)
)
)
);
}
continue;
}
if ($this->$fieldName !== $validator) {
throw new \Genesis\Exceptions\ErrorParameter(
sprintf(
'Required parameter %s is set to %s, but expected to be %s',
$fieldName,
$this->$fieldName,
$validator
)
);
}
}
} | Verify that all required fields are populated with expected values
@throws \Genesis\Exceptions\ErrorParameter |
protected function verifyGroupRequirements()
{
if (isset($this->requiredFieldsGroups)) {
$fields = $this->requiredFieldsGroups->getArrayCopy();
$emptyFlag = false;
$groupsFormatted = [];
foreach ($fields as $group => $groupFields) {
$groupsFormatted[] = sprintf(
'%s (%s)',
ucfirst($group),
implode(', ', $groupFields)
);
foreach ($groupFields as $field) {
if (!empty($this->$field)) {
$emptyFlag = true;
}
}
}
if (!$emptyFlag) {
throw new \Genesis\Exceptions\ErrorParameter(
sprintf(
'One of the following group/s of field/s must be filled in: %s%s',
PHP_EOL,
implode(
PHP_EOL,
$groupsFormatted
)
),
true
);
}
}
} | Verify that the group fields in the request are populated
@throws \Genesis\Exceptions\ErrorParameter |
protected function verifyConditionalRequirements()
{
if (!isset($this->requiredFieldsConditional)) {
return;
}
$fields = $this->requiredFieldsConditional->getArrayCopy();
foreach ($fields as $fieldName => $fieldDependencies) {
if (!isset($this->$fieldName)) {
continue;
}
foreach ($fieldDependencies as $fieldValue => $fieldDependency) {
if (is_array($fieldDependency)) {
if ($this->$fieldName != $fieldValue) {
continue;
}
foreach ($fieldDependency as $field) {
if (empty($this->$field)) {
$fieldValue =
is_bool($this->$fieldName)
? var_export($this->$fieldName, true)
: $this->$fieldName;
throw new \Genesis\Exceptions\ErrorParameter(
sprintf(
'%s with value %s is depending on: %s, which is empty (null)!',
$fieldName,
$fieldValue,
$field
)
);
}
}
} elseif (empty($this->$fieldDependency)) {
throw new \Genesis\Exceptions\ErrorParameter(
sprintf(
'%s is depending on: %s, which is empty (null)!',
$fieldName,
$fieldDependency
)
);
}
}
}
} | Verify that all fields (who depend on previously populated fields) are populated
@throws \Genesis\Exceptions\ErrorParameter
@SuppressWarnings(PHPMD.CyclomaticComplexity) |
protected function verifyConditionalFields()
{
if (isset($this->requiredFieldsOR)) {
$fields = $this->requiredFieldsOR->getArrayCopy();
$status = false;
foreach ($fields as $fieldName) {
if (isset($this->$fieldName) && !empty($this->$fieldName)) {
$status = true;
}
}
if (!$status) {
throw new \Genesis\Exceptions\ErrorParameter(implode($fields));
}
}
} | Verify conditional requirement, where either one of the fields are populated
@throws \Genesis\Exceptions\ErrorParameter |
protected function transform($method, $args, $prefix = 'transform')
{
$method = $prefix . CommonUtils::snakeCaseToCamelCase($method);
if (method_exists($this, $method)) {
$result = call_user_func_array([$this, $method], $args);
if ($result) {
return $result;
}
}
return reset($args);
} | Perform a field transformation
and return the result
@param string $method
@param array $args
@param string $prefix
@return mixed |
protected function transformAmount($amount = '', $currency = '')
{
if (!empty($amount) && !empty($currency)) {
return \Genesis\Utils\Currency::amountToExponent($amount, $currency);
}
return false;
} | Apply transformation: Convert to Minor currency unit
@param string $amount
@param string $currency
@return string |
protected function buildRequestURL($sub = 'gateway', $path = '', $token = '')
{
$protocol = ($this->getApiConfig('protocol')) ? $this->getApiConfig('protocol') : 'https';
$sub = \Genesis\Config::getSubDomain($sub);
$domain = \Genesis\Config::getEndpoint();
$port = ($this->getApiConfig('port')) ? $this->getApiConfig('port') : 443;
$path = ($token) ? sprintf('%s/%s/', $path, $token) : $path;
return sprintf(
'%s://%s%s:%s/%s',
$protocol,
$sub,
$domain,
$port,
$path
);
} | Build the complete URL for the request
@param $sub String - gateway/wpf etc.
@param $path String - path of the current request
@param $token String - should we append the token to the end of the url
@return string - complete URL |
protected function initApiGatewayConfiguration($requestPath = 'process', $includeToken = true)
{
$this->setApiConfig(
'url',
$this->buildRequestURL(
'gateway',
$requestPath,
($includeToken ? \Genesis\Config::getToken() : false)
)
);
} | Initializes Api EndPoint Url with request path & terminal token
@param string $requestPath
@param bool $includeToken
@return void |
public function setCryptoAddress($address)
{
if (!$this->checkAddress($address) || !preg_match(static::CRYPTO_ADDRESS_VALIDATION_REGEX, $address)) {
throw new ErrorParameter('Invalid crypto address provided');
}
$this->crypto_address = $address;
return $this;
} | Valid crypto address where the funds will be received
@param $address
@return $this
@throws ErrorParameter |
public function checkAddress($address)
{
$addr = $this->decodeBase58($address);
if (strlen($addr) != 50) {
return false;
}
$check = substr($addr, 0, strlen($addr) - 8);
$check = pack('H*', $check);
$check = strtoupper(hash('sha256', hash('sha256', $check, true)));
$check = substr($check, 0, 8);
return $check == substr($addr, strlen($addr) - 8);
} | Taken from https://github.com/tenfef/btc_address_validator
@param $address
@return bool |
private function encodeHex($dec)
{
$hexchars = '0123456789ABCDEF';
$return = '';
while (bccomp($dec, 0) == 1) {
$rem = (integer)bcmod($dec, '16');
$dec = (string)bcdiv($dec, '16', 0);
$return = $return . $hexchars[$rem];
}
return strrev($return);
} | @param $dec
@return string |
private function decodeBase58($base58)
{
$origbase58 = $base58;
$base58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
$return = '0';
for ($i = 0; $i < strlen($base58); $i++) {
$current = (string)strpos($base58chars, $base58[$i]);
$return = (string)bcmul($return, "58", 0);
$return = (string)bcadd($return, $current, 0);
}
$return = $this->encodeHex($return);
//leading zeros
for ($i = 0; $i < strlen($origbase58) && $origbase58[$i] == '1'; $i++) {
$return = '00' . $return;
}
if (strlen($return) % 2 != 0) {
$return = '0' . $return;
}
return $return;
} | Convert a Base58-encoded integer into the equivalent hex string representation
@param string $base58
@return string
@access private |
protected function setRequiredFields()
{
$requiredFields = [
'transaction_id',
'return_success_url',
'return_failure_url',
'amount',
'currency',
'crypto_address',
'crypto_wallet_provider'
];
$this->requiredFields = \Genesis\Utils\Common::createArrayObject($requiredFields);
$requiredFieldValues = [
'crypto_wallet_provider' => [
self::WALLET_PROVIDER_BITGO,
self::WALLET_PROVIDER_UPHOLD,
self::WALLET_PROVIDER_CIRCLE,
self::WALLET_PROVIDER_COINBASE,
self::WALLET_PROVIDER_GDAX,
self::WALLET_PROVIDER_GEMINI,
self::WALLET_PROVIDER_ITBIT,
self::WALLET_PROVIDER_KRAKEN
]
];
$this->requiredFieldValues = \Genesis\Utils\Common::createArrayObject($requiredFieldValues);
} | Set the required fields
@return void |
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,
'customer_email' => $this->customer_email,
'crypto_address' => $this->crypto_address,
'crypto_wallet_provider' => $this->crypto_wallet_provider,
'billing_address' => $this->getBillingAddressParamsStructure(),
'shipping_address' => $this->getShippingAddressParamsStructure()
];
} | Return additional request attributes
@return array |
protected function setRequiredFields()
{
$requiredFields = [
'transaction_id',
'amount',
'currency',
'customer_email',
'account_name',
'bank_name',
'billing_first_name',
'billing_last_name',
'billing_address1',
'billing_city',
'billing_country',
];
$this->requiredFields = \Genesis\Utils\Common::createArrayObject($requiredFields);
$requiredFieldValues = [
'billing_country' => [
'AD', 'AU', 'AT', 'BH', 'BS', 'BE', 'BG', 'CA', 'CY', 'CZ', 'DK', 'EG', 'EE',
'FI', 'FR', 'DE', 'GR', 'HK', 'HU', 'ID', 'IE', 'IL', 'IT', 'JP', 'KE', 'LV',
'LI', 'LT', 'LU', 'MY', 'MT', 'MA', 'NL', 'NZ', 'NO', 'PK', 'PH', 'PL', 'PT',
'RO', 'SG', 'SK', 'SI', 'ES', 'SE', 'CH', 'GB', 'US', 'VN'
],
'currency' => \Genesis\Utils\Currency::getList()
];
$this->requiredFieldValues = \Genesis\Utils\Common::createArrayObject($requiredFieldValues);
$this->setRequiredFieldValuesConditional();
} | 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,
'account_name' => $this->account_name,
'bank_name' => $this->bank_name,
'iban' => $this->iban,
'bic' => $this->bic,
'account_number' => $this->account_number,
'bank_code' => $this->bank_code,
'branch_code' => $this->branch_code,
'account_number_suffix' => $this->account_number_suffix,
'sort_code' => $this->sort_code,
'aba_routing_number' => $this->aba_routing_number,
'billing_address' => $this->getBillingAddressParamsStructure(),
];
} | Return additional request attributes
@return array |
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_account_id' => $this->customer_account_id,
'customer_email' => $this->customer_email,
'customer_phone' => $this->customer_phone,
'billing_address' => $this->getBillingAddressParamsStructure(),
'shipping_address' => $this->getShippingAddressParamsStructure()
];
} | Return additional request attributes
@return array |
protected function setRequiredFields()
{
$requiredFields = [
'transaction_id',
'payment_type',
'remote_ip',
'amount',
'currency',
'return_success_url',
'return_failure_url',
'customer_email',
'billing_country'
];
$this->requiredFields = CommonUtils::createArrayObject($requiredFields);
$requiredFieldValues = [
'payment_type' => PaymentMethods::getMethods(),
'billing_country' => \Genesis\Utils\Country::getList(),
'currency' => \Genesis\Utils\Currency::getList()
];
$this->requiredFieldValues = CommonUtils::createArrayObject($requiredFieldValues);
$requiredFieldsConditional = [
'payment_type' => [
PaymentMethods::GIRO_PAY => [
'bic',
'iban'
],
PaymentMethods::PRZELEWY24 => [
'customer_email'
],
PaymentMethods::QIWI => [
'account_phone'
]
]
];
$this->requiredFieldsConditional = CommonUtils::createArrayObject($requiredFieldsConditional);
$this->setRequiredFieldValuesConditional();
} | Set the required fields
@return void |
protected function setRequiredFieldValuesConditional()
{
$requiredFieldValuesConditional = [
'payment_type' => [
PaymentMethods::EPS => [
[
'billing_country' => 'AT',
'currency' => 'EUR'
]
],
PaymentMethods::SAFETY_PAY => [
[
'billing_country' => [
'AT', 'BE', 'BR', 'CL', 'CO', 'CR', 'DE', 'EC', 'ES', 'MX', 'NL', 'PE', 'PR'
],
'currency' => ['EUR', 'USD']
]
],
PaymentMethods::TRUST_PAY => [
[
'billing_country' => 'CZ',
'currency' => 'CZK'
],
[
'billing_country' => ['CZ', 'SK'],
'currency' => 'EUR'
]
],
PaymentMethods::PRZELEWY24 => [
[
'billing_country' => 'PL',
'currency' => 'PLN'
]
],
PaymentMethods::IDEAL => [
[
'billing_country' => 'NL',
'currency' => 'EUR'
]
],
PaymentMethods::QIWI => [
[
'billing_country' => 'RU',
'currency' => ['EUR', 'RUB']
]
],
PaymentMethods::GIRO_PAY => [
[
'billing_country' => 'DE',
'currency' => 'EUR'
]
],
PaymentMethods::BCMC => [
[
'billing_country' => 'BE',
'currency' => 'EUR'
]
],
PaymentMethods::MYBANK => [
[
'billing_country' => ['BE', 'FR', 'IT', 'LU'],
'currency' => 'EUR'
]
]
]
];
$this->requiredFieldValuesConditional = CommonUtils::createArrayObject($requiredFieldValuesConditional);
} | Set the required fields - conditionally depending on other fields
@return void
@SuppressWarnings(PHPMD.ExcessiveMethodLength) |
protected function getPaymentTransactionStructure()
{
return [
'payment_type' => $this->payment_type,
'amount' => $this->transformAmount($this->amount, $this->currency),
'currency' => $this->currency,
'return_success_url' => $this->return_success_url,
'return_failure_url' => $this->return_failure_url,
'customer_email' => $this->customer_email,
'customer_phone' => $this->customer_phone,
'account_number' => $this->account_number,
'bank_code' => $this->bank_code,
'bic' => $this->bic,
'iban' => $this->iban,
'account_phone' => $this->account_phone,
'billing_address' => $this->getBillingAddressParamsStructure(),
'shipping_address' => $this->getShippingAddressParamsStructure()
];
} | Return additional request attributes
@return array |
public function remove($value)
{
$hash = self::hash($value);
if(array_key_exists($hash, $this->objects)) {
unset($this->objects[$hash]);
return true;
}
return false;
} | If the value is in the set, it will be removed and true is returned. otherwise false is returned.
@param $value
@return bool |
public function contains($value)
{
$hash = self::hash($value);
return array_key_exists($hash, $this->objects);
} | Returns true if the value exist in the set. Otherwise false.
@return bool |
private function find($value, $add = false)
{
$hash = self::hash($value);
if(array_key_exists($hash, $this->objects)) {
return true;
}
else if($add) {
$this->objects[$hash] = $value;
}
return false;
} | Finds the given value and returns true if it was found. Otherwise return false. |
public function execute(InputInterface $input, OutputInterface $output)
{
$moduleId = $input->getArgument('moduleid');
$shopId = $input->hasOption('shop') ? $input->getOption('shop') : null;
$this->activateModule($moduleId, $shopId, $output);
} | {@inheritdoc} |
public function activateModule($moduleId, $shopId, $output)
{
/** @var ModuleInstaller $moduleInstaller */
$moduleInstaller = Registry::get(ModuleInstaller::class);
if ($shopId) {
$oConfig = ShopConfig::get($shopId);
$moduleInstaller->setConfig($oConfig);
}
$moduleList = oxNew(ModuleList::class);
$moduleList->getModulesFromDir(Registry::getConfig()->getModulesDir());
$modules = $moduleList->getList();
/** @var Module $module */
$module = $modules[$moduleId];
if ($module == null) {
$output->writeLn("$moduleId not found. choose from:");
$output->writeLn(join("\n", array_keys($modules)));
exit(1);
}
if ($module->isActive()) {
$output->writeLn("$moduleId already active");
} else {
$moduleInstaller->activate($module);
}
} | @param string $moduleId
@param string $shopId
@param OutputInterface $output
@throws \OxidEsales\Eshop\Core\Exception\StandardException |
public function execute(InputInterface $input, OutputInterface $output)
{
$this->init();
$this->input = $input;
$this->output = $output;
$oScaffold = $this->_buildScaffold();
$this->_generateModule($oScaffold);
$output->writeLn('Module generated successfully');
} | {@inheritdoc} |
protected function _generateModule($oScaffold)
{
$oSmarty = $this->_getSmarty();
$oSmarty->assign('oScaffold', $oScaffold);
if ($oScaffold->sVendor) {
$this->_generateVendorDir($oScaffold->sVendor);
}
$sModuleDir = $this->_getModuleDir($oScaffold->sVendor, $oScaffold->sModuleName);
$this->_copyAndParseDir(
$this->_sTemplatesDir, $sModuleDir, array(
'_prefix_' => strtolower($oScaffold->sVendor . $oScaffold->sModuleName)
)
);
} | Generate module from scaffold object
@param object $oScaffold |
protected function _copyAndParseDir($sFrom, $sTo, array $aNameMap = array())
{
$oFileInfos = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($sFrom, \RecursiveDirectoryIterator::SKIP_DOTS)
);
if (!file_exists($sTo)) {
mkdir($sTo);
}
foreach ($oFileInfos as $oFileInfo) {
$sFilePath = (string)$oFileInfo;
$aReplace = array(
'search' => array_merge(array($sFrom), array_keys($aNameMap)),
'replace' => array_merge(array($sTo), array_values($aNameMap))
);
$sNewPath = str_replace($aReplace['search'], $aReplace['replace'], $sFilePath);
$this->_copyAndParseFile($sFilePath, $sNewPath);
}
} | Copies files from directory, parses all files and puts
parsed content to another directory
@param string $sFrom Directory from
@param string $sTo Directory to
@param array $aNameMap What should be changed in file name? |
protected function _copyAndParseFile($sFrom, $sTo)
{
$this->_createMissingFolders($sTo);
$sTo = preg_replace('/\.tpl$/', '', $sTo);
if (preg_match('/\.tpl$/', $sFrom)) {
$oSmarty = $this->_getSmarty();
$sContent = $oSmarty->fetch($sFrom);
} else {
$sContent = file_get_contents($sFrom);
}
file_put_contents($sTo, $sContent);
} | Copies file from one directory to another, parses file if original
file extension is .tpl
@param $sFrom
@param $sTo |
protected function _createMissingFolders($sFilePath)
{
$sPath = dirname($sFilePath);
if (!file_exists($sPath)) {
mkdir($sPath, 0777, true);
}
} | Create missing folders of file path
@param string $sFilePath |
protected function _generateVendorDir($sVendor)
{
$sVendorDir = $this->_sModuleDir . $sVendor . DIRECTORY_SEPARATOR;
if (!file_exists($sVendorDir)) {
mkdir($sVendorDir);
// Generate vendor metadata file
file_put_contents($sVendorDir . 'vendormetadata.php', '<?php');
}
} | Generate vendor directory
@param string $sVendor |
protected function _buildScaffold()
{
$oScaffold = new \stdClass();
$oScaffold->sVendor = strtolower($this->_getUserInput('Vendor Prefix', true));
$blFirstRequest = true;
do {
if (!$blFirstRequest) {
$this->output->writeLn('Module path or id is taken with given title');
} else {
$blFirstRequest = false;
}
$oScaffold->sModuleTitle = $this->_getUserInput('Module Title');
$oScaffold->sModuleName = str_replace(' ', '', ucwords($oScaffold->sModuleTitle));
$oScaffold->sModuleId = $oScaffold->sVendor . strtolower($oScaffold->sModuleName);
} while (!$this->_modulePathAvailable($oScaffold->sVendor, $oScaffold->sModuleName)
|| !$this->_moduleIdAvailable($oScaffold->sModuleId));
$oScaffold->sModuleDir = $this->_getModuleDir($oScaffold->sVendor, $oScaffold->sModuleName);
$oScaffold->sAuthor = $this->_getUserInput('Author', true);
$oScaffold->sUrl = $this->_getUserInput('Url', true);
$oScaffold->sEmail = $this->_getUserInput('Email', true);
return $oScaffold;
} | Build scaffold object from user inputs
@return \stdClass |
protected function _getModuleDir($sVendor, $sModuleName)
{
$sModuleDir = $this->_sModuleDir;
if ($sVendor) {
$sModuleDir .= strtolower($sVendor) . DIRECTORY_SEPARATOR;
}
return $sModuleDir . strtolower($sModuleName) . DIRECTORY_SEPARATOR;
} | Get module dir
@param string $sVendor
@param string $sModuleName
@return string |
protected function _getUserInput($sText, $bAllowEmpty = false)
{
$questionHelper = $this->getHelper('question');
do {
$sTitle = "$sText: " . ($bAllowEmpty ? '[optional] ' : '[required] ');
$question = new Question($sTitle);
$sInput = $questionHelper->ask($this->input, $this->output, $question);
} while (!$bAllowEmpty && !$sInput);
return $sInput;
} | Get user input
@param string $sText
@param bool $bAllowEmpty
@return string |
public function setIban($value)
{
if ($this->billing_country === 'DE') {
$this->validateIban(self::PATTERN_DE_IBAN, $value);
}
return parent::setIban($value);
} | @param $value
@return InstantTransfer
@throws ErrorParameter |
public function execute(InputInterface $input, OutputInterface $output)
{
try {
$timestamp = $this->_parseTimestamp($input->getArgument('timestamp'));
} catch (ConsoleException $oEx) {
$output->writeLn($oEx->getMessage());
exit(1);
}
$output->writeLn('Running migration scripts');
$debugOutput = $input->getOption('verbose')
? $output
: new NullOutput();
/** @var MigrationHandler $oMigrationHandler */
$oMigrationHandler = Registry::get(MigrationHandler::class);
$oMigrationHandler->run($timestamp, $debugOutput);
$output->writeLn('Migration finished successfully');
} | {@inheritdoc} |
protected function _parseTimestamp($timestamp)
{
if (is_null($timestamp))
return AbstractQuery::getCurrentTimestamp();
if (!AbstractQuery::isValidTimestamp($timestamp)) {
if ($sTime = strtotime($timestamp)) {
$timestamp = date('YmdHis', $sTime);
} else {
throw oxNew(
ConsoleException::class,
'Invalid timestamp format, use YYYYMMDDhhmmss format'
);
}
}
return $timestamp;
} | Parse timestamp from user input
@param string|null $timestamp
@return string |