code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
protected function randomPastDateTime($sLow = null) { $oNow = Factory::factory('DateTime'); return $this->randomDateTime($sLow, $oNow->format('Y-m-d H:i:s')); }
Return a random datetime from the past, optionally restricted to a lower bound @param string $sLow The lowest possible datetime to return @return string
protected function randomDate($sLow = null, $sHigh = null, $sFormat = 'Y-m-d') { $iLow = $sLow ? strtotime($sLow) : strtotime('last year'); $iHigh = $sHigh ? strtotime($sHigh) : strtotime('next year'); return date($sFormat, rand($iLow, $iHigh)); }
Return a random date, optionally restricted between bounds @param string $sLow The lowest possible date to return @param string $sHigh The highest possible date to return @param string $sFormat The format to return the datetime value in @return string
protected function randomFutureDate($sHigh = null) { $oNow = Factory::factory('DateTime'); return $this->randomDateTime($oNow->format('Y-m-d'), $sHigh); }
Return a random date from the future, optionally restricted to a upper bound @param string $sHigh The highest possible date to return @return string
protected function configure(): void { $this ->setName('make:model') ->setDescription('Creates a new App model') ->addArgument( 'modelName', InputArgument::OPTIONAL, 'Define the name of the model to create' ) ->addOption( 'skip-db', null, InputOption::VALUE_NONE, 'Skip database table creation' ) ->addOption( 'skip-seeder', null, InputOption::VALUE_NONE, 'Skip seeder creation' ) ->addOption( 'auto-detect', null, InputOption::VALUE_NONE, 'Automatically build models from the database' ) ->addOption( 'localised', null, InputOption::VALUE_NONE, 'Create a localised model (or convert an existing model)' ); if (Components::exists('nails/module-admin')) { $this->addOption( 'admin', null, InputOption::VALUE_NONE, 'Create an admin controller' ); } }
Configure the command
protected function execute(InputInterface $oInput, OutputInterface $oOutput): int { parent::execute($oInput, $oOutput); // -------------------------------------------------------------------------- $bSkipDb = $oInput->getOption('skip-db'); $bAdmin = Components::exists('nails/module-admin') && $oInput->getOption('admin'); // -------------------------------------------------------------------------- // Test database connection if (!$bSkipDb) { try { Factory::service('PDODatabase'); } catch (ConnectionException $e) { return $this->abort( self::EXIT_CODE_FAILURE, [ 'Failed to connect to the database.', $e->getMessage(), ] ); } catch (\Exception $e) { return $this->abort( self::EXIT_CODE_FAILURE, [ 'An exception occurred when connecting to the database.', $e->getMessage(), ] ); } } // -------------------------------------------------------------------------- try { $this /** * Validate the services file for resources first, so that the corrcet * values are set on the second call. */ ->validateServiceFile(static::SERVICE_RESOURCE_TOKEN) ->validateServiceFile() ->createPath(self::MODEL_PATH) ->createPath(self::MODEL_RESOURCE_PATH); if ($bAdmin) { $this->createPath(self::ADMIN_PATH); } $this->createModel(); } catch (\Exception $e) { return $this->abort( self::EXIT_CODE_FAILURE, [$e->getMessage()] ); } // -------------------------------------------------------------------------- // Cleaning up $oOutput->writeln(''); $oOutput->writeln('<comment>Cleaning up...</comment>'); // -------------------------------------------------------------------------- // And we're done $oOutput->writeln(''); $oOutput->writeln('Complete!'); return self::EXIT_CODE_SUCCESS; }
Executes the app @param InputInterface $oInput The Input Interface provided by Symfony @param OutputInterface $oOutput The Output Interface provided by Symfony @return int
private function tableExists(\stdClass $oModel): bool { $oDb = Factory::service('PDODatabase'); $oResult = $oDb->query('SHOW TABLES LIKE "' . $oModel->table_with_prefix . '"'); return $oResult->rowCount() > 0; }
Detemine whether a particular table exists already @param \stdClass $oModel The model definition @return bool @throws \Nails\Common\Exception\FactoryException
private function convertExistingModelToLocalised( \stdClass $oModel, bool $bSkipDb, bool $bAdmin, bool $bSkipSeeder ): void { $this ->addLocalisedUseStatement($oModel) ->convertTablesToLocalised($oModel); }
Orchestrates the conversion of a normal model to a localised model @param \stdClass $oModel The model being converted @param bool $bSkipDb Whether to skip table creation @param bool $bAdmin Whether to create an admin controller or not @param bool $bSkipSeeder Whether to skip seeder creation
private function createLocalisedModel( \stdClass $oModel, bool $bSkipDb, bool $bAdmin, bool $bSkipSeeder ): array { $this ->createModelFile($oModel, 'model_localised') ->createResource($oModel, 'resource'); if (!$bSkipDb) { $this->createDatabaseTable($oModel, 'model_table_localised'); } if ($bAdmin) { $this->createAdminController($oModel); } if (!$bSkipSeeder) { $this->createSeeder($oModel); } return $this->generateServiceDefinitions($oModel); }
Orchestrates the creation of a localised model @param \stdClass $oModel The model being created @param bool $bSkipDb Whether to skip table creation @param bool $bAdmin Whether to create an admin controller or not @param bool $bSkipSeeder Whether to skip seeder creation @return array
private function createModelFile(\stdClass $oModel, string $sTemplate): self { $this->oOutput->write('Creating model <comment>' . $oModel->class_path . '</comment>... '); $this->createPath($oModel->path); $this->createFile( $oModel->path . $oModel->filename, $this->getResource('template/' . $sTemplate . '.php', (array) $oModel) ); $this->oOutput->writeln('<info>done!</info>'); return $this; }
Creates the model file @param \stdClass $oModel The model being created @param string $sTemplate The template to use @return $this @throws NailsException @throws Path\DoesNotExistException @throws Path\IsNotWritableException
private function createResource(\stdClass $oModel, string $sTemplate): self { $this->oOutput->write('Creating resource <comment>' . $oModel->resource_class_path . '</comment>... '); $this->createPath($oModel->resource_path); $this->createFile( $oModel->resource_path . $oModel->resource_filename, $this->getResource('template/' . $sTemplate . '.php', (array) $oModel) ); $this->oOutput->writeln('<info>done!</info>'); return $this; }
Creates the resource file @param \stdClass $oModel The model being created @param string $sTemplate The template to use @return $this @throws NailsException @throws Path\DoesNotExistException @throws Path\IsNotWritableException
private function createDatabaseTable(\stdClass $oModel, string $sTemplate): self { $this->oOutput->write('Adding database table... '); $oModel->nails_db_prefix = NAILS_DB_PREFIX; $oDb = Factory::service('PDODatabase'); $oDb->query($this->getResource('template/' . $sTemplate . '.php', (array) $oModel)); $this->oOutput->writeln('<info>done!</info>'); return $this; }
Creates the database table @param \stdClass $oModel The model being created @param string $sTemplate The template to use @return $this @throws NailsException @throws FactoryException
private function createAdminController(\stdClass $oModel): self { $this->oOutput->write('Creating admin controller... '); // Execute the create command, non-interactively and silently $iExitCode = $this->callCommand( 'make:controller:admin', [ 'modelName' => $oModel->service_name, '--skip-check' => true, ], false, true ); if ($iExitCode === static::EXIT_CODE_FAILURE) { $this->oOutput->writeln('<error>failed!</error>'); } else { $this->oOutput->writeln('<info>done!</info>'); } return $this; }
Creates an admin controller @param \stdClass $oModel The model being created @return $this @throws \Exception
private function generateServiceDefinitions(\stdClass $oModel): array { return [ // Service definition implode("\n", [ str_repeat(' ', $this->iServicesIndent) . '\'' . $oModel->service_name . '\' => function () {', str_repeat(' ', $this->iServicesIndent) . ' return new ' . $oModel->class_path . '();', str_repeat(' ', $this->iServicesIndent) . '},', ]), // Resource definition implode("\n", [ str_repeat(' ', $this->iServicesIndent) . '\'' . $oModel->service_name . '\' => function ($oObj) {', str_repeat(' ', $this->iServicesIndent) . ' return new ' . $oModel->resource_class_path . '($oObj);', str_repeat(' ', $this->iServicesIndent) . '},', ]), ]; }
Genenrates the service file definitions for a model @param \stdClass $oModel The model being created @return string[]
public static function siteUrl(string $sUrl = null, bool $bForceSecure = false): string { $oConfig = \Nails\Factory::service('Config'); return $oConfig::siteUrl($sUrl, $bForceSecure); }
Create a local URL based on your basepath. Segments can be passed via the first parameter either as a string or an array. @param mixed $sUrl URI segments, either as a string or an array @param bool $bForceSecure Whether to force the url to be secure or not @return string
public static function redirect(string $sUrl = null, string $sMethod = 'location', int $iHttpResponseCode = 302): void { /** * Call the post_system hook, the system will be killed in approximately 13 * lines so this is the last chance to cleanup. */ $oHook =& load_class('Hooks', 'core'); $oHook->call_hook('post_system'); // -------------------------------------------------------------------------- if (!preg_match('#^https?://#i', $sUrl)) { $sUrl = site_url($sUrl); } switch ($sMethod) { case 'refresh': header("Refresh:0;url=" . $sUrl); break; default: header('Location: ' . $sUrl, true, $iHttpResponseCode); break; } exit; }
Header Redirect Header redirect in two flavors For very fine grained control over headers, you could use the Output Library's set_header() function. Overriding so as to call the post_system hook before exit()'ing @param string $sUrl The uri to redirect to @param string $sMethod The redirect method @param integer $sHttpResponseCode The response code to send @return void
public static function tel(string $sUrl = null, string $sTitle = '', string $sAttributes = ''): string { $sTitle = empty($sTitle) ? $sUrl : $sTitle; $sUrl = preg_replace('/[^\+0-9]/', '', $sUrl); $sUrl = 'tel://' . $sUrl; return anchor($sUrl, $sTitle, $sAttributes); }
Generates a hyperlink using the tel: scheme @param string $sUrl The phone number to link @param string $sTitle The title to give the hyperlink @param string $sAttributes Any attributes to give the hyperlink @return string
protected function execute(InputInterface $oInput, OutputInterface $oOutput) { parent::execute($oInput, $oOutput); $oOutput->writeln(''); $oOutput->writeln('<info>--------------------</info>'); $oOutput->writeln('<info>Nails Routes Rewrite</info>'); $oOutput->writeln('<info>--------------------</info>'); $oOutput->writeln(''); $oRoutesService = Factory::service('Routes'); try { if (!$oRoutesService->update(null, $oOutput)) { throw new NailsException($oRoutesService->lastError()); } } catch (\Exception $e) { $this->abort( static::EXIT_CODE_FAILURE, [ 'There was a problem writing the routes.', $e->getMessage(), ] ); } // Cleaning up $oOutput->writeln(''); $oOutput->writeln('<comment>Cleaning up...</comment>'); // And we're done! $oOutput->writeln(''); $oOutput->writeln('Complete!'); return static::EXIT_CODE_SUCCESS; }
Executes the app @param InputInterface $oInput The Input Interface provided by Symfony @param OutputInterface $oOutput The Output Interface provided by Symfony @return int
public function getUrl(string $sKey = null): string { $sUrl = rtrim($this->sUrl, '/'); $sUrl .= $sKey ? '/' . $sKey : ''; return $sUrl; }
Return the URL for the public cache @param string|null $sKey The cache key @return string
public static function getFromArray($mKey, $aArray, $mDefault = null) { $aKeys = (array) $mKey; foreach ($aKeys as $sKey) { if (array_key_exists($sKey, $aArray)) { return $aArray[$sKey]; } } return $mDefault; }
Retrieve a value from $sArray at $sKey, if it exists @param string|array $mKey The key to get, if an array is passed the first valid key will be returned @param array $aArray The array to look in @param mixed $mDefault What to return if $sKey doesn't exist in $aArray @return mixed
public static function arrayUniqueMulti(array $aArray) { // Unique Array for return $aArrayRewrite = []; // Array with the md5 hashes $aArrayHashes = []; foreach ($aArray as $key => $item) { // Serialize the current element and create a md5 hash $hash = md5(serialize($item)); /** * If the md5 didn't come up yet, add the element to to arrayRewrite, * otherwise drop it */ if (!isset($aArrayHashes[$hash])) { // Save the current element hash $aArrayHashes[$hash] = $hash; // Add element to the unique Array $aArrayRewrite[$key] = $item; } } unset($aArrayHashes); unset($key); unset($item); unset($hash); return $aArrayRewrite; }
Removes duplicate items from a multi-dimensional array Hat-tip: http://phpdevblog.niknovo.com/2009/01/using-array-unique-with-multidimensional-arrays.html @param array $aArray The array to filter @return array
public static function arraySortMulti(array &$aArray, $sField) { uasort($aArray, function ($a, $b) use ($sField) { $oA = (object) $a; $oB = (object) $b; $mA = property_exists($oA, $sField) ? strtolower($oA->$sField) : null; $mB = property_exists($oB, $sField) ? strtolower($oB->$sField) : null; // Equal? if ($mA == $mB) { return 0; } // If $mA is a prefix of $mB then $mA comes first if (preg_match('/^' . preg_quote($mA, '/') . '/', $mB)) { return -1; } // Not equal, work out which takes precedence $aSort = [$mA, $mB]; sort($aSort); return $aSort[0] == $mA ? -1 : 1; }); }
Sorts a multi dimensional array @param array &$aArray The array to sort @param string $sField The key to sort on
public static function arraySearchMulti($sValue, $sKey, array $aArray) { foreach ($aArray as $k => $val) { if (is_array($val)) { if ($val[$sKey] == $sValue) { return $k; } } elseif (is_object($val)) { if ($val->$sKey == $sValue) { return $k; } } } return false; }
Searches a multi-dimensional array @param string $sValue Search value @param string $sKey Key to search @param array $aArray The array to search @return mixed The array key on success, false on failure
public static function inArray($aValues, array $aArray): bool { if (is_string($aValues)) { $aValues = (array) $aValues; } foreach ($aValues as $sValue) { if (in_array($sValue, $aArray)) { return true; } } return false; }
Test if an array contains value(s) @param string|array $aValues The values to check for @param array $aArray The array to search @return bool
public static function inArrayMulti($sValue, $sKey, array $aArray): bool { return static::arraySearchMulti($sValue, $sKey, $aArray) !== false; }
Reports whether a value exists in a multi dimensional array @param string $sValue The value to search for @param string $sKey The key to search on @param array $aArray The array to search @return boolean
public static function arrayExtractProperty(array $aInput, $sProperty) { $aOutput = []; foreach ($aInput as $mItem) { $aItem = (array) $mItem; if (array_key_exists($sProperty, $aItem)) { $aOutput[] = $aItem[$sProperty]; } } return $aOutput; }
Extracts the value of properties from a multi-dimensional array into an array of those values @param array $aInput The array to iterate over @param string $sProperty The property to extract @return array
public function show_error( $sSubject, $sMessage = '', $sTemplate = '500', $iStatusCode = 500, $bUseException = true ) { if (is_array($sMessage)) { $sMessage = implode('<br>', $sMessage); } if ($bUseException) { throw new NailsException($sMessage, $iStatusCode); } else { $oErrorHandler = Factory::service('ErrorHandler'); $oErrorHandler->showFatalErrorScreen($sSubject, $sMessage); } }
Override the show_error method and pass to the Nails ErrorHandler @param string $sSubject The error's subject @param string $sMessage The error message @param string $sTemplate Unused; only there to suppress compatibility notification @param int $iStatusCode Unused; only there to suppress compatibility notification @param boolean $bUseException Whether to use an exception @throws NailsException @return void
public function show_exception($oException) { $oErrorHandler = Factory::service('ErrorHandler'); $sMessage = implode( '; ', [ 'Code: ' . $oException->getCode(), 'File: ' . $oException->getFile(), 'Line: ' . $oException->getLine(), ] ); $oErrorHandler->showFatalErrorScreen($oException->getMessage(), $sMessage); }
Override the show_exception method and pass to the Nails ErrorHandler @param \Exception $oException
public function show_php_error($iSeverity, $sMessage, $sFilePath, $iLine) { $oErrorHandler = Factory::service('ErrorHandler'); return $oErrorHandler->triggerError($iSeverity, $sMessage, $sFilePath, $iLine); }
Overrides the show_php_error method in order to track errors @param int $iSeverity @param string $sMessage @param string $sFilePath @param int $iLine @return string
public function show_404($sPage = '', $bLogError = true) { $oErrorHandler = Factory::service('ErrorHandler'); $oErrorHandler->show404($bLogError); }
Renders the 404 page and halts script execution @param bool $bLogError Whether to log the error @return void
protected function autoLoadSubscriptions($sNamespace) { $sClassName = '\\' . $sNamespace . 'Events'; if (class_exists($sClassName)) { $oClass = new $sClassName(); if (is_callable([$oClass, 'autoload'])) { $aSubscriptions = $oClass->autoload(); if (!empty($aSubscriptions)) { foreach ($aSubscriptions as $oSubscription) { $aEvent = (array) $oSubscription->getEvent(); $sNamespace = $oSubscription->getNamespace(); $mCallback = $oSubscription->getCallback(); $bOnce = $oSubscription->isOnce(); if (!empty($aEvent) && !empty($sNamespace) && !empty($mCallback)) { foreach ($aEvent as $sEvent) { $this->subscribe($sEvent, $sNamespace, $mCallback, $bOnce); } } } } } unset($oClass); } }
Looks for a component's event handler and executes the autoload() method if there is one @param string $sNamespace The namespace to check @return void
public function subscribe($sEvent, $sNamespace, $mCallback, $bOnce = false) { $sEvent = strtoupper($sEvent); $sNamespace = strtoupper($sNamespace); if (is_callable($mCallback)) { if (!isset($this->aSubscriptions[$sNamespace])) { $this->aSubscriptions[$sNamespace] = []; } if (!isset($this->aSubscriptions[$sNamespace][$sEvent])) { $this->aSubscriptions[$sNamespace][$sEvent] = []; } // Prevent duplicate subscriptions $sHash = md5(serialize($mCallback)); if (!isset($this->aSubscriptions[$sNamespace][$sEvent][$sHash])) { $this->aSubscriptions[$sNamespace][$sEvent][$sHash] = (object) [ 'is_once' => $bOnce, 'callback' => $mCallback, ]; } } return $this; }
Subscribe to an event @param string $sEvent The event to subscribe to @param string $sNamespace The event's namespace @param mixed $mCallback The callback to execute @param boolean $bOnce Whether the subscription should only fire once @return \Nails\Common\Service\Event
public function trigger($sEvent, $sNamespace = 'nails/common', $aData = []) { $this->addHistory($sEvent, $sNamespace); $sEvent = strtoupper($sEvent); $sNamespace = strtoupper($sNamespace); if (!empty($this->aSubscriptions[$sNamespace][$sEvent])) { foreach ($this->aSubscriptions[$sNamespace][$sEvent] as $sSubscriptionHash => $oSubscription) { if (is_callable($oSubscription->callback)) { call_user_func_array($oSubscription->callback, $aData); } if ($oSubscription->is_once) { unset($this->aSubscriptions[$sNamespace][$sEvent][$sSubscriptionHash]); } } } return $this; }
Trigger the event and execute all callbacks @param string $sEvent The event to trigger @param string $sNamespace The event's namespace @param array $aData Data to pass to the callbacks @return \Nails\Common\Service\Event
protected function addHistory($sEvent, $sNamespace = 'nails/common') { $sEvent = strtoupper($sEvent); $sNamespace = strtoupper($sNamespace); if (!array_key_exists($sNamespace, $this->aHistory)) { $this->aHistory[$sNamespace] = []; } if (!array_key_exists($sEvent, $this->aHistory[$sNamespace])) { $this->aHistory[$sNamespace][$sEvent] = (object) [ 'count' => 0, 'timestamps' => [], ]; } $this->aHistory[$sNamespace][$sEvent]->count++; $this->aHistory[$sNamespace][$sEvent]->timestamps[] = microtime(true); return $this; }
Adds a history item to the history array @param string $sEvent The event name @param string $sNamespace The event namespace @return $this
public function getHistory($sNamespace = null, $sEvent = null) { $sEvent = strtoupper($sEvent); $sNamespace = strtoupper($sNamespace); if (empty($sNamespace) && empty($sEvent)) { return $this->aHistory; } elseif ( empty($sEvent) && !empty($sNamespace) && array_key_exists($sNamespace, $this->aHistory) ) { return $this->aHistory[$sNamespace]; } elseif ( !empty($sNamespace) && array_key_exists($sNamespace, $this->aHistory) && !empty($sEvent) && array_key_exists($sEvent, $this->aHistory[$sNamespace]) ) { return $this->aHistory[$sNamespace][$sEvent]; } return null; }
Retrieve a history item @param string $sNamespace The event namespace @param string $sEvent The event name @return array|\stdClass|null
public function set($sType, $sMessage) { $sType = strtoupper(trim($sType)); $sMessage = trim($sMessage); $this->aMessages[$sType] = $sMessage; return $this; }
Set a feedback message @param string $sType The type of message to set @param string $sMessage The message to set @return Object
public function get($sType) { $sType = strtoupper(trim($sType)); if (!empty($this->aMessages[$sType])) { return $this->aMessages[$sType]; } else { return ''; } }
Return a feedack message @param string $sType The type of feedback to return @return string
public function clear($sType = '') { if (empty($sType)) { $this->aMessages[$sType] = array(); } else { $this->aMessages[$sType] = ''; } }
Clear feedback messages @param string $sType The type of feedback to clear @return
public function getAllDateFormat() { $aFormats = static::FORMAT_DATE; $oNow = Factory::factory('DateTime'); foreach ($aFormats as &$aFormat) { $aFormat = (object) $aFormat; $aFormat->example = $oNow->format($aFormat->format); } return $aFormats; }
Returns all the defined date format objects @return array
public function getAllDateFormatFlat() { $aOut = []; $aFormats = $this->getAllDateFormat(); foreach ($aFormats as $oFormat) { $aOut[$oFormat->slug] = $oFormat->example; } return $aOut; }
Returns all the date format objects as a flat array @return array
public function getDateFormatBySlug($sSlug) { $aFormats = $this->getAllDateFormat(); foreach ($aFormats as $oFormat) { if ($oFormat->slug === $sSlug) { return $oFormat; } } return null; }
Looks for a date format by it's slug @param string $sSlug The slug to search for @return \stdClass|null
public function getAllTimeFormat() { $aFormats = static::FORMAT_TIME; foreach ($aFormats as &$aFormat) { $aFormat = (object) $aFormat; $oDateTimeObject = static::convert(time(), $this->sTimezoneUser); $aFormat->example = $oDateTimeObject->format($aFormat->format); } return $aFormats; }
Returns all the defined time format objects @return array
public function getAllTimeFormatFlat() { $aOut = []; $aFormats = $this->getAllTimeFormat(); foreach ($aFormats as $oFormat) { $aOut[$oFormat->slug] = $oFormat->label; } return $aOut; }
Returns all the time format objects as a flat array @return array
public function getTimeFormatBySlug($sSlug) { $aFormats = $this->getAllTimeFormat(); foreach ($aFormats as $oFormat) { if ($oFormat->slug === $sSlug) { return $oFormat; } } return null; }
Looks for a time format by it's slug @param string $sSlug The slug to search for @return \stdClass|null
public function setDateFormat($sSlug) { $oDateFormat = $this->getDateFormatBySlug($sSlug); if (empty($oDateFormat)) { $oDateFormat = $this->getDateFormatDefault(); } $this->sUserFormatDate = $oDateFormat->format; }
Set the date format to use, uses default if slug cannot be found @param string $sSlug The date format's slug
public function setTimeFormat($sSlug = null) { $oTimeFormat = $this->getTimeFormatBySlug($sSlug); if (empty($oTimeFormat)) { $oTimeFormat = $this->getTimeFormatDefault(); } $this->sUserFormatTime = $oTimeFormat->format; }
Set the time format to use, uses default if slug cannot be found @param string $sSlug The time format's slug
public function toUserDate($mTimestamp = null, $sFormat = null) { $oConverted = static::convert($mTimestamp, $this->sTimezoneUser, $this->sTimezoneNails); if (is_null($oConverted)) { return null; } if (is_null($sFormat)) { $sFormat = $this->sUserFormatDate; } return $oConverted->format($sFormat); }
Convert a date timestamp to the User's timezone from the Nails timezone @param mixed $mTimestamp The timestamp to convert @param string $sFormat The format of the timestamp to return, defaults to User's date preference @return string
public function toNailsDate($mTimestamp = null) { $oConverted = static::convert($mTimestamp, $this->sTimezoneNails, $this->sTimezoneUser); if (is_null($oConverted)) { return null; } return $oConverted->format('Y-m-d'); }
Convert a date timestamp to the Nails timezone from the User's timezone, formatted as Y-m-d @param mixed $mTimestamp The timestamp to convert @return string|null
public function toUserDatetime($mTimestamp = null, $sFormat = null) { $oConverted = static::convert($mTimestamp, $this->sTimezoneUser, $this->sTimezoneNails); if (is_null($oConverted)) { return null; } if (is_null($sFormat)) { $sFormat = $this->sUserFormatDate . ' ' . $this->sUserFormatTime; } return $oConverted->format($sFormat); }
Convert a datetime timestamp to the user's timezone from the Nails timezone @param mixed $mTimestamp The timestamp to convert @param string $sFormat The format of the timestamp to return, defaults to User's dateTime preference @return string|null
public function setTimezones($sTzNails = null, $sTzUser = null) { $this->setNailsTimezone($sTzNails); $this->setUserTimezone($sTzUser); }
Sets the Nails and User timezones simultaneously @param string $sTzNails The Nails timezone @param string $sTzUser The User's timezone
public function getAllTimezone() { // Hat-tip to: https://gist.github.com/serverdensity/82576 $aZones = \DateTimeZone::listIdentifiers(); $aLocations = ['UTC' => 'Coordinated Universal Time (UTC/GMT)']; foreach ($aZones as $sZone) { // 0 => Continent, 1 => City $aZoneExploded = explode('/', $sZone); $aZoneAcceptable = [ 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific', ]; // Only use "friendly" continent names if (in_array($aZoneExploded[0], $aZoneAcceptable)) { if (isset($aZoneExploded[1]) != '') { $sArea = str_replace('_', ' ', $aZoneExploded[1]); if (!empty($aZoneExploded[2])) { $sArea = $sArea . ' (' . str_replace('_', ' ', $aZoneExploded[2]) . ')'; } // Creates array(DateTimeZone => 'Friendly name') $aLocations[$aZoneExploded[0]][$sZone] = $sArea; } } } return $aLocations; }
Returns a multi-dimensional array of supported timezones @return array
public function getAllTimezoneFlat() { $aTimezones = $this->getAllTimezone(); $aOut = []; foreach ($aTimezones as $sKey => $mValue) { if (is_array($mValue)) { foreach ($mValue as $subKey => $subValue) { if (is_string($subValue)) { $aOut[$subKey] = $sKey . ' - ' . $subValue; } } } else { $aOut[$sKey] = $mValue; } } return $aOut; }
Returns all the supported timezones as a flat array @return array
public static function getCodeFromTimezone($sTimezone) { $aAbbreviations = \DateTimeZone::listAbbreviations(); foreach ($aAbbreviations as $sCode => $aValues) { foreach ($aValues as $aValue) { if ($aValue['timezone_id'] == $sTimezone) { return strtoupper($sCode); } } } return false; }
Get the timezone code from the timezone string @param string $sTimezone The timezone, e.g. Europe/London @return string|false
public static function getTimezoneFromCode($sCode) { $aAbbreviations = \DateTimeZone::listAbbreviations(); foreach ($aAbbreviations as $sTzCode => $aValues) { if (strtolower($sCode) == $sTzCode) { $aTimeZone = reset($aValues); return getFromArray('timezone_id', $aTimeZone, false); } } return false; }
Get the timezone string from the timezone code @param string $sCode The timezone code, e.g. GMT @return string|false
public static function convert($mTimestamp, $sToTz, $sFromTz = 'UTC') { // Has a specific timestamp been given? if (is_null($mTimestamp)) { $oDateTime = Factory::factory('DateTime'); } elseif (is_numeric($mTimestamp)) { $oDateTime = Factory::factory('DateTime'); $oDateTime->setTimestamp($mTimestamp); } elseif ($mTimestamp instanceof \DateTime) { $oDateTime = $mTimestamp; } elseif (!empty($mTimestamp) && $mTimestamp !== '0000-00-00' && $mTimestamp !== '0000-00-00 00:00:00') { $oDateTime = new \DateTime($mTimestamp); } else { return null; } // -------------------------------------------------------------------------- // Perform the conversion $oFromTz = new \DateTimeZone($sFromTz); $oToTz = new \DateTimeZone($sToTz); $oOut = new \DateTime($oDateTime->format('Y-m-d H:i:s'), $oFromTz); $oOut->setTimeZone($oToTz); return $oOut; }
Arbitrarily convert a timestamp between timezones @param mixed $mTimestamp The timestamp to convert. If null current time is used, if numeric treated as timestamp, else passed to strtotime() @param string $sToTz The timezone to convert to @param string $sFromTz The timezone to convert from @return \DateTime|null
public function calculateAge( $birthYear, $birthMonth, $birthDay, $deathYear = null, $deathMonth = null, $deathDay = null ) { // Only calculate to a date which isn't today if all values are supplied if (is_null($deathYear) || is_null($deathMonth) || is_null($deathDay)) { $deathYear = date('Y'); $deathMonth = date('m'); $deathDay = date('d'); } // -------------------------------------------------------------------------- $_birth_time = mktime(0, 0, 0, $birthMonth, $birthDay, $birthYear); $_death_time = mktime(0, 0, 0, $deathMonth, $deathDay, $deathYear); // -------------------------------------------------------------------------- // If $_death_time is smaller than $_birth_time then something's wrong if ($_death_time < $_birth_time) { return false; } // -------------------------------------------------------------------------- // Calculate age $_age = ($_birth_time < 0) ? ($_death_time + ($_birth_time * -1)) : $_death_time - $_birth_time; $_age_years = floor($_age / (31536000)); // Divide by number of seconds in a year // -------------------------------------------------------------------------- return $_age_years; }
Calculates a person's age (or age at a certain date) @param string $birthYear The year to calculate from @param string $birthMonth The month to calculate from @param string $birthDay The day to calculate from @param string $deathYear The year to calculate to @param string $deathMonth The month to calculate to @param string $deathDay The day to calculate to @return bool|float
public function preProcessConfiguration(array $configs): array { $newConfigs = $configs; $prependConfigs = []; foreach ($configs as $index => $config) { if (isset($config['system'])) { $prependConfigs[] = ['system' => $config['system']]; unset($config['system']); $newConfigs[$index] = $config; } foreach (array_keys($config) as $configName) { if (!in_array($configName, self::SITEACCCESS_AWARE_SETTINGS, true)) { unset($config[$configName]); } } $newConfigs[] = ['system' => ['default' => $config]]; } return array_merge($prependConfigs, $newConfigs); }
Pre-processes the configuration before it is resolved. The point of the preprocessor is to generate eZ Platform siteaccess aware configuration for every key that is available in self::SITEACCCESS_AWARE_SETTINGS. With this, the following: [ 0 => [ 'netgen_block_manager' => [ 'view' => ... ] ] ] becomes: [ 0 => [ 'netgen_block_manager' => [ 'view' => ..., 'system' => [ 'default' => [ 'view' => ... ] ] ] ] ] If the original array already has a system key, it will be removed and prepended to configs generated from the original parameters.
public function postProcessConfiguration(array $config): array { $config = $this->fixUpViewConfig($config); $processor = new ConfigurationProcessor($this->container, $this->extension->getAlias()); foreach (array_keys($config) as $key) { if ($key === 'system' || !in_array($key, self::SITEACCCESS_AWARE_SETTINGS, true)) { continue; } is_array($config[$key]) ? $processor->mapConfigArray($key, $config, ContextualizerInterface::MERGE_FROM_SECOND_LEVEL) : $processor->mapSetting($key, $config); } $designList = array_keys($config['design_list']); foreach ($config['system'] as $scopeConfig) { $this->validateCurrentDesign($scopeConfig['design'], $designList); } return $config; }
Post-processes the resolved configuration. The postprocessor calls eZ Platform mapConfigArray and mapSettings methods from siteaccess aware configuration processor as per documentation, to make the configuration correctly apply to all siteaccesses.
private function fixUpViewConfig(array $config): array { foreach ($config['system'] as $scope => $scopeConfig) { if ($scope === 'default') { continue; } foreach (array_keys($scopeConfig['view']) as $viewName) { if (isset($config['system']['default']['view'][$viewName])) { foreach ($config['system']['default']['view'][$viewName] as $context => $defaultRules) { if (!isset($config['system'][$scope]['view'][$viewName][$context])) { $config['system'][$scope]['view'][$viewName][$context] = []; } $config['system'][$scope]['view'][$viewName][$context] += $defaultRules; } } } } return $config; }
Ugly hack to support semantic view config. The problem is, eZ semantic config supports only merging arrays up to second level, but in view config we have three. view: block_view: context: config1: ... config2: ... So instead of merging view.block_view.context, eZ merges view.block_view, thus loosing a good deal of config. This iterates over all default view configs for each view and context, and merges them in any found siteaccess or siteaccess group config, to make sure they're not lost after contextualizer does it's thing.
private function buildSectionFilterParameters(ParameterBuilderInterface $builder, array $groups = []): void { $builder->add( 'filter_by_section', ParameterType\Compound\BooleanType::class, [ 'groups' => $groups, ] ); $builder->get('filter_by_section')->add( 'sections', EzParameterType\SectionType::class, [ 'multiple' => true, 'groups' => $groups, ] ); }
Builds the parameters for filtering by sections.
private function getSectionFilterCriteria(ParameterCollectionInterface $parameterCollection): ?Criterion { if ($parameterCollection->getParameter('filter_by_section')->getValue() !== true) { return null; } $sections = $parameterCollection->getParameter('sections')->getValue() ?? []; if (count($sections) === 0) { return null; } return new Criterion\SectionId($this->getSectionIds($sections)); }
Returns the criteria used to filter content by section.
private function getSectionIds(array $sectionIdentifiers): array { $idList = []; foreach ($sectionIdentifiers as $identifier) { try { $section = $this->sectionHandler->loadByIdentifier($identifier); $idList[] = $section->id; } catch (NotFoundException $e) { continue; } } return $idList; }
Returns section IDs for all provided section identifiers.
protected function execute(InputInterface $oInput, OutputInterface $oOutput) { parent::execute($oInput, $oOutput); foreach (\Nails\Components::available() as $oComponent) { if (!empty($oComponent->scripts->install)) { $this->oOutput->writeln('Executing post-install scripts for: <comment>' . $oComponent->slug . '</comment>'); $this->oOutput->writeln('> <info>cd ' . $oComponent->path . '</info>'); chdir($oComponent->path); $this->executeCommand($oComponent->scripts->install); } } return static::EXIT_CODE_SUCCESS; }
Executes the command @param InputInterface $oInput The Input Interface provided by Symfony @param OutputInterface $oOutput The Output Interface provided by Symfony @return int @throws \Nails\Common\Exception\FactoryException
protected function executeCommand($sCommand) { if (is_iterable($sCommand)) { foreach ($sCommand as $sCommand) { $this->executeCommand($sCommand); } } elseif (is_string($sCommand)) { $this->oOutput->writeln('> <info>' . $sCommand . '</info>'); exec($sCommand, $aOutput, $iReturnVal); if ($iReturnVal) { throw new \RuntimeException('Failed to execute command: ' . $sCommand, $iReturnVal); } } }
Executes a command @param string|iterable $sCommand The command to execute
private function addLayoutsSubMenu(ItemInterface $menu): void { $menuOrder = $this->getNewMenuOrder($menu); $layouts = $menu ->addChild('nglayouts') ->setLabel('menu.main_menu.header') ->setExtra('translation_domain', 'ngbm_admin'); $layouts ->addChild('layout_resolver', ['route' => 'ngbm_admin_layout_resolver_index']) ->setLabel('menu.main_menu.layout_resolver') ->setExtra('translation_domain', 'ngbm_admin'); $layouts ->addChild('layouts', ['route' => 'ngbm_admin_layouts_index']) ->setLabel('menu.main_menu.layouts') ->setExtra('translation_domain', 'ngbm_admin'); $layouts ->addChild('shared_layouts', ['route' => 'ngbm_admin_shared_layouts_index']) ->setLabel('menu.main_menu.shared_layouts') ->setExtra('translation_domain', 'ngbm_admin'); $menu->reorderChildren($menuOrder); }
Adds the Netgen Layouts submenu to eZ Platform admin interface.
private function getNewMenuOrder(ItemInterface $menu): array { $menuOrder = array_keys($menu->getChildren()); $configMenuIndex = array_search(MainMenuBuilder::ITEM_ADMIN, $menuOrder, true); if (is_int($configMenuIndex)) { array_splice($menuOrder, $configMenuIndex, 0, ['nglayouts']); return $menuOrder; } $menuOrder[] = 'nglayouts'; return $menuOrder; }
Returns the new menu order.
protected function setRequiredFields() { $this->requiredFields = Common::createArrayObject([ 'transaction_id', 'amount', 'currency', 'card_number', ]); $this->requiredFieldValues = Common::createArrayObject([ 'currency' => ['EUR', 'USD'], 'card_number' => $this->getGiftCardNumberValidator() ]); }
Set the required fields @return void
protected function getPaymentTransactionStructure() { return [ 'amount' => $this->transformAmount($this->amount, $this->currency), 'currency' => $this->currency, 'card_number' => $this->card_number, 'cvv' => $this->cvv, 'customer_email' => $this->customer_email, 'customer_phone' => $this->customer_phone, 'billing_address' => $this->getBillingAddressParamsStructure(), 'shipping_address' => $this->getShippingAddressParamsStructure(), 'dynamic_descriptor_params' => $this->getDynamicDescriptorParamsStructure(), 'reference_id' => $this->reference_id ]; }
Return additional request attributes @return array
protected function populateStructure() { $treeStructure = [ 'payment_transaction' => [ 'transaction_type' => \Genesis\API\Constants\Transaction\Types::AVS, 'transaction_id' => $this->transaction_id, 'usage' => $this->usage, 'moto' => $this->moto, 'remote_ip' => $this->remote_ip, '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(), 'risk_params' => $this->getRiskParamsStructure() ] ]; $this->treeStructure = \Genesis\Utils\Common::createArrayObject($treeStructure); }
Create the request's Tree structure @return void
public function fix($module, $oConfig = null) { if ($oConfig !== null) { $this->setConfig($oConfig); } $moduleId = $module->getId(); if (!$this->initialCacheClearDone) { //clearing some cache to be sure that fix runs not against a stale cache ModuleVariablesLocator::resetModuleVariables(); if (extension_loaded('apc') && ini_get('apc.enabled')) { apc_clear_cache(); } if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $this->output->writeln("initial cache cleared"); } $this->initialCacheClearDone = true; } $this->module = $module; $this->needCacheClear = false; $this->restoreModuleInformation($module, $moduleId); if ($this->needCacheClear){ $this->resetModuleCache($module); $this->output->writeln("cache cleared for $moduleId"); } }
Fix module states task runs version, extend, files, templates, blocks, settings and events information fix tasks @param Module $module @param Config|null $oConfig If not passed uses default base shop config
protected function _addTemplateFiles($aModuleTemplates, $sModuleId) { $aTemplates = (array) $this->getConfig()->getConfigParam('aModuleTemplates'); $old = isset($aTemplates[$sModuleId]) ? $aTemplates[$sModuleId] : null; if (is_array($aModuleTemplates)) { $diff = $this->diff($old,$aModuleTemplates); if ($diff) { $this->output->writeLn("$sModuleId fixing templates:" . $old === null ? ' everything ' : var_export($diff, true)); $aTemplates[$sModuleId] = $aModuleTemplates; $this->_saveToConfig('aModuleTemplates', $aTemplates); $this->needCacheClear = true; } } else { if ($old) { $this->output->writeLn("$sModuleId unregister templates:"); $this->_deleteTemplateFiles($sModuleId); $this->needCacheClear = true; } } }
Add module template files to config for smarty. @param array $aModuleTemplates Module templates array @param string $sModuleId Module id
protected function _addModuleEvents($aModuleEvents, $sModuleId) { $aEvents = (array) $this->getConfig()->getConfigParam('aModuleEvents'); $old = isset($aEvents[$sModuleId]) ? $aEvents[$sModuleId] : null; if (is_array($aModuleEvents) && count($aModuleEvents)) { $diff = $this->diff($old,$aModuleEvents); if ($diff) { $aEvents[$sModuleId] = $aModuleEvents; $this->output->writeLn("$sModuleId fixing module events:" . $old == null ? ' everything ' : var_export($diff, true)); $this->_saveToConfig('aModuleEvents', $aEvents); $this->needCacheClear = true; } } else { if ($old) { $this->output->writeLn("$sModuleId unregister events"); $this->_deleteModuleEvents($sModuleId); $this->needCacheClear = true; } } }
Add module events to config. @param array $aModuleEvents Module events @param string $sModuleId Module id
protected function _addModuleExtensions($moduleExtensions, $moduleId) { $extensions = (array) $this->getConfig()->getConfigParam('aModuleExtensions'); $old = isset($extensions[$moduleId]) ? $extensions[$moduleId] : null; $old = (array) $old; $new = $moduleExtensions === null ? [] : array_values($moduleExtensions); if (is_array($moduleExtensions)) { $diff = $this->diff($old, $new); if ($diff) { $extensions[$moduleId] = array_values($moduleExtensions); $this->output->writeLn("$moduleId fixing module extensions:" . $old === null ? ' everything ' : var_export($diff, true)); $this->_saveToConfig('aModuleExtensions', $extensions); $this->needCacheClear = true; } } else { $this->output->writeLn("$moduleId unregister module extensions"); $this->needCacheClear = true; $this->_saveToConfig('aModuleExtensions', []); } }
Add module id with extensions to config. @param array $moduleExtensions Module version @param string $moduleId Module id
protected function _addModuleVersion($sModuleVersion, $sModuleId) { $aVersions = (array) $this->getConfig()->getConfigParam('aModuleVersions'); $old = isset($aVersions[$sModuleId]) ? $aVersions[$sModuleId] : ''; if (is_array($aVersions)) { $aVersions[$sModuleId] = $sModuleVersion; if ($old !== $sModuleVersion) { $this->output->writeLn("$sModuleId fixing module version from $old to $sModuleVersion"); $aEvents[$sModuleId] = $sModuleVersion; $this->_saveToConfig('aModuleVersions', $aVersions); $this->needCacheClear = true; } } else { if ($old) { $this->output->writeLn("$sModuleId unregister module version"); $this->_deleteModuleVersions($sModuleId); $this->needCacheClear = true; } } }
Add module version to config. @param string $sModuleVersion Module version @param string $sModuleId Module id
private function restoreModuleInformation($module, $moduleId) { $this->_addExtensions($module); $metaDataVersion = $module->getMetaDataVersion(); $metaDataVersion = $metaDataVersion == '' ? $metaDataVersion = "1.0" : $metaDataVersion; if (version_compare($metaDataVersion, '2.0', '<')) { $this->_addModuleFiles($module->getInfo("files"), $moduleId); } $this->_addTemplateBlocks($module->getInfo("blocks"), $moduleId); $this->_addTemplateFiles($module->getInfo("templates"), $moduleId); $this->_addModuleSettings($module->getInfo("settings"), $moduleId); $this->_addModuleVersion($module->getInfo("version"), $moduleId); $this->_addModuleExtensions($module->getExtensions(), $moduleId); $this->_addModuleEvents($module->getInfo("events"), $moduleId); if (version_compare($metaDataVersion, '2.0', '>=')) { try { $this->setModuleControllers($module->getControllers(), $moduleId, $module); } catch (ModuleValidationException $exception) { print "[ERROR]: duplicate controllers:" . $exception->getMessage() ."\n"; } } }
Code taken from OxidEsales\EshopCommunity\Core\Module::activate @param Module $module @param string $moduleId @throws \OxidEsales\Eshop\Core\Exception\StandardException
protected function _addModuleSettings($moduleSettings, $moduleId) { $config = $this->getConfig(); $shopId = $config->getShopId(); if (is_array($moduleSettings)) { foreach ($moduleSettings as $setting) { $module = $this->getModuleConfigId($moduleId); $name = $setting["name"]; $type = $setting["type"]; $value = is_null($config->getConfigParam($name)) ? $setting["value"] : $config->getConfigParam($name); $changed = $config->saveShopConfVar($type, $name, $value, $shopId, $module); if ($changed) { $this->output->writeln("$moduleId: setting for '$name' fixed'"); $this->needCacheClear = $this->needCacheClear || $changed; } } } }
Adds settings to database. @param array $moduleSettings Module settings array @param string $moduleId Module id
protected function setModuleControllers($moduleControllers, $moduleId, $module) { if ($module->isActive()) { $classProviderStorage = $this->getClassProviderStorage(); $dbMap = $classProviderStorage->get(); $controllersForThatModuleInDb = isset($dbMap[$moduleId]) ? $dbMap[$moduleId] : []; $duplicatedKeys = array_intersect_key( array_change_key_case($moduleControllers, CASE_LOWER), $controllersForThatModuleInDb ); if (array_diff_assoc($moduleControllers, $duplicatedKeys)) { $this->output->writeLn("$moduleId fix module ModuleControllers"); $this->deleteModuleControllers($moduleId); $this->resetModuleCache($module); $this->validateModuleMetadataControllersOnActivation($moduleControllers); $classProviderStorage = $this->getClassProviderStorage(); $classProviderStorage->add($moduleId, $moduleControllers); $this->needCacheClear = true; } } else { $moduleCache = oxNew( \OxidEsales\Eshop\Core\Module\ModuleCache::class, $module); $moduleInstaller = oxNew(\OxidEsales\Eshop\Core\Module\ModuleInstaller::class, $moduleCache); $moduleInstaller->deactivate($module);} }
Add controllers map for a given module Id to config @param array $moduleControllers Map of controller ids and class names @param string $moduleId The Id of the module @param Module $module Module core class
protected function _addExtensions(\OxidEsales\Eshop\Core\Module\Module $module) { $aModulesDefault = $this->getConfig()->getConfigParam('aModules'); $aModules = $this->getModulesWithExtendedClass(); $aModules = $this->_removeNotUsedExtensions($aModules, $module); if ($module->hasExtendClass()) { $this->validateMetadataExtendSection($module); $aAddModules = $module->getExtensions(); $aModules = $this->_mergeModuleArrays($aModules, $aAddModules); } $aModules = $this->buildModuleChains($aModules); if ($aModulesDefault != $aModules) { $this->needCacheClear = true; $onlyInAfterFix = array_diff($aModules, $aModulesDefault); $onlyInBeforeFix = array_diff($aModulesDefault, $aModules); $this->output->writeLn("[INFO] fixing " . $module->getId()); foreach ($onlyInAfterFix as $core => $ext) { if ($oldChain = $onlyInBeforeFix[$core]) { $newExt = substr($ext, strlen($oldChain)); if (!$newExt) { //$newExt = substr($ext, strlen($oldChain)); $this->output->writeLn("[INFO] remove ext for $core"); $this->output->writeLn("[INFO] old: $oldChain"); $this->output->writeLn("[INFO] new: $ext"); //$this->_debugOutput->writeLn("[ERROR] extension chain is corrupted for this module"); //return; continue; } else { $this->output->writeLn("[INFO] append $core => ...$newExt"); } unset($onlyInBeforeFix[$core]); } else { $this->output->writeLn("[INFO] add $core => $ext"); } } foreach ($onlyInBeforeFix as $core => $ext) { $this->output->writeLn("[INFO] remove $core => $ext"); } $this->_saveToConfig('aModules', $aModules); } }
Add extension to module @param \OxidEsales\Eshop\Core\Module\Module $module
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, 'product_code' => $this->product_code, 'product_num' => $this->product_num, 'product_desc' => $this->product_desc, '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 getBillingAddressParamsStructure() { return [ 'first_name' => $this->billing_first_name, 'last_name' => $this->billing_last_name, 'address1' => $this->billing_address1, 'address2' => $this->billing_address2, 'zip_code' => $this->billing_zip_code, 'city' => $this->billing_city, 'state' => $this->billing_state, 'country' => $this->billing_country ]; }
Builds an array list with all Params @return array
public function parseResponse($response) { $this->responseRaw = $response; try { $parser = new \Genesis\Parser('xml'); $parser->skipRootNode(); $parser->parseDocument($response); $this->responseObj = $parser->getObject(); } catch (\Exception $e) { throw new \Genesis\Exceptions\InvalidResponse( $e->getMessage(), $e->getCode() ); } // Apply per-field transformations $this->transform([$this->responseObj]); if (isset($this->responseObj->status)) { $state = new Constants\Transaction\States($this->responseObj->status); if (!$state->isValid()) { throw new \Genesis\Exceptions\InvalidArgument( 'Unknown transaction status', isset($this->responseObj->code) ? $this->responseObj->code : 0 ); } if ($state->isError() && !$this->suppressReconciliationException()) { throw new \Genesis\Exceptions\ErrorAPI( $this->responseObj->message, isset($this->responseObj->code) ? $this->responseObj->code : 0 ); } } }
Parse Genesis response to stdClass and apply transformation to known fields @param string $response @throws \Genesis\Exceptions\ErrorAPI @throws \Genesis\Exceptions\InvalidArgument @throws \Genesis\Exceptions\InvalidResponse
public function isSuccessful() { $status = new Constants\Transaction\States( isset($this->responseObj->status) ? $this->responseObj->status : '' ); if ($status->isValid()) { return !$status->isError(); } return null; }
Check whether the request was successful Note: You should consult with the documentation which transaction responses have status available. @return bool | null (on missing status)
public function isPartiallyApproved() { if (isset($this->responseObj->partial_approval)) { return \Genesis\Utils\Common::stringToBoolean($this->responseObj->partial_approval); } return null; }
Check whether the transaction was partially approved @see Genesis_API_Documentation for more information @return bool | null (if inapplicable)
public function suppressReconciliationException() { $instances = [ new \Genesis\API\Request\NonFinancial\Reconcile\DateRange(), new \Genesis\API\Request\NonFinancial\Reconcile\Transaction(), new \Genesis\API\Request\WPF\Reconcile() ]; if (isset($this->requestCtx) && isset($this->responseObj->unique_id)) { foreach ($instances as $instance) { if ($this->requestCtx instanceof $instance) { return true; } } } return false; }
Suppress Reconciliation responses as their statuses reflect their transactions @return bool
public function getErrorDescription() { if (isset($this->responseObj->code) && !empty($this->responseObj->code)) { return Constants\Errors::getErrorDescription($this->responseObj->code); } if (isset($this->responseObj->response_code) && !empty($this->responseObj->response_code)) { return Constants\Errors::getIssuerResponseCode($this->responseObj->response_code); } return null; }
Try to fetch a description of the received Error Code @return string | null (if inapplicable)
public static function transform($obj) { if (is_array($obj) || is_object($obj)) { foreach ($obj as &$object) { if (isset($object->status)) { self::transformObject($object); } self::transform($object); } } }
Iterate and transform object @param mixed $obj
public static function transformObject(&$entry) { $filters = [ 'transformFilterAmounts', 'transformFilterTimestamp' ]; foreach ($filters as $filter) { if (method_exists(__CLASS__, $filter)) { $result = call_user_func([__CLASS__, $filter], $entry); if ($result) { $entry = $result; } } } }
Apply filters to an entry object @param \stdClass|\ArrayObject $entry @return mixed
public static function transformFilterAmounts($transaction) { $properties = [ 'amount', 'leftover_amount' ]; foreach ($properties as $property) { if (isset($transaction->{$property}) && isset($transaction->currency)) { $transaction->{$property} = \Genesis\Utils\Currency::exponentToAmount( $transaction->{$property}, $transaction->currency ); } } return $transaction; }
Get formatted response amounts (instead of ISO4217, return in float) @param \stdClass|\ArrayObject $transaction @return \stdClass|\ArrayObject $transaction
public static function transformFilterAmount($transaction) { // Process a single transaction if (isset($transaction->currency) && isset($transaction->amount)) { $transaction->amount = \Genesis\Utils\Currency::exponentToAmount( $transaction->amount, $transaction->currency ); } return $transaction; }
Get formatted amount (instead of ISO4217, return in float) @param \stdClass|\ArrayObject $transaction @return String | null (if amount/currency are unavailable)
public static function transformFilterTimestamp($transaction) { if (isset($transaction->timestamp)) { try { $transaction->timestamp = new \DateTime($transaction->timestamp); } catch (\Exception $e) { // Just log the attempt error_log($e->getMessage()); } } return $transaction; }
Get DateTime object from the timestamp inside the response @param \stdClass|\ArrayObject $transaction @return \DateTime|null (if invalid timestamp)
public function isValid() { $statusList = \Genesis\Utils\Common::getClassConstants(__CLASS__); return in_array(strtolower($this->status), $statusList); }
Check whether this is a valid (known) status @return bool
public static function getCertificateBundle() { $bundle = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Certificates' . DIRECTORY_SEPARATOR . 'ca-bundle.pem'; if (!file_exists($bundle)) { throw new \Genesis\Exceptions\InvalidArgument( 'CA Bundle file is missing or inaccessible' ); } return $bundle; }
Get the CA PEM @return string - Path to the Genesis CA Bundle; false otherwise @throws \Genesis\Exceptions\InvalidArgument
public static function getInterface($type) { if (array_key_exists($type, self::$interfaces)) { return self::$interfaces[$type]; } return false; }
Get configuration for an interface @param $type - type of the interface @return mixed - interface name or false if non-existing
public static function setInterface($interface, $value) { if (array_key_exists($interface, self::$interfaces)) { self::$interfaces[$interface] = $value; return true; } return false; }
Set an interface @param string $interface Name of interface (e.g. builder, network) @param string $value Value for the new interface (e.g. xml, curl) @return bool
public static function setEnvironment($environmentArg) { $environmentArg = strtolower(trim($environmentArg)); $aliases = [ \Genesis\API\Constants\Environments::STAGING => [ 'test', 'testing', 'staging', \Genesis\API\Constants\Environments::STAGING ], \Genesis\API\Constants\Environments::PRODUCTION => [ 'live', 'prod', 'production', \Genesis\API\Constants\Environments::PRODUCTION ] ]; foreach ($aliases as $environment => $endpointAlias) { foreach ($endpointAlias as $alias) { if (stripos($environmentArg, $alias) !== false) { return self::$vault['environment'] = $environment; } } } throw new \Genesis\Exceptions\InvalidArgument( 'Invalid Environment' ); }
Set Environment @param string $environmentArg @return string @throws \Genesis\Exceptions\InvalidArgument
public static function setEndpoint($endpointArg) { $endpointArg = strtolower(trim($endpointArg)); $aliases = [ \Genesis\API\Constants\Endpoints::EMERCHANTPAY => [ 'emp', 'emerchantpay', \Genesis\API\Constants\Endpoints::EMERCHANTPAY ], \Genesis\API\Constants\Endpoints::ECOMPROCESSING => [ 'ecp', 'ecomprocessing', 'e-comprocessing', \Genesis\API\Constants\Endpoints::ECOMPROCESSING ] ]; foreach ($aliases as $endpoint => $endpointAlias) { foreach ($endpointAlias as $alias) { if (stripos($endpointArg, $alias) !== false) { return self::$vault['endpoint'] = $endpoint; } } } throw new \Genesis\Exceptions\InvalidArgument( 'Invalid Endpoint' ); }
Set Genesis Endpoint @param string $endpointArg @return string @throws \Genesis\Exceptions\InvalidArgument
public static function getSubDomain($sub) { if (isset(self::$domains[$sub])) { return self::$domains[$sub][self::getEnvironment()]; } return null; }
Get a sub-domain host based on the environment @see self::$domains @param $sub @return string @throws Exceptions\EnvironmentNotSet
public static function loadSettings($iniFile) { if (!file_exists($iniFile)) { throw new \Genesis\Exceptions\InvalidArgument( 'The provided configuration file is invalid or inaccessible!' ); } $settings = parse_ini_file($iniFile, true); foreach ($settings['Genesis'] as $option => $value) { if (array_key_exists($option, self::$vault)) { self::$vault[$option] = $value; } } foreach ($settings['Interfaces'] as $option => $value) { if (array_key_exists($option, self::$interfaces)) { self::$interfaces[$option] = $value; } } }
Load settings from an ini File @param string $iniFile Path to an ini file containing the settings @throws \Genesis\Exceptions\InvalidArgument()
protected function setRequiredFields() { $requiredFields = [ 'transaction_id', 'return_success_url', 'return_failure_url', 'amount', 'currency', 'consumer_reference', 'national_id', 'customer_email', 'billing_country' ]; $this->requiredFields = \Genesis\Utils\Common::createArrayObject($requiredFields); $allowedBillingCountries = $this->getAllowedBillingCountries(); if (!empty($allowedBillingCountries)) { $requiredFieldValues = [ 'billing_country' => $allowedBillingCountries ]; $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, 'consumer_reference' => $this->consumer_reference, 'national_id' => $this->national_id, 'birth_date' => $this->birth_date, 'customer_email' => $this->customer_email, 'billing_address' => $this->getBillingAddressParamsStructure(), 'shipping_address' => $this->getShippingAddressParamsStructure() ]; }
Return additional request attributes @return array
public function setApiCtxData($apiContext) { $this->context->prepareRequestBody( [ 'body' => $apiContext->getDocument(), 'url' => $apiContext->getApiConfig('url'), 'type' => $apiContext->getApiConfig('type'), 'port' => $apiContext->getApiConfig('port'), 'protocol' => $apiContext->getApiConfig('protocol'), 'timeout' => \Genesis\Config::getNetworkTimeout(), 'ca_bundle' => \Genesis\Config::getCertificateBundle(), 'user_agent' => sprintf('Genesis PHP Client v%s', \Genesis\Config::getVersion()), 'user_login' => sprintf('%s:%s', \Genesis\Config::getUsername(), \Genesis\Config::getPassword()) ] ); }
Set Header/Body of the HTTP request @param \Genesis\API\Request $apiContext