code
stringlengths
52
7.75k
docs
stringlengths
1
5.85k
protected function unloadNailsPackage($sAsset, $sForceType) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': unset($this->aCss['NAILS-PACKAGE-' . $sAsset]); break; case 'JS': unset($this->aJs['NAILS-PACKAGE-' . $sAsset]); break; } }
Unloads a Nails package asset (as a relative url from NAILS_ASSETS_URL . 'packages/') @param string $sAsset The asset to unload @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
protected function unloadAppBower($sAsset, $sForceType) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': unset($this->aCss['APP-BOWER-' . $sAsset]); break; case 'JS': unset($this->aJs['APP-BOWER-' . $sAsset]); break; } }
Unloads a Bower asset from the app's bower_components directory @param string $sAsset The asset to unload @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
protected function unloadAppPackage($sAsset, $sForceType) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': unset($this->aCss['APP-PACKAGE-' . $sAsset]); break; case 'JS': unset($this->aJs['APP-PACKAGE-' . $sAsset]); break; } }
Unloads an App package asset (as a relative url from 'packages/') @param string $sAsset The asset to load @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
protected function unloadApp($sAsset, $sForceType) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': unset($this->aCss['APP-' . $sAsset]); break; case 'JS': unset($this->aJs['APP-' . $sAsset]); break; } }
Unloads an asset from the app's asset directory @param string $sAsset The asset to unload @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
protected function unloadModule($sAsset, $sForceType, $sModule) { $sType = $this->determineType($sAsset, $sForceType); switch ($sType) { case 'CSS': unset($this->aCss['MODULE-' . $sModule . '-' . $sAsset]); break; case 'JS': unset($this->aJs['MODULE-' . $sModule . '-' . $sAsset]); break; } }
Unloads an asset from the app's asset directory @param string $sAsset The asset to unload @param string $sForceType Force a particular type of asset (i.e. JS or CSS) @return void
public function inline($sScript = null, $sForceType = null, $sJsLocation = 'FOOTER') { if (!empty($sScript)) { $sJsLocation = strtoupper($sJsLocation); if ($sJsLocation != 'FOOTER' && $sJsLocation != 'HEADER') { throw new AssetException( '"' . $sJsLocation . '" is not a valid inline JS location value.', 1 ); } $sType = $this->determineType($sScript, $sForceType); switch ($sType) { case 'CSS-INLINE': case 'CSS': $this->aCssInline['INLINE-CSS-' . md5($sScript)] = $sScript; break; case 'JS-INLINE': case 'JS': if ($sJsLocation == 'FOOTER') { $this->aJsInlineFooter['INLINE-JS-' . md5($sScript)] = $sScript; } else { $this->aJsInlineHeader['INLINE-JS-' . md5($sScript)] = $sScript; } break; } } return $this; }
Loads an inline asset @param string $sScript The inline asset to load, wrap in script tags for JS, or style tags for CSS @param string $sForceType Force a particular type of asset (i.e. JS-INLINE or CSS-INLINE) @param string $sJsLocation Where the inline JS should appear, accepts FOOTER or HEADER @return object
public function clear() { $this->aCss = []; $this->aCssInline = []; $this->aJs = []; $this->aJsInlineHeader = []; $this->aJsInlineFooter = []; return $this; }
Clears all loaded assets @return object
public function getLoaded() { $oLoaded = new \stdClass(); $oLoaded->css = $this->aCss; $oLoaded->cssInline = $this->aCssInline; $oLoaded->js = $this->aJs; $oLoaded->jsInlineHeader = $this->aJsInlineHeader; $oLoaded->jsInlineFooter = $this->aJsInlineFooter; return $oLoaded; }
Returns an object containing all loaded assets, useful for debugging. @return stdClass
protected function addCacheBuster($sAsset) { if ($this->sCacheBuster) { $aParsedUrl = parse_url($sAsset); if (empty($aParsedUrl['query'])) { $sAsset .= '?'; } else { $sAsset .= '&'; } $sAsset .= 'revision=' . $this->sCacheBuster; } return $sAsset; }
Appends the cacheBuster string to the asset name, accounts for existing query strings @param string $sAsset The asset's url to append
protected function determineType($sAsset, $sForceType = null) { // Override if nessecary if (!empty($sForceType)) { return $sForceType; } // -------------------------------------------------------------------------- // Look for <style></style> if (preg_match('/^<style.*?>.*?<\/style>$/si', $sAsset)) { return 'CSS-INLINE'; } // -------------------------------------------------------------------------- // Look for <script></script> if (preg_match('/^<script.*?>.*?<\/script>$/si', $sAsset)) { return 'JS-INLINE'; } // -------------------------------------------------------------------------- // Look for .css if (substr($sAsset, strrpos($sAsset, '.')) == '.css') { return 'CSS'; } // -------------------------------------------------------------------------- // Look for .js if (substr($sAsset, strrpos($sAsset, '.')) == '.js') { return 'JS'; } }
Determines the type of asset being loaded @param string $sAsset The asset being loaded @param string $sForceType Forces a particular type (accepts values CSS, JS, CSS-INLINE or JS-INLINE) @return string
public function onAdminMatch(AdminMatchEvent $event): void { $pageLayoutTemplate = $event->getPageLayoutTemplate(); if ($pageLayoutTemplate !== null) { return; } $currentRequest = $this->requestStack->getCurrentRequest(); if (!$currentRequest instanceof Request) { return; } $siteAccess = $currentRequest->attributes->get('siteaccess')->name; if (!isset($this->groupsBySiteAccess[$siteAccess])) { return; } if (!in_array(EzPlatformAdminUiBundle::ADMIN_GROUP_NAME, $this->groupsBySiteAccess[$siteAccess], true)) { return; } $event->setPageLayoutTemplate($this->pageLayoutTemplate); }
Sets the pagelayout template for admin interface.
protected function resetProperties($aProperties) { foreach ($aProperties as $aProperty) { if (property_exists($this->oDb, $aProperty[0])) { $this->oDb->{$aProperty[0]} = $aProperty[1]; } } return $this; }
Safely resets properties @param array $aProperties The properties to reset; a multi-dimensional array where index 0 is the property and index 1 is the value. @return $this
protected function compile(array &$aClientConfig, array &$aRequestOptions) { parent::compile($aClientConfig, $aRequestOptions); $aRequestOptions['form_params'] = $this->aFormParams; }
Compile the request @param array $aClientConfig The config array for the HTTP Client @param array $aRequestOptions The options for the request
private function buildMainLocationParameters(ParameterBuilderInterface $builder, array $groups = []): void { $builder->add( 'only_main_locations', ParameterType\BooleanType::class, [ 'default_value' => true, 'groups' => $groups, ] ); }
Builds the parameters for filtering content with main location only.
private function getMainLocationFilterCriteria(ParameterCollectionInterface $parameterCollection): ?Criterion { if ($parameterCollection->getParameter('only_main_locations')->getValue() !== true) { return null; } return new Criterion\Location\IsMainLocation( Criterion\Location\IsMainLocation::MAIN ); }
Returns the criteria used to filter content with main location only.
private function loadLocation(): ?Location { if (!$this->context->has('ez_location_id')) { return null; } return $this->locationService->loadLocation( (int) $this->context->get('ez_location_id') ); }
Loads the location from the eZ Platform API by using the location ID stored in the context.
private function log(ContainerBuilder $container, string $message): void { if (Kernel::VERSION_ID < 30300) { $compiler = $container->getCompiler(); $compiler->addLogMessage($compiler->getLoggingFormatter()->format($this, $message)); return; } $container->log($this, $message); }
@deprecated Logs a message into the log. Acts as a BC layer to support Symfony 2.8.
private function buildQueryTypeParameters(ParameterBuilderInterface $builder, array $groups = []): void { $builder->add( 'query_type', ParameterType\ChoiceType::class, [ 'required' => true, 'options' => [ 'List' => 'list', 'Tree' => 'tree', ], 'groups' => $groups, ] ); }
Builds the parameters for selecting a query type.
private function getQueryTypeFilterCriteria(ParameterCollectionInterface $parameterCollection, Location $parentLocation): ?Criterion { if ($parameterCollection->getParameter('query_type')->getValue() !== 'list') { return null; } return new Criterion\Location\Depth( Criterion\Operator::EQ, $parentLocation->depth + 1 ); }
Returns the criteria used to filter content with one of the supported query types.
public static function convert(string $uuid) { // convert to 16 byte binary representation $bin = hex2bin(str_replace(['{', '-', '}'], '', $uuid)); // xor first half with second to give 8 bytes $xor = self::xor(...str_split($bin, 8)); // convert to a 64-bit signed integer return unpack('q', $xor)[1]; }
Convert a uuid to a 64-bit signed integer. This is a lossy conversion, performed by xoring the both halves. @param string $uuid @return int
public static function isPageSecure() { if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) === 'on') { // Page is being served through HTTPS return true; } elseif (isset($_SERVER['SERVER_NAME']) && isset($_SERVER['REQUEST_URI']) && SECURE_BASE_URL != BASE_URL) { // Not being served through HTTPS, but does the URL of the page begin // with SECURE_BASE_URL (when BASE_URL is different) $sUrl = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; return (bool) preg_match('#^' . SECURE_BASE_URL . '.*#', $sUrl); } // Unknown, assume not return false; }
Detects whether the current page is secure or not @return bool
public static function getDomainFromUrl($sUrl) { $sDomain = parse_url($sUrl, PHP_URL_HOST); $bits = explode('.', $sDomain); $idz = count($bits); $idz -= 3; if (!isset($bits[($idz + 2)])) { $aOut = false; } elseif (strlen($bits[($idz + 2)]) == 2 && isset($bits[($idz + 2)])) { $aOut = [ !empty($bits[$idz]) ? $bits[$idz] : false, !empty($bits[$idz + 1]) ? $bits[$idz + 1] : false, !empty($bits[$idz + 2]) ? $bits[$idz + 2] : false, ]; $aOut = implode('.', array_filter($aOut)); } elseif (strlen($bits[($idz + 2)]) == 0) { $aOut = [ !empty($bits[$idz]) ? $bits[$idz] : false, !empty($bits[$idz + 1]) ? $bits[$idz + 1] : false, ]; $aOut = implode('.', array_filter($aOut)); } elseif (isset($bits[($idz + 1)])) { $aOut = [ !empty($bits[$idz + 1]) ? $bits[$idz + 1] : false, !empty($bits[$idz + 2]) ? $bits[$idz + 2] : false, ]; $aOut = implode('.', array_filter($aOut)); } else { $aOut = false; } return $aOut; }
Attempts to get the top level part of a URL (i.e example.tld from sub.domains.example.tld). Hat tip: http://uk1.php.net/parse_url#104874 BUG: 2 character TLD's break this @param string $sUrl The URL to analyse @return mixed string on success, false on failure @todo: Try and fix this bug
public static function getRelativePath($sFrom, $sTo) { $aFrom = explode('/', $sFrom); $aTo = explode('/', $sTo); $aRelPath = $aTo; foreach ($aFrom as $iDepth => $sDir) { // Find first non-matching dir if ($sDir === $aTo[$iDepth]) { // Ignore this directory array_shift($aRelPath); } else { // Get number of remaining dirs to $aFrom $remaining = count($aFrom) - $iDepth; if ($remaining > 1) { // add traversals up to first matching dir $padLength = (count($aRelPath) + $remaining - 1) * -1; $aRelPath = array_pad($aRelPath, $padLength, '..'); break; } else { $aRelPath[0] = './' . $aRelPath[0]; } } } return implode('/', $aRelPath); }
Fetches the relative path between two directories Hat tip: Thanks to Gordon for this one; http://stackoverflow.com/a/2638272/789224 @param string $sFrom Path 1 @param string $sTo Path 2 @return string
public static function showError($sMessage = '', $sSubject = '', $iStatusCode = 500) { $oError =& load_class('Exceptions', 'core'); $oError->show_error($sSubject, $sMessage, $iStatusCode, $iStatusCode); }
Throw an error @param string $sMessage The error message @param string $sSubject The error subject @param int $iStatusCode The status code
public function getAsString(): string { return implode( '_', array_filter([ (string) $this->getLanguage(), (string) $this->getRegion(), (string) $this->getScript(), ]) ); }
Compute the string representation of the locale @return string
public function write($mData, string $sKey = null): Item { // Generate a key if one isn't explicitly specified if (is_null($sKey)) { $sKey = md5(microtime(true)); } $sPath = $this->prepKey($sKey); file_put_contents($sPath, $mData); return $this->newItem($sKey); }
Writes to the cache @param mixed $mData The data to write @param string|null $sKey The key of the item @return Item @throws FactoryException
public function read(string $sKey): ?Item { return $this->exists($sKey) ? $this->newItem($sKey) : null; }
Reads a file from the cache @param string $sKey The key of the item @return Item|null @throws FactoryException
public function delete(string $sKey): bool { if ($this->exists($sKey)) { return @unlink($this->prepKey($sKey)); } else { return false; } }
Delete a cache item @param string $sKey The key of the item @return bool
protected function newItem(string $sKey): Item { $oObj = (object) [ 'sKey' => $sKey, 'sPath' => $this->prepKey($sKey), ]; // When testing the Factory isn't available if (defined('PHPUNIT_NAILS_COMMON_TEST_SUITE')) { $oItem = new Item($oObj); } else { /** @var Item $oItem */ $oItem = Factory::resource('FileCacheItem', null, $oObj); } return $oItem; }
Configures a new item object @param string $sKey The item's key @return Item @throws FactoryException
public static function readFileChunked($sFilename, $iChunkSize = 1048576) { $iBytesRead = 0; $rHandle = fopen($sFilename, 'rb'); if ($rHandle === false) { return false; } while (!feof($rHandle)) { $sBuffer = fread($rHandle, $iChunkSize); $iBytesRead += strlen($sBuffer); echo $sBuffer; } $bStatus = fclose($rHandle); return $bStatus ? $iBytesRead : false; }
Outputs a file in bytesized chunks. http://teddy.fr/2007/11/28/how-serve-big-files-through-php/ @param string $sFilename The file to output @param integer $iChunkSize The chunk size, in bytes @return bool|int
public static function fileExistsCS($sFilename) { if (array_key_exists($sFilename, static::$aFileExistsCache)) { return static::$aFileExistsCache[$sFilename]; } $sDirectory = dirname($sFilename); $aFiles = array_map(function ($sFile) { return basename($sFile); }, glob($sDirectory . DIRECTORY_SEPARATOR . '*', GLOB_NOSORT)); if (in_array(basename($sFilename), $aFiles)) { // Test if the directory exists $bResult = static::isDirCS($sDirectory); } else { $bResult = false; } static::$aFileExistsCache[$sFilename] = $bResult; return $bResult; }
A case-sensitive file_exists @param string $sFilename The file to test @return bool
public static function isDirCS($sDir) { if (array_key_exists($sDir, static::$aIsDirCache)) { return static::$aIsDirCache[$sDir]; } $aDirBits = explode(DIRECTORY_SEPARATOR, $sDir); $bResult = true; while (count($aDirBits) > 1) { $sDirectory = array_pop($aDirBits); $sDirectoryPath = implode(DIRECTORY_SEPARATOR, $aDirBits); $aDirectories = array_map(function ($sDirectory) { return basename($sDirectory); }, glob($sDirectoryPath . DIRECTORY_SEPARATOR . '*', GLOB_NOSORT | GLOB_ONLYDIR)); if (!in_array($sDirectory, $aDirectories)) { $bResult = false; break; } } static::$aIsDirCache[$sDir] = $bResult; return $bResult; }
A case-sensitive is_dir @param string $sDir The directory to trst @return bool
private function getObjectStates(Options $options): array { $allObjectStates = []; $groups = $this->objectStateService->loadObjectStateGroups(); $configuredGroups = $options['states']; foreach ($groups as $group) { $configuredGroups += [$group->identifier => true]; if ($configuredGroups[$group->identifier] === false) { continue; } $objectStates = $this->objectStateService->loadObjectStates($group); foreach ($objectStates as $objectState) { if ( is_array($configuredGroups[$group->identifier]) && !in_array($objectState->identifier, $configuredGroups[$group->identifier], true) ) { continue; } $groupName = $group->getName() ?? $group->identifier; $stateName = $objectState->getName() ?? $objectState->identifier; $allObjectStates[$groupName][$stateName] = $group->identifier . '|' . $objectState->identifier; } } return $allObjectStates; }
Returns the allowed content states from eZ Platform.
protected function setCache($sKey, $mValue) { if (!static::$CACHING_ENABLED) { return false; } elseif (empty($sKey)) { return false; } // -------------------------------------------------------------------------- // Test we're not near memory limit if (function_exists('ini_get')) { $sMemoryLimit = ini_get('memory_limit_cat'); if ($sMemoryLimit !== false) { $sLastChar = strtoupper($sMemoryLimit[strlen($sMemoryLimit) - 1]); switch ($sLastChar) { // The 'G' modifier is available since PHP 5.1.0 case 'G': $sMemoryLimit *= 1024; /* falls through */ case 'M': $sMemoryLimit *= 1024; /* falls through */ case 'K': $sMemoryLimit *= 1024; } $fPercentage = (memory_get_usage() / $sMemoryLimit) * 100; if ($fPercentage > 90) { $this->clearCache(); } } } // -------------------------------------------------------------------------- // Prep the key, the key should have a prefix unique to this model $iCacheIndex = $this->getCache($sKey, false); if (!is_null($iCacheIndex)) { $this->aCache[$iCacheIndex]->value = $mValue; } else { $sCacheKey = $this->getCachePrefix() . $sKey; $this->aCache[] = (object) [ 'key' => [$sCacheKey], 'value' => $mValue, ]; } // -------------------------------------------------------------------------- return true; }
Saves an item to the cache @param string $sKey The cache key @param mixed $mValue The data to be cached @return bool
protected function setCacheAlias($sAliasKey, $sOriginalKey) { if (!static::$CACHING_ENABLED) { return false; } elseif (empty($sAliasKey) || empty($sOriginalKey)) { return false; } $sOriginalCacheKey = $this->getCache($sOriginalKey, false); if (is_null($sOriginalCacheKey)) { return false; } $this->aCache[$sOriginalCacheKey]->key[] = $this->getCachePrefix() . $sAliasKey; $this->aCache[$sOriginalCacheKey]->key = array_unique($this->aCache[$sOriginalCacheKey]->key); // -------------------------------------------------------------------------- return true; }
Adds an additional key to an existing cache item @param string $sAliasKey The alias to add @param string $sOriginalKey The original cache key @return bool
protected function getCache($sKey, $bReturnValue = true) { if (!static::$CACHING_ENABLED) { return false; } elseif (empty($sKey)) { return false; } $sCacheKey = $this->getCachePrefix() . $sKey; foreach ($this->aCache as $iIndex => $oCacheItem) { if (in_array($sCacheKey, $oCacheItem->key)) { return $bReturnValue ? $oCacheItem->value : $iIndex; } } return null; }
Fetches an item from the cache @param string $sKey The cache key @param boolean $bReturnValue Whether to return the value, or the index in the cache array @return mixed
protected function unsetCache($sKey) { if (!static::$CACHING_ENABLED) { return false; } elseif (empty($sKey)) { return false; } $iCacheIndex = $this->getCache($sKey, false); if (is_null($iCacheIndex)) { return false; } unset($this->aCache[$iCacheIndex]); return true; }
Deletes an item from the cache @param string $sKey The cache key @return boolean
protected function unsetCachePrefix($sPrefix) { if (!static::$CACHING_ENABLED) { return false; } elseif (empty($sPrefix)) { return false; } $sPrefix = $this->getCachePrefix() . $sPrefix; // -------------------------------------------------------------------------- // Prep the key, the key should have a prefix unique to this model $aKeysToUnset = []; foreach ($this->aCache as $sCacheKey => $oCacheItem) { foreach ($oCacheItem->key as $sKey) { if (preg_match('/^' . preg_quote($sPrefix, '/') . '/', $sKey)) { $aKeysToUnset[] = $sCacheKey; } } } foreach ($aKeysToUnset as $iKey) { unset($this->aCache[$iKey]); } // -------------------------------------------------------------------------- return true; }
Deletes item from the cache which match a particular prefix @param string $sPrefix The key prefix @return bool
public static function delete(string $sDir): void { if (is_dir($sDir)) { $oFiles = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $sDir, RecursiveDirectoryIterator::SKIP_DOTS ), RecursiveIteratorIterator::CHILD_FIRST ); foreach ($oFiles as $oFile) { $sfunction = $oFile->isDir() ? 'rmdir' : 'unlink'; $sfunction($oFile->getRealPath()); } rmdir($sDir); } }
Recursively deletes a directory @param string $sDir the directory to delete
public static function tempdir(string $sDir = null, string $sPrefix = 'tmp_', int $iMode = 0700, int $iMaxAttempts = 1000) { // Use the system temp dir by default if (is_null($sDir)) { $sDir = sys_get_temp_dir(); } // Trim trailing slashes from $sDir $sDir = rtrim($sDir, DIRECTORY_SEPARATOR); /** * If we don't have permission to create a directory, fail, otherwise we will * be stuck in an endless loop */ if (!is_dir($sDir)) { throw new DirectoryDoesNotExistException( '"' . $sDir . '" does not exist' ); } elseif (!is_writable($sDir)) { throw new DirectoryIsNotWritableException( '"' . $sDir . '" is not writable' ); } // Make sure characters in prefix are safe if (strpbrk($sPrefix, '\\/:*?"<>|') !== false) { throw new DirectoryNameException( '"' . $sDir . '" name contains invalid characters' ); } /** * Attempt to create a random directory until it works. Abort if we reach * $iMaxAttempts. Something screwy could be happening with the filesystem * and our loop could otherwise become endless. */ $iAttempts = 0; do { $sPath = sprintf('%s%s%s%s', $sDir, DIRECTORY_SEPARATOR, $sPrefix, mt_rand(100000, mt_getrandmax())); } while ( !mkdir($sPath, $iMode) && $iAttempts++ < $iMaxAttempts ); return $sPath . DIRECTORY_SEPARATOR; }
Creates a temporary directory hat-tip: https://stackoverflow.com/a/30010928/789224 @param string|null $sDir Where to create the temporary directory (uses system temp directory by default) @param string $sPrefix A prefix to use @param int $iMode The mode of the created directory @param int $iMaxAttempts The maximum number of attempts @return string @throws DirectoryDoesNotExistException @throws DirectoryIsNotWritableException @throws DirectoryNameException
public function execute() { $oModel = Factory::model(static::CONFIG_MODEL_NAME, static::CONFIG_MODEL_PROVIDER); /** @var Locale $oLocale */ $oLocale = Factory::service('Locale'); $oDefaultLocale = $oLocale->getDefautLocale(); $aFieldsDescribed = $oModel->describeFields(); $aFields = []; foreach ($aFieldsDescribed as $oField) { if (!in_array($oField->key, static::CONFIG_IGNORE_FIELDS)) { $aFields[] = $oField; } } for ($i = 0; $i < static::CONFIG_NUM_PER_SEED; $i++) { try { $aData = $this->generate($aFields); if (classUses($oModel, Localised::class)) { if (!$oModel->create($aData, false, $oDefaultLocale)) { throw new NailsException('Failed to create item. ' . $oModel->lastError()); } } elseif (!$oModel->create($aData)) { throw new NailsException('Failed to create item. ' . $oModel->lastError()); } } catch (\Exception $e) { echo "\nSEED ERROR: " . $e->getMessage(); } } }
Execute the seed @return void
protected function generate($aFields) { $aOut = []; foreach ($aFields as $oField) { switch ($oField->type) { case 'textarea': $mValue = $this->loremParagraph(); break; case 'wysiwyg': $mValue = $this->loremHtml(); break; case 'number': $mValue = $this->randomInteger(); break; case 'boolean': $mValue = $this->randomBool(); break; case 'datetime': $mValue = $this->randomDateTime(); break; case 'date': $mValue = $this->randomDateTime(null, null, 'Y-m-d'); break; case 'time': $mValue = $this->randomDateTime(null, null, 'H:i:s'); break; case 'dropdown': $mValue = $this->randomItem(array_keys($oField->options)); break; default: $mValue = $this->loremWord(3); break; } $aOut[$oField->key] = $mValue; } // Special Cases, model dependant $oModel = Factory::model(static::CONFIG_MODEL_NAME, static::CONFIG_MODEL_PROVIDER); // Slugs // If these are being automatically generated then let the model do the hard work if ($oModel->isAutoSetSlugs()) { $sColumn = $oModel->getColumn('slug'); unset($aOut[$sColumn]); } // Tokens // If these are being automatically generated then let the model do the hard work if ($oModel->isAutoSetTokens()) { $sColumn = $oModel->getColumn('token'); unset($aOut[$sColumn]); } return $aOut; }
Generate a new item @param array $aFields The fields to generate @return array
public function line($sLine = '') { // Is dummy mode enabled? If it is then don't do anything. if ($this->bDummy) { return; } // -------------------------------------------------------------------------- $sLogPath = $this->oLog->dir . $this->oLog->file; $oDate = Factory::factory('DateTime'); // -------------------------------------------------------------------------- // If the log file doesn't exist (or we haven't checked already), attempt to create it if (!$this->oLog->exists) { if (!file_exists($sLogPath)) { // Check directory is there $sDir = dirname($sLogPath); if (!is_dir($sDir)) { // Create structure mkdir($sDir, 0750, true); } // -------------------------------------------------------------------------- $sFirstLine = '<?php die(\'Unauthorised\'); ?>' . "\n\n"; if (write_file($sLogPath, $sFirstLine)) { $this->oLog->exists = true; } else { $this->oLog->exists = false; } } else { $this->oLog->exists = true; } } // -------------------------------------------------------------------------- if ($this->oLog->exists) { if (empty($sLine)) { write_file($sLogPath, "\n", 'a'); } else { write_file($sLogPath, 'INFO - ' . $oDate->format('Y-m-d H:i:s') . ' --> ' . trim($sLine) . "\n", 'a'); } } }
Writes a line to the log @param string $sLine The line to write @return void
public function setFile($sFile = '') { // Reset the log exists var so that line() checks again $this->oLog->exists = false; // -------------------------------------------------------------------------- if (!empty($sFile)) { $this->oLog->file = $sFile; } else { $oDate = Factory::factory('DateTime'); $this->oLog->file = 'log-' . $oDate->format('Y-m-d') . '.php'; } }
Set the filename which is being written to @param string $sFile The file to write to
public function setDir($sDir = '') { // Reset the log exists var so that line() checks again $this->oLog->exists = false; // -------------------------------------------------------------------------- if (!empty($sDir) && substr($sDir, 0, 1) === '/') { $this->oLog->dir = $sDir; } elseif (!empty($sDir)) { $this->oLog->dir = DEPLOY_LOG_DIR . $sDir; } else { $this->oLog->dir = DEPLOY_LOG_DIR; } }
Set the log directory which is being written to @param string $sDir The directory to write to
public function connect($sDbHost = '', $sDbUser = '', $sDbPass = '', $sDbName = '') { // Close the connection if one is open if (!is_null($this->oDb)) { $this->oDb = null; } $sDbHost = !empty($sDbHost) ? $sDbHost : (defined('DEPLOY_DB_HOST') ? DEPLOY_DB_HOST : ''); $sDbUser = !empty($sDbUser) ? $sDbUser : (defined('DEPLOY_DB_USERNAME') ? DEPLOY_DB_USERNAME : ''); $sDbPass = !empty($sDbPass) ? $sDbPass : (defined('DEPLOY_DB_PASSWORD') ? DEPLOY_DB_PASSWORD : ''); $sDbName = !empty($sDbName) ? $sDbName : (defined('DEPLOY_DB_DATABASE') ? DEPLOY_DB_DATABASE : ''); try { $this->oDb = new \PDO( 'mysql:host=' . $sDbHost . ';dbname=' . $sDbName . ';charset=utf8', $sDbUser, $sDbPass ); $this->oDb->exec('set names utf8'); $this->oDb->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); } catch (\Exception $e) { throw new ConnectionException( sprintf(self::ERR_MSG_CONNECTION_FAILED, $e->getCode(), $e->getMessage()), self::ERR_NUM_CONNECTION_FAILED ); } }
Connect to the database @param string $sDbHost The database host @param string $sDbUser The database user @param string $sDbPass The database password @param string $sDbName The database @return void @throws ConnectionException
public function query($sQuery) { if (empty($this->oDb)) { $this->connect(); } return $this->oDb->query($sQuery); }
Execute a query @param string $sQuery The query to execute @return \PDOStatement
public function prepare($sQuery) { if (empty($this->oDb)) { $this->connect(); } return $this->oDb->prepare($sQuery); }
Prepares an SQL query @param string $sQuery The query to prepare @return \PDOStatement
public function escape($sString) { if (empty($this->oDb)) { $this->connect(); } return $this->oDb->quote($sString); }
Escapes a string to make it query safe @param string $sString The string to escape @return string
public function transactionStart() { if (empty($this->oDb)) { $this->connect(); } try { $this->oDb->beginTransaction(); $this->transactionRunning = true; return true; } catch (\Exception $e) { throw new TransactionException($e->getMessage(), $e->getCode()); } }
Starts a DB transaction @return boolean @throws TransactionException
public function transactionCommit() { if (empty($this->oDb)) { $this->connect(); } try { $this->oDb->commit(); $this->transactionRunning = false; return true; } catch (\Exception $e) { throw new TransactionException($e->getMessage(), $e->getCode()); } }
Commits a DB transaction @return boolean @throws TransactionException
public function transactionRollback() { if (empty($this->oDb)) { $this->connect(); } try { $this->oDb->rollback(); $this->transactionRunning = false; return true; } catch (\Exception $e) { throw new TransactionException($e->getMessage(), $e->getCode()); } }
Rollsback a DB transaction @return boolean @throws TransactionException
public static function replaceLastOccurrence($sString, $sReplace, $sSubject) { $iPos = strrpos($sSubject, $sString); if ($iPos !== false) { $sSubject = substr_replace($sSubject, $sReplace, $iPos, strlen($sString)); } return $sSubject; }
Replace the last occurrence of a string within a string with a string @param string $sString The substring to replace @param string $sReplace The string to replace the substring with @param string $sSubject The string to search @return string
public static function underscoreToCamelcase($sString, $bLowerFirst = true) { $sString = explode('_', $sString); $sString = array_map('strtolower', $sString); $sString = array_map('ucfirst', $sString); $sString = implode($sString); $sString = $bLowerFirst ? lcfirst($sString) : $sString; return $sString; }
Transforms a string with underscores into a camelcased string @param string $sString The string to transform @param boolean $bLowerFirst Whether or not to lowercase the first letter of the transformed string or not @return string
public static function generateToken($sMask = null, $aChars = [], $aDigits = []) { $sMask = empty($sMask) ? 'AAAA-AAAA-AAAA-AAAA-AAAA-AAAA' : $sMask; $aChars = empty($aChars) ? str_split('abcdefghijklmnopqrstuvwxyz') : $aChars; $aDigits = empty($aDigits) ? str_split('0123456789') : $aDigits; $aMask = str_split(strtoupper($sMask)); $aOut = []; $iMaskLen = count($aMask); for ($i = 0; $i < $iMaskLen; $i++) { if ($aMask[$i] === 'A') { if (mt_rand(0, 1)) { $aOut[] = random_element($aChars); } else { $aOut[] = random_element($aDigits); } } else { if ($aMask[$i] === 'C') { $aOut[] = random_element($aChars); } else { if ($aMask[$i] === 'D') { $aOut[] = random_element($aDigits); } else { $aOut[] = $aMask[$i]; } } } } return implode($aOut); }
Generates a token string using a specific mask @param string $sMask The mask to use; A = Any, C = Character, D = digit, S = Symbol @param array $aChars The array of characters to use @param array $aDigits The array of digits to use @return string
public static function prosaicList(array $aArray, $sSeparator = ', ', $sConjunctive = ' and ', $bOxfordComma = true) { $iCount = count($aArray); if ($iCount <= 1) { return implode('', $aArray); } elseif ($iCount == 2) { return implode($sConjunctive, $aArray); } else { $aOut = []; for ($i = 0; $i < $iCount; $i++) { $sTemp = $aArray[$i]; if ($i == ($iCount - 2) && $bOxfordComma) { // Second last item, and using Oxford comma $sTemp .= $sSeparator . $sConjunctive; } elseif ($i == ($iCount - 2) && !$bOxfordComma) { $sTemp .= $sConjunctive; } elseif ($i != ($iCount - 1)) { $sTemp .= $sSeparator; } $aOut[] = $sTemp; } return implode('', $aOut); } }
Takes an array of strings and returns as a comma separated string using a terminal conjunctive, optionally using an Oxford Comma. @param array $aArray The array to implode @param string $sSeparator The string to use to separate the strings @param string $sConjunctive The conjunctive to use @param bool $bOxfordComma Whether to use an Oxford comma, or not. @return string
public function getInstance($sSlug) { if (isset($this->aInstances[$sSlug])) { return $this->aInstances[$sSlug]; } else { foreach ($this->aComponents as $oDriverConfig) { if ($sSlug == $oDriverConfig->slug) { $oDriver = $oDriverConfig; break; } } if (!empty($oDriver)) { $this->aInstances[$oDriver->slug] = Components::getDriverInstance($oDriver); // Apply driver configurations $aSettings = [ 'sSlug' => $oDriver->slug, ]; if (!empty($oDriver->data->settings)) { $aSettings = array_merge( $aSettings, $this->extractComponentSettings( $oDriver->data->settings, $oDriver->slug ) ); } $this->aInstances[$sSlug]->setConfig($aSettings); return $this->aInstances[$sSlug]; } } return null; }
Return an instance of the driver. @param string $sSlug The driver's slug @return mixed
public function getContentName($contentId): string { try { $versionInfo = $this->loadVersionInfo($contentId); return $versionInfo->getName() ?? ''; } catch (Throwable $t) { return ''; } }
Returns the content name. @param int|string $contentId @return string
public function getLocationPath($locationId): array { try { $location = $this->loadLocation($locationId); $locationPath = $location->path; array_shift($locationPath); $translatedNames = []; foreach ($locationPath as $locationPathId) { $locationInPath = $this->loadLocation($locationPathId); $translatedNames[] = $this->getContentName($locationInPath->contentInfo->id); } return $translatedNames; } catch (Throwable $t) { return []; } }
Returns the location path. @param int|string $locationId @return string[]
public function getContentTypeName(string $identifier): string { try { $contentType = $this->loadContentType($identifier); return $contentType->getName() ?? ''; } catch (Throwable $t) { return ''; } }
Returns the content type name.
private function loadVersionInfo($contentId): VersionInfo { return $this->repository->sudo( static function (Repository $repository) use ($contentId): VersionInfo { return $repository->getContentService()->loadVersionInfoById($contentId); } ); }
Loads the version info for provided content ID. @param int|string $contentId @return \eZ\Publish\API\Repository\Values\Content\VersionInfo
private function loadContentType(string $identifier): ContentType { return $this->repository->sudo( static function (Repository $repository) use ($identifier): ContentType { return $repository->getContentTypeService()->loadContentTypeByIdentifier($identifier); } ); }
Loads the content type for provided identifier.
public static function get() { if (empty(static::$sEnvironment)) { if (!empty($_ENV['ENVIRONMENT'])) { static::set($_ENV['ENVIRONMENT']); } else { static::set(ENVIRONMENT); } try { $oInput = Factory::service('Input'); if (static::not(static::ENV_PROD) && $oInput->header(Testing::TEST_HEADER_NAME) === Testing::TEST_HEADER_VALUE) { static::set(static::ENV_HTTP_TEST); // @todo (Pablo - 2018-11-21) - Consider halting execution if on prod and a test header is received } } catch (\Exception $e) { /** * In the circumstance the environment is checked before the factory * is loaded then this block will fail. Rather than consider this an * error, simply swallow it quietly as it's probably intentional and * can be considered a non-testing situation. */ } } return static::$sEnvironment; }
Get the current environment @return string
public static function is($mEnvironment) { if (is_array($mEnvironment)) { return array_search(static::get(), array_map('strtoupper', $mEnvironment)) !== false; } else { return static::get() === strtoupper($mEnvironment); } }
Returns whether the environment is the supplied environment @param array|string $mEnvironment The environment(s) to query @return boolean
public function filter_uri(&$str) { try { parent::filter_uri($str); } catch (Exception $e) { /** * If illegal characters are found, and in production halt with error. This * runs very early on so we can't use a 404 or similar. We don't want this * to bubble to error handlers as it'll just pollute the logs. On non-production * environments allow the exception to bubble so it's more obvious to the dev. * * This is obviously a fragile check :( */ $sMessage = 'The URI you submitted has disallowed characters.'; if (Environment::is(Environment::ENV_PROD) && $e->getMessage() === $sMessage) { ErrorHandler::halt($sMessage, '', HttpCodes::STATUS_NOT_FOUND); } else { throw $e; } } }
Filters the URI and prevents illegal characters @param string $str THE URI @throws Exception
public function query($sQuery) { $sQuery = $this->replaceConstants($sQuery); $this->iQueryCount++; $this->sLastQuery = $sQuery; return $this->oDb->query($sQuery); }
Execute a DB query @param string $sQuery The query to execute @return \PDOStatement
public function prepare($sQuery) { $sQuery = $this->replaceConstants($sQuery); $this->iQueryCount++; $this->sLastQuery = $sQuery; return $this->oDb->prepare($sQuery); }
Prepare a DB query @param string $sQuery The query to prepare @return \PDOStatement
protected function replaceConstants($sString) { return preg_replace_callback( '/{{(.+?)}}/', function ($aMatches) { if (defined($aMatches[1])) { return constant($aMatches[1]); } return $aMatches[0]; }, $sString ); }
Replaces {{CONSTANT}} with the value of constant, CONSTANT @param string $sString The string to search on @return string
public function execute(): void { if ($this->oLocaleService::ENABLE_SNIFF_URL) { /** * Manipulate the URL * Remove the /{language} element from the URL once the Locale service has initialsied * so that this doesn't affect normal routing of the application. * * @todo (Pablo - 2019-03-08) - Check if this breaks on systems where the app isn't at the root of the domain */ $oUrl = $this->parseUrl($this->getUrl()); // If the detected language is the same as the default language then remove it form the URL and repeat if ($oUrl->language === $this->oLocaleService::DEFAULT_LANGUAGE) { header( 'Location: /' . $oUrl->url, true, HttpCodes::STATUS_TEMPORARY_REDIRECT ); exit(0); } // Save the original URL, should it be needed $_SERVER['ORIGINAL_URL'] = $this->getUrl(); // Update the $_SERVER values so the rest of the system continues as normal if (array_key_exists('PATH_INFO', $_SERVER)) { $_SERVER['PATH_INFO'] = '/' . $oUrl->path; } if (array_key_exists('REQUEST_URI', $_SERVER)) { $_SERVER['REQUEST_URI'] = '/' . $oUrl->url; } } }
--------------------------------------------------------------------------
protected function parseUrl(string $sUrl): \stdClass { preg_match($this->oLocaleService->getUrlRegex(), $sUrl, $aMatches); $sLanguage = !empty($aMatches[1]) ? $aMatches[1] : ''; $sRequestUrl = !empty($aMatches[3]) ? $aMatches[3] : ''; $aRequestUrl = parse_url($sRequestUrl); $sPath = ltrim(!empty($aRequestUrl['path']) ? $aRequestUrl['path'] : '', '/'); $sQuery = !empty($aRequestUrl['query']) ? $aRequestUrl['query'] : ''; return (object) [ 'language' => !empty($aMatches[1]) ? $aMatches[1] : null, 'path' => $sPath, 'query' => $sQuery, 'url' => $sPath . ($sQuery ? '?' . $sQuery : ''), ]; }
Parse the URL for supported languages @param string $sUrl The URL to parse @return \stdClass
public function getData($sKey = null) { if (is_null($sKey)) { return $this->aData; } elseif (array_key_exists($sKey, $this->aData)) { return $this->aData[$sKey]; } else { return null; } }
Get an item from the view data array @param string $sKey The key to retrieve @return array|mixed|null
public function setData($mKey, $mValue = null) { if (is_array($mKey)) { foreach ($mKey as $sKey => $mSubValue) { $this->setData($sKey, $mSubValue); } } elseif (is_string($mKey) || is_numeric($mKey)) { $this->aData[$mKey] = $mValue; } else { throw new NailsException('Key must be a string or a numeric'); } return $this; }
Add an item to the view data array, or update an existing item @param string|array $mKey The key, or keys (in a key value pair), to set @param mixed $mValue The value to set @throws \Exception @returns $this
public function unsetData($mKey) { if (is_array($mKey)) { foreach ($mKey as $sSubKey) { $this->unsetData($sSubKey); } } else { unset($this->aData[$mKey]); } return $this; }
Unset an item from the view data array @param string|array $mKey The key, or keys, to unset @return $this
public function load($mView, $aData = [], $bReturn = false) { if (is_array($mView)) { $sOut = ''; foreach ($mView as $sView) { if ($bReturn) { $sOut .= $this->load($sView, $aData, $bReturn); } else { $this->load($sView, $aData, $bReturn); } } return $bReturn ? $sOut : $this; } elseif (is_string($mView)) { $aData = array_merge($this->getData(), (array) $aData); ob_start(); try { $sResolvedPath = $this->resolvePath($mView); } catch (ViewNotFoundException $e) { @ob_end_clean(); throw $e; } extract($aData); include $sResolvedPath; if (!array_key_exists($sResolvedPath, $this->aLoadedViews)) { $this->aLoadedViews[$sResolvedPath] = 0; } $this->aLoadedViews[$sResolvedPath]++; if ($bReturn) { $sBuffer = ob_get_contents(); @ob_end_clean(); return $sBuffer; } elseif (ob_get_level() > $this->iBufferLevel + 1) { ob_end_flush(); } else { $oOutput = Factory::service('Output'); $oOutput->append_output(ob_get_contents()); @ob_end_clean(); } return $this; } else { return $this; } }
Loads a view @param string|array $mView The view to load, or an array of views to load @param array $aData Data to pass to the view(s) @param boolean $bReturn Whether to return the view(s) or not @return mixed
public function isLoaded(string $sView): bool { try { return array_key_exists( $this->resolvePath($sView), $this->aLoadedViews ); } catch (ViewNotFoundException $e) { return false; } }
Determines if a view has previous been loaded or not @param string $sView The view to checl @return bool
protected function execute(InputInterface $oInput, OutputInterface $oOutput) { parent::execute($oInput, $oOutput); return $this->executeInstaller(); }
Executes the app @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
function defineAppVars() { $vars = []; $vars[] = '// App Constants'; $vars[] = [ 'key' => 'APP_NAME', 'label' => 'App Name', 'value' => defined('APP_NAME') ? APP_NAME : 'Untitled', ]; $vars[] = [ 'key' => 'APP_DEFAULT_TIMEZONE', 'label' => 'App Timezone', 'value' => defined('APP_DEFAULT_TIMEZONE') ? APP_DEFAULT_TIMEZONE : date_default_timezone_get(), 'validate' => function ($sInput) { return in_array($sInput, timezone_identifiers_list()); }, ]; $vars[] = [ 'key' => 'APP__KEY', 'label' => 'App Key', 'value' => defined('APP_PRIVATE_KEY') && !empty(APP_PRIVATE_KEY) ? APP_PRIVATE_KEY : md5(rand(0, 1000) . microtime(true)), ]; $vars[] = [ 'key' => 'APP_DEVELOPER_EMAIL', 'label' => 'Developer Email', 'value' => defined('APP_DEVELOPER_EMAIL') ? APP_DEVELOPER_EMAIL : '', ]; $vars[] = [ 'key' => 'APP_DB_PREFIX', 'label' => 'Prefix for app database tables', 'value' => defined('APP_DB_PREFIX') ? 'app_' : '', ]; // -------------------------------------------------------------------------- // Any constants defined by the components? $componentVars = $this->getConstantsFromComponents('APP', $vars); $vars = array_merge($vars, $componentVars); // -------------------------------------------------------------------------- // Any other constants defined in app.php? $appFile = $this->getConstantsFromFile('config/app.php', $vars); $vars = array_merge($vars, $appFile); // -------------------------------------------------------------------------- return $vars; }
Defines all the App vars and their defaults @return array
private function getVarValue($sKey, $aVars) { foreach ($aVars as $aVar) { if ($sKey == $aVar['key']) { return $aVar['value']; } } return null; }
Returns the current value of a variable @param string $sKey The key to return @param array $aVars The variable array to look at @return mixed var value (usually string) on success, null on failure
private function getConstantsFromFile($path, array $vars = []) { $out = []; if (file_exists($path)) { $appFile = file_get_contents($path); $pattern = '/define\([\'|"](.+?)[\'|"]\,(.*)\)/'; preg_match_all($pattern, $appFile, $matches); if (!empty($matches[0])) { $numMatches = count($matches[0]); // Remove quotes from stringy values for ($i = 0; $i < $numMatches; $i++) { $matches[2][$i] = trim($matches[2][$i]); if (substr($matches[2][$i], 0, 1) == '\'' || substr($matches[2][$i], 0, 1) == '"') { // Remove the first and last character; subtracting 2 to account for the removal of both chars $matches[2][$i] = substr($matches[2][$i], 1, strlen($matches[2][$i]) - 2); } } for ($i = 0; $i < $numMatches; $i++) { // Check to see if it's already been requested $exists = false; foreach ($vars as $existing) { if (!is_string($existing) && $existing['key'] == $matches[1][$i]) { $exists = true; } } if (!$exists) { $name = str_replace('_', ' ', $matches[1][$i]); $name = strtolower($name); $name = ucwords($name); $out[] = [ 'key' => $matches[1][$i], 'label' => $name, 'value' => defined($matches[1][$i]) ? constant($matches[1][$i]) : '', 'options' => [], ]; } } } } return $out; }
Finds all constants defined in a particular file @param string $path The path to analyse @param array $vars The existing variables to check against (so only new variables are returned) @return array
private function setVars(&$vars) { foreach ($vars as &$v) { if (is_array($v)) { $question = 'What should "' . $v['label'] . '" be set to?'; if (!empty($v['options'])) { $question .= ' (' . implode('|', $v['options']) . ')'; // The field has options, ensure the option selected is valid do { $v['value'] = $this->ask($question, $v['value']); if (isset($v['callback']) && is_callable($v['callback'])) { $v['value'] = call_user_func($v['callback'], $v['value']); } $bIsValidOption = in_array($v['value'], $v['options']); $question = '<error>Selection must be one of ' . implode(', ', $v['options']) . '</error>'; } while (!$bIsValidOption); } elseif (isset($v['validate']) && is_callable($v['validate'])) { // Validator, keep asking until validator passes do { $v['value'] = $this->ask($question, $v['value']); if (isset($v['callback']) && is_callable($v['callback'])) { $v['value'] = call_user_func($v['callback'], $v['value']); } $question = '<error>Sorry, that is not a valid selection.</error>'; } while (!call_user_func($v['validate'], $v['value'])); } else { // No validator, just ask and accept what's given $v['value'] = $this->ask($question, $v['value']); if (isset($v['callback']) && is_callable($v['callback'])) { $v['value'] = call_user_func($v['callback'], $v['value']); } } } } }
Requests the user to confirm all the variables @param array &$vars An array of the variables to set
private function writeFile($vars, $file) { $fp = fopen($file, 'w'); fwrite($fp, "<?php\n"); foreach ($vars as $v) { if (is_string($v)) { fwrite($fp, $v . "\n"); } else { if (is_numeric($v['value'])) { $sValue = $v['value']; } else { $sValue = "'" . str_replace("'", "\'", $v['value']) . "'"; } fwrite($fp, "define('" . $v['key'] . "', " . $sValue . ");\n"); } } fclose($fp); return true; }
Writes the supplied variables to the config file @param array $vars The variables to write @param string $file The file to write to @return boolean
private function migrateDb($sDbHost = null, $sDbUser = null, $sDbPass = null, $sDbName = null) { // Execute the migrate command, non-interactively and silently $iExitCode = $this->callCommand( 'db:migrate', [ '--dbHost' => $sDbHost, '--dbUser' => $sDbUser, '--dbPass' => $sDbPass, '--dbName' => $sDbName, ], false, true ); if ($iExitCode == static::EXIT_CODE_SUCCESS) { $this->oOutput->writeln('<info>done!</info>'); return true; } else { $this->abort( self::EXIT_CODE_FAILURE, [ 'The Migration tool encountered issues and aborted the migration.', 'You should run it manually and investigate any issues.', 'The exit code was ' . $iExitCode, ] ); return false; } }
Migrates the DB for a fresh install @param string $sDbHost The database host to connect to @param string $sDbUser The database user to connect with @param string $sDbPass The database password to connect with @param string $sDbName The database name to connect to @return boolean
private function rewriteRoutes() { $iExitCode = $this->callCommand('routes:rewrite', [], false, true); if ($iExitCode == static::EXIT_CODE_SUCCESS) { $this->oOutput->writeln('<info>done!</info>'); return true; } else { $this->abort( self::EXIT_CODE_FAILURE, [ 'The Routes Rewriting tool encountered issues and aborted the process.', 'You should run it manually and investigate any issues.', 'The exit code was ' . $iExitCode, ] ); return false; } }
Rewrites routes @return bool
protected function abort($iExitCode = self::EXIT_CODE_FAILURE, array $aMessages = []) { $aMessages[] = 'Aborting install'; if (!empty($this->oDb) && $this->oDb->isTransactionRunning()) { $aMessages[] = 'Rolling back Database'; $this->oDb->transactionRollback(); } return parent::abort($iExitCode, $aMessages); }
Performs the abort functionality and returns the exit code @param array $aMessages The error message @param integer $iExitCode The exit code @return int
private function buildSortParameters(ParameterBuilderInterface $builder, array $groups = [], array $allowedSortTypes = []): void { $sortTypes = [ 'Published' => 'date_published', 'Modified' => 'date_modified', 'Alphabetical' => 'content_name', 'Priority' => 'location_priority', 'Defined by parent' => 'defined_by_parent', ]; if (count($allowedSortTypes) > 0) { $sortTypes = array_intersect($sortTypes, $allowedSortTypes); } $builder->add( 'sort_type', ParameterType\ChoiceType::class, [ 'required' => true, 'options' => $sortTypes, 'groups' => $groups, ] ); $builder->add( 'sort_direction', ParameterType\ChoiceType::class, [ 'required' => true, 'options' => [ 'Descending' => LocationQuery::SORT_DESC, 'Ascending' => LocationQuery::SORT_ASC, ], 'groups' => $groups, ] ); }
Builds the parameters for sorting eZ content.
private function getSortClauses(ParameterCollectionInterface $parameterCollection, ?Location $parentLocation = null): array { $sortType = $parameterCollection->getParameter('sort_type')->getValue() ?? 'default'; $sortDirection = $parameterCollection->getParameter('sort_direction')->getValue() ?? LocationQuery::SORT_DESC; if ($sortType === 'defined_by_parent' && $parentLocation !== null) { return $parentLocation->getSortClauses(); } return [ new self::$sortClauses[$sortType]($sortDirection), ]; }
Returns the clauses for sorting eZ content. @return \eZ\Publish\API\Repository\Values\Content\Query\SortClause[]
public function getAllFlat() { $aOut = array(); $aCountries = $this->getAll(); foreach ($aCountries as $oCountry) { $aOut[$oCountry->code] = $oCountry->label; } return $aOut; }
Get all defined countries as a flat array @return array
public function getByCode($sCode) { $aCountries = $this->getAll(); return ! empty($aCountries[$sCode]) ? $aCountries[$sCode] : false; }
Get a country by it's code @param string $sCode The code to look for @return mixed stdClass on success, false on failure
public function getContinentByCode($sCode) { $aContinents = $this->getAll(); return ! empty($aContinents[$sCode]) ? $aContinents[$sCode] : false; }
Get a continent by it's code @param string $sCode The continents code @return mixed stdClass on success, false on failure
public function setConfig($aConfig) { foreach ($aConfig as $sKey => $mValue) { if (property_exists($this, $sKey)) { $this->{$sKey} = $mValue; } else { $this->oSettings->{$sKey} = $mValue; } } return $this; }
Sets the value of existing properties based on the default settings and database overrides, anything left over is placed into the $oSettings object. @param $aConfig @return $this
protected function getSetting($sProperty = null) { if (property_exists($this->oSettings, $sProperty)) { return $this->oSettings->{$sProperty}; } elseif (is_null($sProperty)) { return $this->oSettings; } else { return null; } }
Safely retrieve a value from the $oSettings object @param string $sProperty the property to retrieve @return mixed
public function getLogoUrl($iWidth = null, $iHeight = null) { $iLogoId = $this->getLogoId(); if (!empty($iLogoId) && !empty($iWidth) && !empty($iHeight)) { return cdnScale($iLogoId, $iWidth, $iHeight); } elseif (!empty($iLogoId)) { return cdnServe($iLogoId); } else { return null; } }
Returns the URL of the driver's logo @param integer $iWidth The bounding width @param integer $iHeight The bounding height @return string
public function getEnabledSlug() { if ($this->bEnableMultiple) { $aOut = []; foreach ($this->mEnabled as $oComponent) { $aOut[] = $oComponent->slug; } return $aOut; } else { return !empty($this->mEnabled->slug) ? $this->mEnabled->slug : null; } }
Fetches the slug of the enabled components, or array of slugs if bEnableMultiple is true @return array|string
public function getBySlug($sSlug) { foreach ($this->aComponents as $oComponent) { if ($sSlug == $oComponent->slug) { return $oComponent; } } return null; }
Get a component by it's slug @param string $sSlug The components's slug @return \stdClass
public function saveEnabled($mSlug) { $oAppSettingService = Factory::service('AppSetting'); if ($this->bEnableMultiple) { $mSlug = (array) $mSlug; $mSlug = array_filter($mSlug); $mSlug = array_unique($mSlug); } else { $mSlug = trim($mSlug); } $aSetting = [ $this->sEnabledSetting => $mSlug, ]; if (!$oAppSettingService->set($aSetting, $this->sModule)) { throw new NailsException($oAppSettingService->lastError(), 1); } return $this; }
Save which components are enabled @param array|string $mSlug The slug to set as enabled, or array of slugs if bEnableMultiple is true @throws NailsException @return $this
protected function extractComponentSettings($aSettings, $sSlug) { $aOut = []; foreach ($aSettings as $oSetting) { // If the object contains a `fields` property then consider this a field set and inception if (isset($oSetting->fields)) { $aOut = array_merge( $aOut, $this->extractComponentSettings( $oSetting->fields, $sSlug ) ); } else { $sValue = appSetting($oSetting->key, $sSlug); if (is_null($sValue) && isset($oSetting->default)) { $sValue = $oSetting->default; } $aOut[$oSetting->key] = $sValue; } } return $aOut; }
Recursively gets all the settings from the settings array @param array $aSettings The array of field sets and/or settings @param string $sSlug The components's slug @return array
protected function loremWord($iNumWords = 5) { $aWords = [ 'lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipiscing', 'elit', 'mauris', 'venenatis', 'metus', 'volutpat', 'hendrerit', 'interdum', 'nisi', 'odio', 'finibus', 'ex', 'eu', 'congue', 'mauris', 'nisi', 'in', 'magna', 'ut', 'gravida', 'neque', 'at', 'nulla', 'viverra', 'egestas', 'vel', 'et', 'ante', 'maecenas', 'hendrerit', 'sit', 'amet', 'urna', 'posuere', 'ultrices', 'aenean', 'quis', 'velit', 'velit', 'suspendisse', 'sit', 'amet', 'egestas', 'tortor', ]; $aOut = []; for ($i = 0; $i < $iNumWords; $i++) { $aOut[] = $aWords[array_rand($aWords)]; } return implode(' ', $aOut); }
Generate some random Lorem Ipsum words @param int $iNumWords The number of words to generate @return string
protected function loremSentence($iNumSentences = 1) { $aOut = []; $aLengths = [5, 6, 8, 10, 12]; for ($i = 0; $i < $iNumSentences; $i++) { $iLength = $aLengths[array_rand($aLengths)]; $aOut[] = ucfirst($this->loremWord($iLength)); } return implode('. ', $aOut) . '.'; }
Generate some random Lorem Ipsum sentences @param int $iNumSentences The number of sentences to generate @return string
protected function loremParagraph($iNumParagraphs = 1) { $aOut = []; $aLengths = [5, 6, 8, 10, 12]; for ($i = 0; $i < $iNumParagraphs; $i++) { $iLength = $aLengths[array_rand($aLengths)]; $aOut[] = $this->loremSentence($iLength); } return implode("\n\n", $aOut); }
Generate some random Lorem Ipsum paragraphs @param int $iNumParagraphs The number of paragraphs to generate @return string
protected function randomId($sModel, $sProvider, $aData = []) { $oModel = Factory::model($sModel, $sProvider); $aResults = $oModel->getAll(0, 1, $aData + ['sort' => [['id', 'random']]]); $oRow = reset($aResults); return $oRow ? $oRow->id : null; }
Returns a random ID from a particular model @param string $sModel The model to use @param string $sProvider The model's provider @param array $aData Any data to pass to the model @return int|null