code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
private function buildContentTypeFilterParameters(ParameterBuilderInterface $builder, array $groups = []): void
{
$builder->add(
'filter_by_content_type',
ParameterType\Compound\BooleanType::class,
[
'groups' => $groups,
]
);
$builder->get('filter_by_content_type')->add(
'content_types',
EzParameterType\ContentTypeType::class,
[
'multiple' => true,
'groups' => $groups,
]
);
$builder->get('filter_by_content_type')->add(
'content_types_filter',
ParameterType\ChoiceType::class,
[
'required' => true,
'options' => [
'Include content types' => 'include',
'Exclude content types' => 'exclude',
],
'groups' => $groups,
]
);
} | Builds the parameters for filtering by content types. |
private function getContentTypeFilterCriteria(ParameterCollectionInterface $parameterCollection): ?Criterion
{
if ($parameterCollection->getParameter('filter_by_content_type')->getValue() !== true) {
return null;
}
$contentTypes = $parameterCollection->getParameter('content_types')->getValue() ?? [];
if (count($contentTypes) === 0) {
return null;
}
$contentTypeFilter = new Criterion\ContentTypeId(
$this->getContentTypeIds($contentTypes)
);
if ($parameterCollection->getParameter('content_types_filter')->getValue() === 'exclude') {
$contentTypeFilter = new Criterion\LogicalNot($contentTypeFilter);
}
return $contentTypeFilter;
} | Returns the criteria used to filter content by content type. |
public function read(string $sKey): ?Resource\Cookie
{
return ArrayHelper::getFromArray($sKey, $this->aCookies, null);
} | Returns a specific cookie
@param string $sKey The cookie's key
@return Resource\Cookie|null |
public function write(
string $sKey,
string $sValue,
int $iTTL = null,
string $sPath = '',
string $sDomain = '',
bool $bSecure = false,
bool $bHttpOnly = false
): bool {
if (setcookie($sKey, $sValue, $iTTL ? time() + $iTTL : 0, $sPath, $sDomain, $bSecure, $bHttpOnly)) {
$this->aCookies[$sKey] = Factory::resource(
'Cookie',
null,
(object) [
'key' => $sKey,
'value' => $sValue,
]
);
return true;
}
return false;
} | Writes a cookie, or overwrites an existing one
@param string $sKey The cookie's key
@param string $sValue The cookie's value
@param int|null $iTTL The cookie's TTL in seconds
@return bool |
public function delete(string $sKey): bool
{
if (array_key_exists($sKey, $this->aCookies) && setcookie($sKey, '', 1)) {
unset($this->aCookies[$sKey]);
return true;
}
return false;
} | Delete a cookie
@param string $sKey The cookie to delete, or an array of cookies
@return bool |
public function view($view, $vars = [], $return = false)
{
if (strpos($view, '/') === 0) {
// The supplied view is an absolute path, so use it.
// Add on EXT if it's not there (so pathinfo() works as expected)
if (substr($view, strlen(EXT) * -1) != EXT) {
$view .= EXT;
}
// Get path information about the view
$pathInfo = pathinfo($view);
$path = $pathInfo['dirname'] . '/';
$view = $pathInfo['filename'];
// Set the view path so the loader knows where to look
$this->_ci_view_paths = [$path => true] + $this->_ci_view_paths;
// Load the view
return $this->_ci_load([
'_ci_view' => $view,
'_ci_vars' => $this->_ci_object_to_array($vars),
'_ci_return' => $return,
]);
} else {
/**
* Try looking in the application folder second - prevents Nails views
* being loaded over an application view.
*/
$absoluteView = APPPATH . 'views/' . $view;
if (substr($absoluteView, strlen(EXT) * -1) != EXT) {
$absoluteView .= EXT;
}
if (file_exists($absoluteView)) {
// Try again with this view
return $this->view($absoluteView, $vars, $return);
} else {
// Fall back to the old method
return parent::view($view, $vars, $return);
}
}
} | Loads a view. If an absolute path is provided then that view will be used,
otherwise the system will search the modules
@param string $view The view to load
@param array $vars An array of data to pass to the view
@param boolean $return Whether or not to return then view, or output it
@return mixed |
public function viewExists($view)
{
list($path, $view) = Modules::find($view, $this->_module, 'views/');
return (bool) trim($path);
} | Determines whether or not a view exists
@param string $view The view to look for
@return boolean |
public function helper($helpers = [])
{
$aHelpers = (array) $helpers;
foreach ($aHelpers as $sHelper) {
Factory::helper($sHelper);
}
} | Loads a helper. Overloading this method so that extended helpers in NAILS are
correctly loaded. Slightly more complex as the helper() method for
ModuleExtensions also needs to be fired (i.e it's functionality needs to exist
in here too).
@param array $helpers The helpers to load
@return void |
private function buildLocationQuery(Query $query, Location $parentLocation): LocationQuery
{
$locationQuery = new LocationQuery();
$criteria = [
new Criterion\Subtree($parentLocation->pathString),
new Criterion\Visibility(Criterion\Visibility::VISIBLE),
new Criterion\LogicalNot(new Criterion\LocationId($parentLocation->id)),
$this->getMainLocationFilterCriteria($query),
$this->getQueryTypeFilterCriteria($query, $parentLocation),
$this->getContentTypeFilterCriteria($query),
$this->getSectionFilterCriteria($query),
$this->getObjectStateFilterCriteria($query),
];
$criteria = array_filter(
$criteria,
static function ($criterion): bool {
return $criterion instanceof Criterion;
}
);
$locationQuery->filter = new Criterion\LogicalAnd($criteria);
$locationQuery->sortClauses = $this->getSortClauses($query, $parentLocation);
return $locationQuery;
} | Builds the query from current parameters. |
public function getBody($bIsJSON = true)
{
if ($bIsJSON) {
return json_decode($this->oResponse->getBody());
} else {
return (string) $this->oResponse->getBody();
}
} | Return the response's body, optionally parsed as JSON
@param boolean $bIsJSON Whether the body is JSON or not
@return array|\stdClass|string|null |
public static function property(string $sPropertyName, ?string $sComponentName = '')
{
$mProperty = self::getService('properties', $sPropertyName, $sComponentName);
if (is_callable($mProperty)) {
return $mProperty();
} else {
return $mProperty;
}
} | Return a property from the container.
@param string $sPropertyName The property name
@param string $sComponentName The name of the component which provides the property
@return mixed
@throws FactoryException |
public static function setProperty(string $sPropertyName, $mPropertyValue, ?string $sComponentName = ''): void
{
$sComponentName = empty($sComponentName) ? 'nails/common' : $sComponentName;
if (!self::$aContainers[$sComponentName]['properties']->offsetExists($sPropertyName)) {
throw new FactoryException(
'Property "' . $sPropertyName . '" is not provided by component "' . $sComponentName . '"',
0
);
}
self::$aContainers[$sComponentName]['properties'][$sPropertyName] = $mPropertyValue;
} | Sets a new value for a property
@param string $sPropertyName The property name
@param mixed $mPropertyValue The new property value
@param string $sComponentName The name of the component which provides the property
@return void
@throws FactoryException |
public static function service(string $sServiceName, ?string $sComponentName = ''): object
{
return static::getServiceOrModel(
static::$aLoadedItems['SERVICES'],
'services',
$sServiceName,
$sComponentName,
array_slice(func_get_args(), 2)
);
} | Return a service from the container.
@param string $sServiceName The service name
@param string $sComponentName The name of the component which provides the service
@return object
@throws FactoryException
@todo (Pablo - 2019-03-22) - Consider forcing all servcies to extend a base class (and add a typehint) |
public static function model(string $sModelName, ?string $sComponentName = ''): Base
{
return static::getServiceOrModel(
static::$aLoadedItems['MODELS'],
'models',
$sModelName,
$sComponentName,
array_slice(func_get_args(), 2)
);
} | Return a model from the container.
@param string $sModelName The model name
@param string $sComponentName The name of the component which provides the model
@return Base
@throws FactoryException |
private static function getServiceOrModel(
array &$aTrackerArray,
string $sType,
string $sName,
string $sComponent,
array $aParamaters
): object {
/**
* We track them like this because we need to return the instance of the
* item, not the closure. If we don't do this then we will always get
* a new instance of the item, which is undesireable.
*/
$sKey = md5($sComponent . $sName);
if (!array_key_exists($sKey, $aTrackerArray)) {
$aTrackerArray[$sKey] = call_user_func_array(
self::getService($sType, $sName, $sComponent),
$aParamaters
);
} elseif (!empty($aParamaters)) {
trigger_error(
'A call to Factory::' . $sType . '(' . $sName . ') passed construction paramaters, but the object has already been constructed'
);
}
return $aTrackerArray[$sKey];
} | Loads a servie or a model from the tracker array
@param array $aTrackerArray The tracker array to load from
@param string $sType The type of item being loaded
@param string $sName The name of the item being loaded
@param string $sComponent The name of the component which provides the item
@param array $aParamaters Any paramters to pass to the constructor
@return object
@throws FactoryException |
public static function factory(string $sFactoryName, ?string $sComponentName = ''): object
{
return call_user_func_array(
self::getService('factories', $sFactoryName, $sComponentName),
array_slice(func_get_args(), 2)
);
} | Return a factory from the container.
@param string $sFactoryName The factory name
@param string $sComponentName The name of the component which provides the factory
@return object
@throws FactoryException |
public static function resource(string $sResourceName, ?string $sComponentName = ''): Resource
{
return call_user_func_array(
self::getService('resources', $sResourceName, $sComponentName),
array_slice(func_get_args(), 2)
);
} | Return a resource from the container.
@param string $sResourceName The resource name
@param string $sComponentName The name of the component which provides the resource
@return Resource
@throws FactoryException |
public static function helper(string $sHelperName, ?string $sComponentName = ''): void
{
$sComponentName = empty($sComponentName) ? 'nails/common' : $sComponentName;
if (empty(self::$aLoadedHelpers[$sComponentName][$sHelperName])) {
if (empty(self::$aLoadedHelpers[$sComponentName])) {
self::$aLoadedHelpers[$sComponentName] = [];
}
/**
* If we're only interested in the app version of the helper then we change things
* around a little as the paths and reliance of a "component" based helper aren't the same
*/
if ($sComponentName == 'app') {
$sAppPath = NAILS_APP_PATH . 'application/helpers/' . $sHelperName . '.php';
if (!file_exists($sAppPath)) {
throw new FactoryException(
'Helper "' . $sComponentName . '/' . $sHelperName . '" does not exist.',
1
);
}
require_once $sAppPath;
} else {
$sComponentPath = NAILS_APP_PATH . 'vendor/' . $sComponentName . '/helpers/' . $sHelperName . '.php';
$sAppPath = NAILS_APP_PATH . 'application/helpers/' . $sComponentName . '/' . $sHelperName . '.php';
if (!file_exists($sComponentPath)) {
throw new FactoryException(
'Helper "' . $sComponentName . '/' . $sHelperName . '" does not exist.',
1
);
}
if (file_exists($sAppPath)) {
require_once $sAppPath;
}
require_once $sComponentPath;
}
self::$aLoadedHelpers[$sComponentName][$sHelperName] = true;
}
} | Load a helper file
@param string $sHelperName The helper name
@param string $sComponentName The name of the component which provides the factory
@throws FactoryException
@return void |
private static function getService(string $sServiceType, string $sServiceName, ?string $sComponentName = '')
{
$sComponentName = empty($sComponentName) ? 'nails/common' : $sComponentName;
if (!array_key_exists($sComponentName, self::$aContainers)) {
throw new FactoryException(
'No containers registered for ' . $sComponentName
);
} elseif (!array_key_exists($sServiceType, self::$aContainers[$sComponentName])) {
throw new FactoryException(
'No ' . $sServiceType . ' containers registered for ' . $sComponentName
);
} elseif (!self::$aContainers[$sComponentName][$sServiceType]->offsetExists($sServiceName)) {
throw new FactoryException(
ucfirst($sServiceType) . '::' . $sServiceName . ' is not provided by ' . $sComponentName
);
}
return self::$aContainers[$sComponentName][$sServiceType][$sServiceName];
} | Returns a service from the namespaced container
@param string $sServiceType The type of the service to return
@param string $sServiceName The name of the service to return
@param string $sComponentName The name of the module which defined it
@throws FactoryException
@return mixed |
public static function autoload(): void
{
// CI base helpers
require_once BASEPATH . 'core/Common.php';
$aComponents = [];
foreach (Components::available() as $oModule) {
$aComponents[] = (object) [
'slug' => $oModule->slug,
'autoload' => $oModule->autoload,
];
}
// Module items
foreach ($aComponents as $oModule) {
// Helpers
if (!empty($oModule->autoload->helpers)) {
foreach ($oModule->autoload->helpers as $sHelper) {
if (is_array($sHelper)) {
list($sName, $sProvider) = $sHelper;
self::helper($sName, $sProvider);
} else {
self::helper($sHelper, $oModule->slug);
}
}
}
// Services
if (!empty($oModule->autoload->services)) {
foreach ($oModule->autoload->services as $sService) {
if (is_array($sHelper)) {
list($sName, $sProvider) = $sService;
self::service($sName, $sProvider);
} else {
self::service($sService, $oModule->slug);
}
}
}
}
} | Auto-loads items at startup |
protected static function extractAutoLoadItemsFromComposerJson(string $sPath): \stdClass
{
$oOut = (object) ['helpers' => [], 'services' => []];
if (file_exists($sPath)) {
$oAppComposer = json_decode(file_get_contents($sPath));
if (!empty($oAppComposer->extra->nails->autoload->helpers)) {
foreach ($oAppComposer->extra->nails->autoload->helpers as $sHelper) {
$oOut->helpers[] = $sHelper;
}
}
if (!empty($oAppComposer->extra->nails->autoload->services)) {
foreach ($oAppComposer->extra->nails->autoload->services as $sService) {
$oOut->services[] = $sService;
}
}
}
return $oOut;
} | Extracts the autoload elements from a composer.json file
@param string $sPath The path to the composer.json file
@return \stdClass |
public static function destroyService(string $sServiceName, ?string $sComponentName = ''): bool
{
return static::destroyServiceOrModel(
static::$aLoadedItems['SERVICES'],
null,
$sServiceName,
$sComponentName
);
} | Allows for a service to be destroyed so that a subsequent request will yeild a new instance
@param string $sServiceName The name of the service to destroy
@param string $sComponentName The name of the component which provides the service
@return bool |
public static function destroyModel(string $sModelName, ?string $sComponentName = ''): bool
{
return static::destroyServiceOrModel(
static::$aLoadedItems['MODELS'],
null,
$sModelName,
$sComponentName
);
} | Allows for a model to be destroyed so that a subsequent request will yeild a new instance
@param string $sModelName The name of the model to destroy
@param string $sComponentName The name of the component which provides the model
@return bool |
public static function destroy(object $oInstance): bool
{
foreach (static::$aLoadedItems['SERVICES'] as $sKey => $oItem) {
if ($oItem === $oInstance) {
return static::destroyServiceOrModel(static::$aLoadedItems['SERVICES'], $sKey);
}
}
foreach (static::$aLoadedItems['MODELS'] as $sKey => $oItem) {
if ($oItem === $oInstance) {
return static::destroyServiceOrModel(static::$aLoadedItems['MODELS'], $sKey);
}
}
return false;
} | Destroys an object by its instance
@param object $oInstance The instance to destroy
@return bool |
private static function destroyServiceOrModel(
array &$aTrackerArray,
string $sKey,
string $sName = null,
string $sComponent = null
): bool {
if (!$sKey) {
$sKey = md5($sComponent . $sName);
}
if (array_key_exists($sKey, $aTrackerArray)) {
unset($aTrackerArray[$sKey]);
return true;
} else {
return false;
}
} | Destroys an item in the tracker array
@param array $aTrackerArray The tracker array to destroy from
@param string $sKey The key to destroy, if known
@param string $sName The name of the item being destroyed, used to generate the key
@param string $sComponent The name of the component which provides the item, used to generate the key
@return bool |
public function line($line = '', $params = null)
{
if (empty($params)) {
return parent::line($line);
}
// We have some parameters, sub 'em in or the unicorns will die.
$line = parent::line($line);
if ($line !== false) {
if (is_array($params)) {
$line = vsprintf($line, $params);
} else {
$line = sprintf($line, $params);
}
}
return $line;
} | Overriding the default line() method so that parameters can be specified
@param string $line the language line
@param array $params any parameters to sub in
@return string |
protected function setErrorReporting()
{
/**
* Configure how verbose PHP is; Everything except E_STRICT and E_ERROR;
* we'll let the errorHandler pick up fatal errors
*/
error_reporting(E_ALL ^ E_STRICT ^ E_ERROR);
// Configure whether errors are shown or no
if (function_exists('ini_set')) {
switch (Environment::get()) {
case Environment::ENV_PROD:
// Suppress all errors on production
ini_set('display_errors', false);
break;
default:
// Show errors everywhere else
ini_set('display_errors', true);
break;
}
}
} | Sets the appropriate error reporting values and handlers
@return void |
protected function passwordProtectedRequest()
{
$oInput = Factory::service('Input');
header('WWW-Authenticate: Basic realm="' . APP_NAME . ' - Restricted Area"');
header($oInput->server('SERVER_PROTOCOL') . ' 401 Unauthorized');
$oErrorHandler = Factory::service('ErrorHandler');
$oErrorHandler->renderErrorView(401);
exit(401);
} | Requests staging credentials
@return void |
protected function generateRoutes()
{
if (defined('NAILS_STARTUP_GENERATE_APP_ROUTES') && NAILS_STARTUP_GENERATE_APP_ROUTES) {
$oRoutesService = Factory::service('Routes');
if (!$oRoutesService->update()) {
throw new NailsException('Failed to generate routes_app.php. ' . $oRoutesService->lastError(), 500);
} else {
$oInput = Factory::service('Input');
redirect($oInput->server('REQUEST_URI'), 'auto', 307);
}
}
} | Checks if routes need to be generated as part of the startup request
@throws NailsException
@throws \Nails\Common\Exception\FactoryException |
protected function instantiateLanguages()
{
// Define default language
$oLanguageService = Factory::service('Language');
$oDefault = $oLanguageService->getDefault();
if (empty($oDefault)) {
throw new NailsException('No default language has been set, or it\'s been set incorrectly.');
}
Functions::define('APP_DEFAULT_LANG_CODE', $oDefault->code);
Functions::define('APP_DEFAULT_LANG_LABEL', $oDefault->label);
// --------------------------------------------------------------------------
/**
* Set any global preferences for this user, e.g languages, fall back to the
* app's default language (defined in config.php).
*/
$sUserLangCode = activeUser('language');
if (!empty($sUserLangCode)) {
Functions::define('RENDER_LANG_CODE', $sUserLangCode);
} else {
Functions::define('RENDER_LANG_CODE', APP_DEFAULT_LANG_CODE);
}
// Set the language config item which CodeIgniter will use.
$oConfig = Factory::service('Config');
$oConfig->set_item('language', RENDER_LANG_CODE);
// Load the Nails. generic lang file
$this->lang->load('nails');
} | Sets up language handling
@return void |
protected function definePackages()
{
/**
* This is an important part. Here we are defining all the packages to load.
* this translates as "where CodeIgniter will look for stuff".
*
* We have to do a few manual hacks to ensure things work as expected, i.e.
* the load/check order is:
*
* 1. The Application
* 2. Available modules
* 3. Nails Common
*/
// Reset
$oConfig = Factory::service('Config');
$oConfig->_config_paths = [];
$aPaths = [];
// Nails Common
$aPaths[] = NAILS_COMMON_PATH;
// Available Modules
$aAvailableModules = Components::modules();
foreach ($aAvailableModules as $oModule) {
$aPaths[] = $oModule->path;
}
// The Application
$aPaths[] = NAILS_APP_PATH . 'application';
foreach ($aPaths as $sPath) {
$this->load->add_package_path($sPath);
}
} | Defines all the package paths |
protected function isUserSuspended()
{
// Check if this user is suspended
if (isLoggedIn() && activeUser('is_suspended')) {
// Load models and langs
$oAuthModel = Factory::model('Auth', 'nails/module-auth');
$this->lang->load('auth/auth');
// Log the user out
$oAuthModel->logout();
// Create a new session
$oSession = Factory::service('Session', 'nails/module-auth');
$oSession->sess_create();
// Give them feedback
$oSession->setFlashData('error', lang('auth_login_fail_suspended'));
redirect('/');
}
} | Determines whether the active user is suspended and, if so, logs them out.
@return void |
public static function backwardsCompatibility(&$oBindTo)
{
/**
* Backwards compatibility
* Various older modules expect to be able to access a few services/models
* via magic methods. These will be deprecated soon.
*/
// @todo (Pablo - 2017-06-07) - Remove these
$oBindTo->db = Factory::service('Database');
$oBindTo->input = Factory::service('Input');
$oBindTo->output = Factory::service('Output');
$oBindTo->meta = Factory::service('Meta');
$oBindTo->asset = Factory::service('Asset');
$oBindTo->encrypt = Factory::service('Encrypt');
$oBindTo->logger = Factory::service('Logger');
$oBindTo->uri = Factory::service('Uri');
$oBindTo->security = Factory::service('Security');
$oBindTo->emailer = Factory::service('Emailer', 'nails/module-email');
$oBindTo->event = Factory::service('Event', 'nails/module-event');
$oBindTo->session = Factory::service('Session', 'nails/module-auth');
$oBindTo->user = Factory::model('User', 'nails/module-auth');
$oBindTo->user_group_model = Factory::model('UserGroup', 'nails/module-auth');
$oBindTo->user_password_model = Factory::model('UserPassword', 'nails/module-auth');
// Set variables for the views, too
$oBindTo->data['user'] = $oBindTo->user;
$oBindTo->data['user_group'] = $oBindTo->user_group_model;
$oBindTo->data['user_password'] = $oBindTo->user_password_model;
} | Provides some backwards compatability
@param \stdClass $oBindTo The class to bind to |
public static function populateUserFeedback(array &$aData)
{
// Set User Feedback alerts for the views
$oSession = Factory::service('Session', 'nails/module-auth');
$oUserFeedback = Factory::service('UserFeedback');
$aData['error'] = $oUserFeedback->get('error') ?: $oSession->getFlashData('error');
$aData['negative'] = $oUserFeedback->get('negative') ?: $oSession->getFlashData('negative');
$aData['success'] = $oUserFeedback->get('success') ?: $oSession->getFlashData('success');
$aData['positive'] = $oUserFeedback->get('positive') ?: $oSession->getFlashData('positive');
$aData['info'] = $oUserFeedback->get('info') ?: $oSession->getFlashData('info');
$aData['warning'] = $oUserFeedback->get('message') ?: $oSession->getFlashData('warning');
// @deprecated
$aData['message'] = $oUserFeedback->get('message') ?: $oSession->getFlashData('message');
$aData['notice'] = $oUserFeedback->get('notice') ?: $oSession->getFlashData('notice');
} | Populates an array from the UserFeedback and session classes
@param array $aData The array to populate |
public static function populatePageData(array &$aData)
{
/** @var Locale $oLocale */
$oLocale = Factory::service('Locale');
$aData['page'] = (object) [
'title' => '',
'html_lang' => $oLocale->get()->getLanguage(),
'seo' => (object) [
'title' => '',
'description' => '',
'keywords' => '',
],
];
} | Populates an array with a default object for page and SEO
@param array $aData The array to populate |
protected function setCommonMeta(array $aMeta = [])
{
$oMeta = Factory::service('Meta');
$oMeta
->addRaw([
'charset' => 'utf-8',
])
->addRaw([
'name' => 'viewport',
'content' => 'width=device-width, initial-scale=1',
]);
foreach ($aMeta as $aItem) {
$oMeta->addRaw($aItem);
}
} | Sets some common meta for every page load
@param array $aMeta Any additional meta items to set
@throws \Nails\Common\Exception\FactoryException |
public static function setNailsJs()
{
$oAsset = Factory::service('Asset');
$aVariables = [
'ENVIRONMENT' => Environment::get(),
'SITE_URL' => site_url('', Functions::isPageSecure()),
'NAILS' => (object) [
'URL' => NAILS_ASSETS_URL,
'LANG' => (object) [],
'USER' => (object) [
'ID' => activeUser('id') ? activeUser('id') : null,
'FNAME' => activeUser('first_name'),
'LNAME' => activeUser('last_name'),
'EMAIL' => activeUser('email'),
],
],
];
foreach ($aVariables as $sKey => $mValue) {
$oAsset->inline('window.' . $sKey . ' = ' . json_encode($mValue) . ';', 'JS', 'HEADER');
}
} | Sets a global Nails JS object
@throws \Nails\Common\Exception\FactoryException |
protected function setGlobalJs()
{
$oAsset = Factory::service('Asset');
$sCustomJs = appSetting('site_custom_js', 'site');
if (!empty($sCustomJs)) {
$oAsset->inline($sCustomJs, 'JS');
}
// --------------------------------------------------------------------------
/**
* If a Google Analytics profile has been specified then include that too
*/
$sGoogleAnalyticsProfile = appSetting('google_analytics_account');
if (!empty($sGoogleAnalyticsProfile)) {
$oAsset->inline(
"(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '" . appSetting('google_analytics_account') . "', 'auto');
ga('send', 'pageview');",
'JS'
);
}
} | Sets global JS
@throws \Nails\Common\Exception\FactoryException |
protected function setGlobalCss()
{
$oAsset = Factory::service('Asset');
$sCustomCss = appSetting('site_custom_css', 'site');
if (!empty($sCustomCss)) {
$oAsset->inline($sCustomCss, 'CSS');
}
} | Sets global CSS
@throws \Nails\Common\Exception\FactoryException |
protected function writeFile()
{
// Routes are writable, apparently, give it a bash
$sData = '<?php' . "\n\n";
$sData .= '/**' . "\n";
$sData .= ' * THIS FILE IS CREATED/MODIFIED AUTOMATICALLY' . "\n";
$sData .= ' * ===========================================' . "\n";
$sData .= ' *' . "\n";
$sData .= ' * Any changes you make in this file will be overwritten the' . "\n";
$sData .= ' * next time the app routes are generated.' . "\n";
$sData .= ' *' . "\n";
$sData .= ' * See Nails docs for instructions on how to utilise the' . "\n";
$sData .= ' * routes_app.php file' . "\n";
$sData .= ' *' . "\n";
$sData .= ' **/' . "\n\n";
// --------------------------------------------------------------------------
foreach ($this->aRoutes as $sKey => $sValue) {
if (preg_match('#^//.*$#', $sKey)) {
// This is a comment
$sData .= $sKey . "\n";
} else {
// This is a route
$sData .= '$route[\'' . $sKey . '\']=\'' . $sValue . '\';' . "\n";
}
}
$oDate = Factory::factory('DateTime');
$sData .= "\n" . '//LAST GENERATED: ' . $oDate->format('Y-m-d H:i:s');
$sData .= "\n";
// --------------------------------------------------------------------------
$fHandle = @fopen(static::ROUTES_DIR . static::ROUTES_FILE, 'w');
if (!$fHandle) {
$this->setError('Unable to open routes file for writing.');
return false;
}
if (!fwrite($fHandle, $sData)) {
fclose($fHandle);
$this->setError('Unable to write data to routes file.');
return false;
}
fclose($fHandle);
return true;
} | Write the routes file
@return boolean |
public function canWriteRoutes()
{
if (!is_null($this->bCanWriteRoutes)) {
return $this->bCanWriteRoutes;
}
// First, test if file exists, if it does is it writable?
if (file_exists(static::ROUTES_DIR . static::ROUTES_FILE)) {
if (is_writable(static::ROUTES_DIR . static::ROUTES_FILE)) {
$this->bCanWriteRoutes = true;
return true;
} else {
// Attempt to chmod the file
if (@chmod(static::ROUTES_DIR . static::ROUTES_FILE, FILE_WRITE_MODE)) {
$this->bCanWriteRoutes = true;
return true;
} else {
$this->setError('The route config exists, but is not writable.');
$this->bCanWriteRoutes = false;
return false;
}
}
} elseif (is_writable(static::ROUTES_DIR)) {
$this->bCanWriteRoutes = true;
return true;
} else {
// Attempt to chmod the directory
if (@chmod(static::ROUTES_DIR, DIR_WRITE_MODE)) {
$this->bCanWriteRoutes = true;
return true;
} else {
$this->setError('The route directory is not writable. <small>' . static::ROUTES_DIR . '</small>');
$this->bCanWriteRoutes = false;
return false;
}
}
} | Determine whether or not the routes can be written
@return boolean |
protected function getCountCommon(array $aData = [])
{
// @deprecated - searching should use the search() method, but this in place
// as a quick fix for loads of admin controllers
if (!empty($aData['keywords']) && !empty($this->searchableFields)) {
if (empty($aData['or_like'])) {
$aData['or_like'] = [];
}
$sAlias = $this->getTableAlias(true);
foreach ($this->searchableFields as $mField) {
// If the field is an array then search across the columns concatenated together
if (is_array($mField)) {
$sMappedFields = array_map(function ($sInput) use ($sAlias) {
if (strpos($sInput, '.') !== false) {
return $sInput;
} else {
return $sAlias . $sInput;
}
}, $mField);
$aData['or_like'][] = ['CONCAT_WS(" ", ' . implode(',', $sMappedFields) . ')', $aData['keywords']];
} else {
if (strpos($mField, '.') !== false) {
$aData['or_like'][] = [$mField, $aData['keywords']];
} else {
$aData['or_like'][] = [$sAlias . $mField, $aData['keywords']];
}
}
}
}
// --------------------------------------------------------------------------
$this->getCountCommonCompileSelect($aData);
$this->getCountCommonCompileFilters($aData);
$this->getCountCommonCompileWheres($aData);
$this->getCountCommonCompileLikes($aData);
$this->getCountCommonCompileHavings($aData);
$this->getCountCommonCompileSort($aData);
} | This method applies the conditionals which are common across the get_*()
methods and the count() method.
@param array $aData Data passed from the calling method
@return void |
protected function getCountCommonCompileSelect(array &$aData)
{
if (!empty($aData['select'])) {
$oDb = Factory::service('Database');
$oDb->select($aData['select']);
}
} | Compiles the select statement
@param array &$aData The data array
@return void |
protected function getCountCommonCompileFiltersString($sColumn, $mValue, $bIsQuery)
{
if (is_object($mValue) && ($mValue instanceof \Closure)) {
$mValue = $mValue();
}
$oDb = Factory::service('Database');
if ($bIsQuery) {
$aBits = [$mValue];
} elseif (!is_array($mValue)) {
$aBits = [
strpos($sColumn, '`') === false ? $oDb->escape_str($sColumn, false) : $sColumn,
'=',
$oDb->escape($mValue),
];
} else {
$sOperator = ArrayHelper::getFromArray(0, $mValue);
$sValue = ArrayHelper::getFromArray(1, $mValue);
$bEscape = (bool) ArrayHelper::getFromArray(2, $mValue, true);
$aBits = [
$oDb->escape_str($sColumn, false),
$sOperator,
$bEscape ? $oDb->escape($sValue) : $sValue,
];
}
return trim(implode(' ', $aBits));
} | Compile the filter string
@param string $sColumn The column
@param mixed $mValue The value
@param boolean $bIsQuery Whether the value is an SQL wuery or not
@return string |
protected function getCountCommonCompileSort(array &$aData)
{
$oDb = Factory::service('Database');
if (!empty($aData['sort'])) {
/**
* How we handle sorting
* =====================
*
* - If $aData['sort'] is a string assume it's the field to sort on, use the default order
* - If $aData['sort'] is a single dimension array then assume the first element (or the element
* named 'column') is the column; and the second element (or the element named 'order') is the
* direction to sort in
* - If $aData['sort'] is a multidimensional array then loop each element and test as above.
*
**/
if (is_string($aData['sort'])) {
// String
$oDb->order_by($aData['sort']);
} elseif (is_array($aData['sort'])) {
$mFirst = reset($aData['sort']);
if (is_string($mFirst)) {
// Single dimension array
$aSort = $this->getCountCommonParseSort($aData['sort']);
if (!empty($aSort['column'])) {
$oDb->order_by($aSort['column'], $aSort['order']);
}
} else {
// Multi dimension array
foreach ($aData['sort'] as $sort) {
$aSort = $this->getCountCommonParseSort($sort);
if (!empty($aSort['column'])) {
$oDb->order_by($aSort['column'], $aSort['order']);
}
}
}
}
}
} | Compiles the sort element into the query
@param array &$aData The data array
@return void |
protected function getCountCommonParseSort($mSort)
{
$aOut = ['column' => null, 'order' => null];
// --------------------------------------------------------------------------
if (is_string($mSort)) {
$aOut['column'] = $mSort;
return $aOut;
} elseif (isset($mSort['column'])) {
$aOut['column'] = $mSort['column'];
} else {
// Take the first element
$aOut['column'] = reset($mSort);
$aOut['column'] = is_string($aOut['column']) ? $aOut['column'] : null;
}
if ($aOut['column']) {
// Determine order
if (isset($mSort['order'])) {
$aOut['order'] = $mSort['order'];
} elseif (count($mSort) > 1) {
// Take the last element
$aOut['order'] = end($mSort);
$aOut['order'] = is_string($aOut['order']) ? $aOut['order'] : null;
}
}
return $aOut;
} | Parse the sort variable
@param string|array $mSort The sort variable
@return array |
private function buildParentLocationParameters(ParameterBuilderInterface $builder, array $groups = []): void
{
$builder->add(
'use_current_location',
ParameterType\Compound\BooleanType::class,
[
'reverse' => true,
'groups' => $groups,
]
);
$builder->get('use_current_location')->add(
'parent_location_id',
EzParameterType\LocationType::class,
[
'allow_invalid' => true,
'groups' => $groups,
]
);
} | Builds the parameters for filtering by parent location. |
private function getParentLocation(ParameterCollectionInterface $parameterCollection): ?Location
{
if ($parameterCollection->getParameter('use_current_location')->getValue() === true) {
return $this->contentProvider->provideLocation();
}
$parentLocationId = $parameterCollection->getParameter('parent_location_id')->getValue();
if ($parentLocationId === null) {
return null;
}
try {
$parentLocation = $this->locationService->loadLocation($parentLocationId);
return $parentLocation->invisible ? null : $parentLocation;
} catch (Throwable $t) {
return null;
}
} | Returns the parent location to use for the parameter collection. |
public function addHook($hookwhere, $hook)
{
if (is_array($hook)) {
if (isset($hook['classref']) && isset($hook['method']) && isset($hook['params'])) {
if (is_object($hook['classref']) && method_exists($hook['classref'], $hook['method'])) {
$this->aCustomHooks[$hookwhere][] = $hook;
return true;
}
}
}
return false;
} | Adds a particular hook
@param string The hook name
@param array The hook configuration (classref, method, params)
@return bool |
public function call_hook($sWhich = '')
{
if (!isset($this->aCustomHooks[$sWhich])) {
return parent::call_hook($sWhich);
}
if (isset($this->aCustomHooks[$sWhich][0]) && is_array($this->aCustomHooks[$sWhich][0])) {
foreach ($this->aCustomHooks[$sWhich] as $aCustomHook) {
$this->runCustomHook($aCustomHook);
}
return true;
} else {
$this->runCustomHook($this->aCustomHooks[$sWhich]);
return true;
}
return parent::call_hook($sWhich);
} | Call a particular hook
@param string $sWhich The hook to cal
@return bool |
protected function runCustomHook($aData)
{
if (!is_array($aData)) {
return false;
}
/** -----------------------------------
* Safety - Prevents run-away loops
* ------------------------------------
* If the script being called happens to have the same
* hook call within it a loop can happen
*/
if ($this->bCustomHooksInProgress == true) {
return;
}
// Set class/method name
$oClass = null;
$sMethod = null;
$aParams = [];
if (isset($aData['classref'])) {
$oClass =& $aData['classref'];
}
if (isset($aData['method'])) {
$sMethod = $aData['method'];
}
if (isset($aData['params'])) {
$aParams = $aData['params'];
}
if (!is_object($oClass) || !method_exists($oClass, $sMethod)) {
return false;
}
// Set the in_progress flag
$this->bCustomHooksInProgress = true;
// Call the requested class and/or function
$oClass->$sMethod($aParams);
$this->bCustomHooksInProgress = false;
return true;
} | Execute a cusotm hook
@param array $aData The hook data
@return bool|void |
public function _run_hook($aData)
{
if (!is_array($aData)) {
return false;
}
/** -----------------------------------
* Safety - Prevents run-away loops
* ------------------------------------
* If the script being called happens to have the same
* hook call within it a loop can happen
*/
if ($this->bCustomHooksInProgress == true) {
return;
}
// Set file path
if (!isset($aData['filepath']) || !isset($aData['filename'])) {
return false;
}
// Using absolute filepath?
if (substr($aData['filepath'], 0, 1) == '/') {
$sFilePath = rtrim($aData['filepath'], '/') . '/';
$sFilePath .= $aData['filename'];
} else {
$sFilePath = APPPATH;
$sFilePath .= rtrim($aData['filepath'], '/') . '/';
$sFilePath .= $aData['filename'];
}
if (!file_exists($sFilePath)) {
return false;
}
// Set class/function name
$sClass = false;
$sFunction = false;
$sParams = '';
if (isset($aData['class']) && $aData['class'] != '') {
$sClass = $aData['class'];
}
if (isset($aData['function'])) {
$sFunction = $aData['function'];
}
if (isset($aData['params'])) {
$sParams = $aData['params'];
}
if ($sClass === false && $sFunction === false) {
return false;
}
// Set the in_progress flag
$this->in_progress = true;
// Call the requested class and/or function
if ($sClass !== false) {
if (!class_exists($sClass)) {
require($sFilePath);
}
$HOOK = new $sClass();
$HOOK->$sFunction($sParams);
} else {
if (!function_exists($sFunction)) {
require($sFilePath);
}
$sFunction($sParams);
}
$this->in_progress = false;
return true;
} | Run Hook
Runs a particular hook
@param array The hook details
@return bool |
public function create(array $aData = [], $bReturnObject = false)
{
$mResult = parent::create($aData, $bReturnObject);
if ($mResult) {
$this->saveBreadcrumbs($bReturnObject ? $mResult->id : $mResult);
$this->saveOrder();
// Refresh object to get updated breadcrumbs/URL
if ($bReturnObject) {
$mResult = $this->getById($mResult->id);
}
}
return $mResult;
} | Generates breadcrumbs after creating an object
@param array $aData Data to create the item with
@param bool $bReturnObject Whether to return an object or not
@return mixed |
public function update($mIds, array $aData = []): bool
{
$mResult = parent::update($mIds, $aData);
if ($mResult) {
$aIds = (array) $mIds;
foreach ($aIds as $iId) {
$this->saveBreadcrumbs($iId);
}
$this->saveOrder();
}
return $mResult;
} | Generates breadcrumbs after updating an object
@param array|integer $mIds The ID(s) to update
@param array $aData Data to update the items with¬
@return mixed |
protected function saveBreadcrumbs($iItemId)
{
// @todo (Pablo - 2018-07-01) - protect against infinite loops
$oItem = $this->getById($iItemId);
if (!empty($oItem)) {
$aBreadcrumbs = [];
$iParentId = (int) $oItem->parent_id;
while ($iParentId) {
$oParentItem = $this->getById($iParentId);
if ($oParentItem) {
$iParentId = $oParentItem->parent_id;
array_unshift(
$aBreadcrumbs,
(object) array_filter([
'id' => $oParentItem->id,
'label' => !empty($oParentItem->label) ? $oParentItem->label : null,
'slug' => !empty($oParentItem->slug) ? $oParentItem->slug : null,
'url' => !empty($oParentItem->url) ? $oParentItem->url : null,
])
);
} else {
$iParentId = null;
}
}
// Save breadcrumbs to the current item
parent::update(
$iItemId,
[
$this->getBreadcrumbsColumn() => json_encode($aBreadcrumbs),
]
);
// Save breadcrumbs of all children
$oDb = Factory::service('Database');
$oDb->where('parent_id', $iItemId);
$aChildren = $oDb->get($this->getTableName())->result();
foreach ($aChildren as $oItem) {
$this->saveBreadcrumbs($oItem->id);
}
}
} | Generates breadcrumbs for the item
@param integer $iItemId The item's ID |
protected function saveOrder()
{
/**
* If the model also uses the Sortable trait then let that handle sorting
*/
if (!classUses($this, Sortable::class)) {
/** @var Database $oDb */
$oDb = Factory::service('Database');
$oDb->select([
$this->getColumn('id'),
$this->getColumn('parent_id', 'parent_id'),
]);
if (!$this->isDestructiveDelete()) {
$oDb->where($this->getColumn('deleted'), false);
}
$oDb->order_by($this->getColumn('label'));
$aItems = $oDb->get($this->getTableName())->result();
$iIndex = 0;
$aItems = $this->flattenTree(
$this->buildTree($aItems)
);
foreach ($aItems as $oItem) {
$oDb->set($this->getOrderColumn(), ++$iIndex);
$oDb->where($this->getColumn('id'), $oItem->id);
$oDb->update($this->getTableName());
}
}
} | -------------------------------------------------------------------------- |
protected function buildTree(array &$aItems, int $iParentId = null): array
{
$aTemp = [];
$sIdColumn = $this->getColumn('id');
$sParentColumn = $this->getColumn('parent_id', 'parent_id');
foreach ($aItems as $oItem) {
if ($oItem->{$sParentColumn} == $iParentId) {
$oItem->children = $this->buildTree($aItems, $oItem->{$sIdColumn});
$aTemp[] = $oItem;
}
}
return $aTemp;
} | Builds a tree of objects
@param array $aItems The items to sort
@param int $iParentId The parent ID to sort on
@return array |
protected function flattenTree(array $aItems, &$aOutput = []): array
{
foreach ($aItems as $oItem) {
$aOutput[] = $oItem;
$this->flattenTree($oItem->children, $aOutput);
unset($oItem->children);
}
return $aOutput;
} | Flattens a tree of objects
@param array $aItems The items to flatten
@param array $aOutput The array to write to
@return array |
public function generateUrl($oObj)
{
if (empty($oObj->breadcrumbs)) {
return null;
}
$aBreadcrumbs = json_decode($oObj->breadcrumbs);
if (is_null($aBreadcrumbs)) {
return null;
}
$aUrl = arrayExtractProperty($aBreadcrumbs, 'slug');
$aUrl[] = $oObj->slug;
$sUrl = implode('/', $aUrl);
$sNamespace = defined('static::NESTED_URL_NAMESPACE') ? addTrailingSlash(static::NESTED_URL_NAMESPACE) : '';
return $sNamespace . $sUrl;
} | Generates the URL for nestable objects; optionally place under a URL namespace
@param \stdClass $oObj The object to generate the URL for
@return string|null |
public function getChildren($iId, $bRecursive = false, array $aData = [])
{
$aQueryData = $aData;
if (!array_key_exists('where', $aQueryData)) {
$aQueryData['where'] = [];
}
$aQueryData['where'][] = ['parent_id', $iId];
$aChildren = $this->getAll($aQueryData);
foreach ($aChildren as $oChild) {
if ($bRecursive) {
$oChild->children = $this->getChildren($oChild->id, $bRecursive, $aData);
}
}
return $aChildren;
} | Retrieves the immediate children of an item
@param integer $iId The ID of the item
@param bool $bRecursive Whetehr to recursively fetch children
@param array $aData Any additional data to pass to the `getAll()` method
@return mixed |
private function getContentType(EzLocation $location): ContentType
{
if (method_exists($location, 'getContent') && method_exists($location->getContent(), 'getContentType')) {
return $location->getContent()->getContentType();
}
// @deprecated Remove when support for eZ kernel < 7.4 ends
return $this->repository->getContentTypeService()->loadContentType(
$location->contentInfo->contentTypeId
);
} | Loads the content type for provided location.
@deprecated Acts as a BC layer for eZ kernel <7.4 |
public function getAll($iPage = null, $iPerPage = null, array $aData = [], $bIncludeDeleted = false): array
{
$aResult = parent::getAll($iPage, $iPerPage, $aData, $bIncludeDeleted);
$this->addLocaleToResources($aResult);
return $aResult;
} | Overloads the getAll to add a Locale object to each resource
@param int|null|array $iPage The page number of the results, if null then no pagination; also accepts an $aData array
@param int|null $iPerPage How many items per page of paginated results
@param array $aData Any data to pass to getCountCommon()
@param bool $bIncludeDeleted If non-destructive delete is enabled then this flag allows you to include deleted items
@return Resource[]
@throws FactoryException |
protected function addLocaleToResource(Resource $oResource): void
{
/** @var Locale $oLocale */
$oLocale = Factory::service('Locale');
// Add the locale for _this_ item
$oResource->locale = $this->getLocale(
$oResource->{static::$sColumnLanguage},
$oResource->{static::$sColumnRegion}
);
// Set the locales for all _available_ items
$oResource->available_locales = array_map(function ($sLocale) use ($oLocale) {
list($sLanguage, $sRegion) = $oLocale::parseLocaleString($sLocale);
return $this->getLocale($sLanguage, $sRegion);
}, explode(',', $oResource->available_locales));
// Specify which locales are missing
$oResource->missing_locales = array_diff(
$oLocale->getSupportedLocales(),
$oResource->available_locales
);
// Remove internal fields
unset($oResource->{static::$sColumnLanguage});
unset($oResource->{static::$sColumnRegion});
} | Adds a Locale object to a Resource, and removes the language and region properties
@param Resource $oResource The resource to modify
@throws FactoryException |
private function getLocale(string $sLanguage, string $sRegion): \Nails\Common\Factory\Locale
{
return Factory::factory('Locale')
->setLanguage(Factory::factory('LocaleLanguage', null, $sLanguage))
->setRegion(Factory::factory('LocaleRegion', null, $sRegion))
->setScript(Factory::factory('LocaleScript'));
} | Generate a Locale object for a language/region
@param string $sLanguage The language to set
@param string $sRegion The region to set
@return \Nails\Common\Factory\Locale
@throws FactoryException |
public function getTableName($bIncludeAlias = false): string
{
$sTable = parent::getTableName() . static::$sLocalisedTableSuffix;
return $bIncludeAlias ? trim($sTable . ' as `' . $this->getTableAlias() . '`') : $sTable;
} | Returns the localised table name
@param bool $bIncludeAlias Whether to include the table alias or not
@return string
@throws ModelException |
protected function generateSlug(string $sLabel, int $iIgnoreId = null, \Nails\Common\Factory\Locale $oLocale = null)
{
if (empty($oLocale)) {
throw new ModelException(
self::class . ': A locale must be defined when generating slugs for a localised item'
);
}
$oDb = Factory::service('Database');
$oDb->start_cache();
$oDb->where('language', $oLocale->getLanguage());
$oDb->where('region', $oLocale->getRegion());
$oDb->stop_cache();
$sSlug = parent::generateSlug($sLabel, $iIgnoreId);
$oDb->flush_cache();
return $sSlug;
} | Generates a unique slug
@param string $sLabel The label from which to generate a slug
@param int $iIgnoreId The ID of an item to ignore
@param \Nails\Common\Factory\Locale $oLocale The locale to restrict the tests against
@return string
@throws ModelException |
public function update($iId, array $aData = [], \Nails\Common\Factory\Locale $oLocale = null): bool
{
if (empty($oLocale)) {
throw new ModelException(
self::class . ': A locale must be defined when updating a localised item'
);
}
unset($aData['locale']);
/**
* Ensure automatic slug generation takes into account locale
*/
if ($this->isAutoSetSlugs() && empty($aData[$this->tableSlugColumn]) && !static::AUTO_SET_SLUG_IMMUTABLE) {
$aData[$this->tableSlugColumn] = $this->generateSlug(
getFromArray($this->tableLabelColumn, $aData),
$iId,
$oLocale
);
}
$oDb = Factory::service('Database');
$oDb->where('language', $oLocale->getLanguage());
$oDb->where('region', $oLocale->getRegion());
return parent::update($iId, $aData);
} | Updates an existing object
@param int $iId The ID of the object to update
@param array $aData The data to update the object with
@param \Nails\Common\Factory\Locale|null $oLocale The locale of the object being updated
@return bool
@throws FactoryException
@throws ModelException |
public function delete($iId, \Nails\Common\Factory\Locale $oLocale = null): bool
{
if (empty($oLocale)) {
throw new ModelException(
self::class . ': A locale must be defined when deleting a localised item'
);
}
/**
* An item can be deleted if any of the following are true:
* - It is the only item
* - It is not the default locale
*/
/** @var Locale $oLocale */
$oLocaleService = Factory::service('Locale');
$oItem = $this->getById($iId, ['USE_LOCALE' => $oLocale]);
if (count($oItem->available_locales) === 1 || $oLocaleService->getDefautLocale() !== $oLocale) {
if ($this->isDestructiveDelete()) {
$bResult = $this->destroy($iId, $oLocale);
} else {
$bResult = $this->update(
$iId,
[$this->tableDeletedColumn => true],
$oLocale
);
}
if ($bResult) {
$this->triggerEvent(static::EVENT_DELETED, [$iId, $oLocale]);
return true;
}
return false;
} elseif (count($oItem->available_locales) > 1 && $oLocaleService->getDefautLocale() === $oLocale) {
throw new ModelException(
'Item cannot be deleted as it is the default item and other items still exist.'
);
} else {
throw new ModelException(
'Item cannot be deleted'
);
}
} | Marks an object as deleted
@param int $iId The ID of the object to mark as deleted
@param \Nails\Common\Factory\Locale|null $oLocale The locale of the object being deleted
@return bool
@throws FactoryException
@throws ModelException |
public function destroy($iId, \Nails\Common\Factory\Locale $oLocale = null): bool
{
if (empty($oLocale)) {
throw new ModelException(
self::class . ': A locale must be defined when deleting a localised item'
);
}
$oDb = Factory::service('Database');
$oDb->where('language', $oLocale->getLanguage());
$oDb->where('region', $oLocale->getRegion());
return parent::destroy($iId);
} | Permanently deletes an object
@param int $iId The ID of the object to destroy
@param \Nails\Common\Factory\Locale|null $oLocale The locale of the item being destroyed
@return bool
@throws FactoryException
@throws ModelException |
public function restore($iId, \Nails\Common\Factory\Locale $oLocale = null): bool
{
if (empty($oLocale)) {
throw new ModelException(
'A locale must be defined when restoring a localised item'
);
}
if ($this->isDestructiveDelete()) {
return null;
} elseif ($this->update($iId, [$this->tableDeletedColumn => false], $oLocale)) {
$this->triggerEvent(static::EVENT_RESTORED, [$iId]);
return true;
}
return false;
} | Unmarks an object as deleted
@param int $iId The ID of the object to restore
@param \Nails\Common\Factory\Locale|null $oLocale The locale of the item being restored
@return bool
@throws FactoryException
@throws ModelException |
public static function siteUrl($sUri, $bUseSecure = false)
{
if (preg_match('/^(https?:\/\/|#)/', $sUri)) {
// Absolute URI; return unaltered
return $sUri;
} else {
if ($bUseSecure && defined('SECURE_BASE_URL')) {
$sBaseUrl = rtrim(SECURE_BASE_URL, '/') . '/';
} else {
$sBaseUrl = rtrim(BASE_URL, '/') . '/';
}
if (is_file($sUri) || is_dir($sUri)) {
return $sBaseUrl . ltrim($sUri, '/');
}
/** @var Locale $oLocale */
$oLocale = Factory::service('Locale');
$sLocale = $oLocale->getUrlSegment($oLocale->get());
$sLocale = $sLocale && $sUri ? $sLocale . '/' : $sLocale;
return $sBaseUrl . $sLocale . ltrim($sUri, '/');
}
} | Prepends BASE_URL or SECURE_BASE_URL to a string
@param string $sUri The URI to append
@param bool $bUseSecure Whether to use BASE_URL or SECURE_BASE_URL
@return string |
public function create(array $aData = [], $bReturnObject = false)
{
$oDb = Factory::service('Database');
$sTable = $this->getTableName();
// --------------------------------------------------------------------------
// Execute the data pre-write hooks
$this
->prepareCreateData($aData)
->prepareWriteData($aData);
// --------------------------------------------------------------------------
// If there are any expandable fields which should automatically save,
// then separate them out now
$aAutoSaveExpandableFields = $this->autoSaveExpandableFieldsExtract($aData);
// --------------------------------------------------------------------------
$this
->setDataTimestamps($aData)
->setDataUsers($aData)
->setDataSlug($aData)
->setDataToken($aData);
// --------------------------------------------------------------------------
if ($this->saveToDb($aData)) {
if (classUses($this, Localised::class)) {
$iId = $aData['id'];
} else {
$iId = $oDb->insert_id();
}
$this->autoSaveExpandableFieldsSave($iId, $aAutoSaveExpandableFields);
$this->triggerEvent(static::EVENT_CREATED, [$iId]);
return $bReturnObject ? $this->getById($iId) : $iId;
} else {
return null;
}
} | Creates a new object
@param array $aData The data to create the object with
@param bool $bReturnObject Whether to return just the new ID or the full object
@return mixed
@throws ModelException |
public function createMany(array $aData)
{
$oDb = Factory::service('Database');
try {
$oDb->trans_begin();
foreach ($aData as $aDatum) {
if (!$this->create($aDatum)) {
throw new ModelException('Failed to create item with data: ' . json_encode($aDatum));
}
}
$oDb->trans_commit();
return true;
} catch (\Exception $e) {
$oDb->trans_rollback();
$this->setError($e->getMessage());
return false;
}
} | Inserts a batch of data into the table
@param array $aData The data to insert
@return bool |
public function update($iId, array $aData = []): bool
{
$sAlias = $this->getTableAlias(true);
$sTable = $this->getTableName(true);
$oDb = Factory::service('Database');
// --------------------------------------------------------------------------
// Execute the data pre-write hooks
$this
->prepareUpdateData($aData)
->prepareWriteData($aData);
// --------------------------------------------------------------------------
// If there are any expandable fields which should automatically save,
// then separate them out now
$aAutoSaveExpandableFields = $this->autoSaveExpandableFieldsExtract($aData);
// --------------------------------------------------------------------------
$this
->setDataTimestamps($aData, false)
->setDataUsers($aData, false)
->setDataSlug($aData, false, $iId)
->setDataToken($aData, false);
// --------------------------------------------------------------------------
if ($this->saveToDb($aData, $iId)) {
// Save any expandable objects
$this->autoSaveExpandableFieldsSave($iId, $aAutoSaveExpandableFields);
// Clear the cache
foreach ($this->aCacheColumns as $sColumn) {
$sKey = strtoupper($sColumn) . ':' . json_encode($iId);
$this->unsetCachePrefix($sKey);
}
$this->triggerEvent(static::EVENT_UPDATED, [$iId]);
return true;
} else {
return false;
}
} | Updates an existing object
@param int $iId The ID of the object to update
@param array $aData The data to update the object with
@return bool
@throws FactoryException
@throws ModelException |
public function updateMany(array $aIds, array $aData = []): bool
{
$oDb = Factory::service('Database');
try {
$oDb->trans_begin();
foreach ($aIds as $iId) {
if (!$this->update($iId, $aData)) {
throw new ModelException('Failed to update item with ID ' . $iId);
}
}
$oDb->trans_commit();
return true;
} catch (\Exception $e) {
$oDb->trans_rollback();
$this->setError($e->getMessage());
return false;
}
} | Update many items with the same data
@param array $aIds An array of IDs to update
@param array $aData The data to set
@return bool
@throws FactoryException
@throws ModelException |
protected function setDataTimestamps(array &$aData, bool $bSetCreated = true): Base
{
if ($this->isAutoSetTimestamps()) {
$oDate = Factory::factory('DateTime');
if ($bSetCreated && empty($aData[$this->tableCreatedColumn])) {
$aData[$this->tableCreatedColumn] = $oDate->format('Y-m-d H:i:s');
}
if (empty($aData[$this->tableModifiedColumn])) {
$aData[$this->tableModifiedColumn] = $oDate->format('Y-m-d H:i:s');
}
}
return $this;
} | Sets the timestamps on the $aData array
@param array $aData The data being passed to the model
@param bool $bSetCreated Whether to set the created timestamp or not
@return $this
@throws FactoryException |
protected function setDataUsers(array &$aData, bool $bSetCreated = true): Base
{
if ($this->isAutoSetUsers()) {
if (isLoggedIn()) {
if ($bSetCreated && empty($aData[$this->tableCreatedByColumn])) {
$aData[$this->tableCreatedByColumn] = activeUser('id');
}
if (empty($aData[$this->tableModifiedByColumn])) {
$aData[$this->tableModifiedByColumn] = activeUser('id');
}
} else {
if ($bSetCreated && empty($aData[$this->tableCreatedByColumn])) {
$aData[$this->tableCreatedByColumn] = null;
}
if (empty($aData[$this->tableModifiedByColumn])) {
$aData[$this->tableModifiedByColumn] = null;
}
}
}
return $this;
} | Set the created/modified user IDs on the $aData array
@param array $aData The data being passed to the model
@param bool $bSetCreated Whether to set the created user or not
@return $this |
protected function setDataSlug(array &$aData, bool $bIsCreate = true, int $iIgnoreId = null): Base
{
if ($this->isAutoSetSlugs() &&
empty($aData[$this->tableSlugColumn]) &&
($bIsCreate || !static::AUTO_SET_SLUG_IMMUTABLE)
) {
if (empty($this->tableSlugColumn)) {
throw new ModelException(static::class . '::create() Slug column variable not set', 1);
}
if (empty($this->tableLabelColumn)) {
throw new ModelException(static::class . '::create() Label column variable not set', 1);
}
if (empty($aData[$this->tableLabelColumn])) {
throw new ModelException(
static::class . '::create() "' . $this->tableLabelColumn .
'" is required when automatically generating slugs.',
1
);
}
$aData[$this->tableSlugColumn] = $this->generateSlug(
$aData[$this->tableLabelColumn],
$iIgnoreId
);
}
return $this;
} | Set the slug on the $aData array
@param array $aData The data being passed to the model
@param bool $bIsCreate Whether the method is being called in a create context or not
@param int $iIgnoreId The ID of an item to ignore
@return $this |
protected function setDataToken(array &$aData, $bIsCreate = true): Base
{
if ($bIsCreate && $this->isAutoSetTokens() && empty($aData[$this->tableTokenColumn])) {
if (empty($this->tableTokenColumn)) {
throw new ModelException(static::class . '::create() Token column variable not set', 1);
}
$aData[$this->tableTokenColumn] = $this->generateToken();
} elseif (!$bIsCreate) {
// Automatically set tokens are permanent and immutable
if ($this->isAutoSetTokens() && !empty($aData[$this->tableTokenColumn])) {
unset($aData[$this->tableTokenColumn]);
}
}
return $this;
} | Set the token on the $aData array
@param array $aData The data being passed to the model
@return $this
@throws ModelException |
protected function saveToDb(array $aData, int $iId = null): bool
{
$oDb = Factory::service('Database');
if (!empty($aData)) {
if (!classUses($this, Localised::class)) {
unset($aData['id']);
}
foreach ($aData as $sColumn => $mValue) {
if (is_array($mValue)) {
$mSetValue = isset($mValue[0]) ? $mValue[0] : null;
$bEscape = isset($mValue[1]) ? (bool) $mValue[1] : true;
$oDb->set($sColumn, $mSetValue, $bEscape);
} else {
$oDb->set($sColumn, $mValue);
}
}
}
if (!$iId) {
$oDb->insert($this->getTableName());
return (bool) $oDb->affected_rows();
} else {
$oDb->where('id', $iId);
return $oDb->update($this->getTableName());
}
} | Commits $aData to the database
@param array $aData the data array
@return bool
@throws FactoryException
@throws ModelException |
public function delete($iId): bool
{
$oItem = $this->getById($iId);
if (empty($oItem)) {
$this->setError('Item does not exist');
return false;
}
if ($this->isDestructiveDelete()) {
$bResult = $this->destroy($iId);
} else {
$bResult = $this->update($iId, [$this->tableDeletedColumn => true]);
}
if ($bResult) {
$this->triggerEvent(static::EVENT_DELETED, [$iId, $oItem]);
}
return $bResult;
} | Marks an object as deleted
If destructive deletion is enabled then this method will permanently
destroy the object. If Non-destructive deletion is enabled then the
$this->tableDeletedColumn field will be set to true.
@param int $iId The ID of the object to mark as deleted
@return bool
@throws FactoryException
@throws ModelException |
public function deleteMany(array $aIds): bool
{
$oDb = Factory::service('Database');
try {
$oDb->trans_begin();
foreach ($aIds as $iId) {
if (!$this->delete($iId)) {
throw new ModelException('Failed to delete item with ID ' . $iId);
}
}
$oDb->trans_commit();
return true;
} catch (\Exception $e) {
$oDb->trans_rollback();
$this->setError($e->getMessage());
return false;
}
} | Deletes many items
@param array $aIds An array of item IDs to delete
@return bool
@throws FactoryException
@throws ModelException |
public function restore($iId): bool
{
if ($this->isDestructiveDelete()) {
return null;
} elseif ($this->update($iId, [$this->tableDeletedColumn => false])) {
$this->triggerEvent(static::EVENT_RESTORED, [$iId]);
return true;
}
return false;
} | Unmarks an object as deleted
If destructive deletion is enabled then this method will return null.
If Non-destructive deletion is enabled then the $this->tableDeletedColumn
field will be set to false.
@param int $iId The ID of the object to restore
@return bool
@throws FactoryException
@throws ModelException |
public function destroy($iId): bool
{
$oDb = Factory::service('Database');
$sTable = $this->getTableName();
// --------------------------------------------------------------------------
$oDb->where('id', $iId);
if ($oDb->delete($sTable)) {
$this->triggerEvent(static::EVENT_DESTROYED, [$iId]);
return true;
}
return false;
} | Permanently deletes an object
This method will attempt to delete the row from the table, regardless of whether
destructive deletion is enabled or not.
@param int $iId The ID of the object to destroy
@return bool
@throws FactoryException
@throws ModelException |
public function getAll($iPage = null, $iPerPage = null, array $aData = [], $bIncludeDeleted = false): array
{
// If the first value is an array then treat as if called with getAll(null, null, $aData);
if (is_array($iPage)) {
$aData = $iPage;
$iPage = null;
}
$oResults = $this->getAllRawQuery($iPage, $iPerPage, $aData, $bIncludeDeleted);
$aResults = $oResults->result();
$iNumResults = count($aResults);
$this->expandExpandableFields($aResults, $aData);
for ($i = 0; $i < $iNumResults; $i++) {
$this->formatObject($aResults[$i], $aData);
}
return $aResults;
} | Fetches all objects and formats them, optionally paginated
@param int|null|array $iPage The page number of the results, if null then no pagination; also accepts an $aData array
@param int|null $iPerPage How many items per page of paginated results
@param mixed $aData Any data to pass to getCountCommon()
@param bool $bIncludeDeleted If non-destructive delete is enabled then this flag allows you to include deleted items
@return Resource[]
@throws ModelException |
public function getAllFlat($iPage = null, $iPerPage = null, array $aData = [], $bIncludeDeleted = false)
{
$aItems = $this->getAll($iPage, $iPerPage, $aData, $bIncludeDeleted);
$aOut = [];
// Nothing returned? Skip the rest of this method, it's pointless.
if (!$aItems) {
return [];
}
// --------------------------------------------------------------------------
// Test columns
$oTest = reset($aItems);
if (!property_exists($oTest, $this->tableLabelColumn)) {
throw new ModelException(
static::class . '::getAllFlat() "' . $this->tableLabelColumn . '" is not a valid column.',
1
);
}
if (!property_exists($oTest, $this->tableLabelColumn)) {
throw new ModelException(
static::class . '::getAllFlat() "' . $this->tableIdColumn . '" is not a valid column.',
1
);
}
unset($oTest);
// --------------------------------------------------------------------------
foreach ($aItems as $oItem) {
$aOut[$oItem->{$this->tableIdColumn}] = $oItem->{$this->tableLabelColumn};
}
return $aOut;
} | Fetches all objects as a flat array
@param int|null $iPage The page number of the results
@param int|null $iPerPage The number of items per page
@param array $aData Any data to pass to getCountCommon()
@param bool $bIncludeDeleted Whether or not to include deleted items
@return array
@throws ModelException |
protected function prepareCacheKey($sColumn, $mValue, array $aData = [])
{
/**
* Remove some elements from the $aData array as they are unlikely to affect the
* _contents_ of an object, only whether it's returned or not. Things like `expand`
* will most likely alter a result so leave them in as identifiers.
*/
$aRemove = [
'where',
'or_where',
'where_in',
'or_where_in',
'where_not_in',
'or_where_not_in',
'like',
'or_like',
'not_like',
'or_not_like',
];
foreach ($aRemove as $sKey) {
unset($aData[$sKey]);
}
$aKey = array_filter([
strtoupper($sColumn),
json_encode($mValue),
$aData !== null ? md5(json_encode($aData)) : null,
]);
return implode(':', $aKey);
} | Formats the key used by the cache, taking into consideration $aData
@param string $sColumn The column name
@param mixed $mValue The value(s)
@param array $aData The data array
@return string |
public function getById($iId, array $aData = [])
{
if (!$this->tableIdColumn) {
throw new ModelException(static::class . '::getById() Column variable not set.', 1);
}
return $this->getByColumn($this->tableIdColumn, $iId, $aData);
} | Fetch an object by it's ID
@param int $iId The ID of the object to fetch
@param mixed $aData Any data to pass to getCountCommon()
@return \stdClass|false
@throws ModelException |
public function getByIds($aIds, array $aData = [], $bMaintainInputOrder = false)
{
if (!$this->tableIdColumn) {
throw new ModelException(static::class . '::getByIds() Column variable not set.', 1);
}
$aItems = $this->getByColumn($this->tableIdColumn, $aIds, $aData, true);
if ($bMaintainInputOrder) {
return $this->sortItemsByColumn($aItems, $aIds, $this->tableIdColumn);
} else {
return $aItems;
}
} | Fetch objects by their IDs
@param array $aIds An array of IDs to fetch
@param mixed $aData Any data to pass to getCountCommon()
@param bool $bMaintainInputOrder Whether to maintain the input order
@return array
@throws ModelException |
public function getBySlug($sSlug, array $aData = [])
{
if (!$this->tableSlugColumn) {
throw new ModelException(static::class . '::getBySlug() Column variable not set.', 1);
}
return $this->getByColumn($this->tableSlugColumn, $sSlug, $aData);
} | Fetch an object by it's slug
@param string $sSlug The slug of the object to fetch
@param array $aData Any data to pass to getCountCommon()
@return \stdClass
@throws ModelException |
public function getBySlugs($aSlugs, array $aData = [], $bMaintainInputOrder = false)
{
if (!$this->tableSlugColumn) {
throw new ModelException(static::class . '::getBySlugs() Column variable not set.', 1);
}
$aItems = $this->getByColumn($this->tableSlugColumn, $aSlugs, $aData, true);
if ($bMaintainInputOrder) {
return $this->sortItemsByColumn($aItems, $aSlugs, $this->tableSlugColumn);
} else {
return $aItems;
}
} | Fetch objects by their slugs
@param array $aSlugs An array of slugs to fetch
@param array $aData Any data to pass to getCountCommon()
@param bool $bMaintainInputOrder Whether to maintain the input order
@return array
@throws ModelException |
public function getByIdOrSlug($mIdSlug, array $aData = [])
{
if (is_numeric($mIdSlug)) {
return $this->getById($mIdSlug, $aData);
} else {
return $this->getBySlug($mIdSlug, $aData);
}
} | Fetch an object by it's id or slug
Auto-detects whether to use the ID or slug as the selector when fetching
an object. Note that this method uses is_numeric() to determine whether
an ID or a slug has been passed, thus numeric slugs (which are against
Nails style guidelines) will be interpreted incorrectly.
@param mixed $mIdSlug The ID or slug of the object to fetch
@param array $aData Any data to pass to getCountCommon()
@return \stdClass |
public function getByToken($sToken, array $aData = [])
{
if (!$this->tableTokenColumn) {
throw new ModelException(static::class . '::getByToken() Column variable not set.', 1);
}
return $this->getByColumn($this->tableTokenColumn, $sToken, $aData);
} | Fetch an object by its token
@param string $sToken The token of the object to fetch
@param array $aData Any data to pass to getCountCommon()
@return \stdClass|null
@throws ModelException if object property tableTokenColumn is not set |
public function getByTokens($aTokens, array $aData = [], $bMaintainInputOrder = false)
{
if (!$this->tableTokenColumn) {
throw new ModelException(static::class . '::getByTokens() Column variable not set.', 1);
}
$aItems = $this->getByColumn($this->tableTokenColumn, $aTokens, $aData, true);
if ($bMaintainInputOrder) {
return $this->sortItemsByColumn($aItems, $aTokens, $this->tableTokenColumn);
} else {
return $aItems;
}
} | Fetch objects by an array of tokens
@param array $aTokens An array of tokens to fetch
@param array $aData Any data to pass to getCountCommon()
@param bool $bMaintainInputOrder Whether to maintain the input order
@return array
@throws ModelException if object property tableTokenColumn is not set |
protected function sortItemsByColumn(array $aItems, array $aInputOrder, $sColumn)
{
$aOut = [];
foreach ($aInputOrder as $sInputItem) {
foreach ($aItems as $oItem) {
if ($oItem->{$sColumn} == $sInputItem) {
$aOut[] = $oItem;
}
}
}
return $aOut;
} | Sorts items into a specific order based on a specific column
@param array $aItems The items to sort
@param array $aInputOrder The order to sort them in
@param string $sColumn The column to sort on
@return array |
protected function getManyAssociatedItems(
array &$aItems,
$sItemProperty,
$sAssociatedItemIdColumn,
$sAssociatedModel,
$sAssociatedModelProvider,
array $aAssociatedModelData = []
) {
if (!empty($aItems)) {
$oAssociatedModel = Factory::model($sAssociatedModel, $sAssociatedModelProvider);
$aItemIds = [];
foreach ($aItems as $oItem) {
// Note the ID
$aItemIds[] = $oItem->id;
// Set the base property
$oItem->{$sItemProperty} = Factory::resource('ExpandableField');
}
if (empty($aAssociatedModelData['where_in'])) {
$aAssociatedModelData['where_in'] = [];
}
$aAssociatedModelData['where_in'][] = [
$oAssociatedModel->getTableAlias() . '.' . $sAssociatedItemIdColumn,
$aItemIds,
];
$aAssociatedItems = $oAssociatedModel->getAll(null, null, $aAssociatedModelData);
foreach ($aItems as $oItem) {
foreach ($aAssociatedItems as $oAssociatedItem) {
if ($oItem->id == $oAssociatedItem->{$sAssociatedItemIdColumn}) {
$oItem->{$sItemProperty}->data[] = $oAssociatedItem;
$oItem->{$sItemProperty}->count++;
}
}
}
}
} | Get associated content for the items in the result set where the the relationship is 1 to many
@param array &$aItems The result set of items
@param string $sItemProperty What property of each item to assign the associated content
@param string $sAssociatedItemIdColumn Which property in the associated content which contains the item's ID
@param string $sAssociatedModel The name of the model which handles the associated content
@param string $sAssociatedModelProvider Which module provides the associated model
@param array $aAssociatedModelData Data to pass to the associated model's getByIds method()
@return void |
protected function countManyAssociatedItems(
array &$aItems,
$sItemProperty,
$sAssociatedItemIdColumn,
$sAssociatedModel,
$sAssociatedModelProvider,
array $aAssociatedModelData = []
) {
if (!empty($aItems)) {
$oAssociatedModel = Factory::model($sAssociatedModel, $sAssociatedModelProvider);
foreach ($aItems as $oItem) {
// Use a new array so as not to impact the original request
$aQueryData = $aAssociatedModelData;
if (empty($aQueryData['where'])) {
$aQueryData['where'] = [];
}
$aQueryData['where'][] = [$sAssociatedItemIdColumn, $oItem->id];
$oItem->{$sItemProperty} = $oAssociatedModel->countAll($aQueryData);
}
}
} | Count associated content for the items in the result set where the the relationship is 1 to many
@param array &$aItems The result set of items
@param string $sItemProperty What property of each item to assign the associated content
@param string $sAssociatedItemIdColumn Which property in the associated content which contains the item's ID
@param string $sAssociatedModel The name of the model which handles the associated content
@param string $sAssociatedModelProvider Which module provides the associated model
@param array $aAssociatedModelData Data to pass to the associated model's getByIds method()
@return void |
public function countAll(array $aData = [], $bIncludeDeleted = false)
{
$oDb = Factory::service('Database');
$table = $this->getTableName(true);
// --------------------------------------------------------------------------
// Apply common items
$this->getCountCommon($aData);
// --------------------------------------------------------------------------
// If non-destructive delete is enabled then apply the delete query
if (!$this->isDestructiveDelete() && !$bIncludeDeleted) {
$oDb->where($this->getTableAlias(true) . $this->tableDeletedColumn, false);
}
// --------------------------------------------------------------------------
return $oDb->count_all_results($table);
} | Counts all objects
@param array $aData An array of data to pass to getCountCommon()
@param bool $bIncludeDeleted Whether to include deleted objects or not
@return int
@throws ModelException |
public function search($sKeywords, $iPage = null, $iPerPage = null, array $aData = [], $bIncludeDeleted = false)
{
// If the second parameter is an array then treat as if called with search($sKeywords, null, null, $aData);
if (is_array($iPage)) {
$aData = $iPage;
$iPage = null;
}
$this->applySearchConditionals($aData, $sKeywords);
return (object) [
'page' => $iPage,
'perPage' => $iPerPage,
'total' => $this->countAll($aData),
'data' => $this->getAll($iPage, $iPerPage, $aData, $bIncludeDeleted),
];
} | Searches for objects, optionally paginated.
@param string $sKeywords The search term
@param int|null $iPage The page number of the results, if null then no pagination
@param int|null $iPerPage How many items per page of paginated results
@param mixed $aData Any data to pass to getCountCommon()
@param bool $bIncludeDeleted If non-destructive delete is enabled then this flag allows you to include
deleted items
@return \stdClass |
protected function applySearchConditionals(array &$aData, $sKeywords)
{
if (empty($aData['or_like'])) {
$aData['or_like'] = [];
}
$sAlias = $this->getTableAlias(true);
foreach ($this->searchableFields as $mField) {
// If the field is an array then search across the columns concatenated together
if (is_array($mField)) {
$sMappedFields = array_map(function ($sInput) use ($sAlias) {
if (strpos($sInput, '.') !== false) {
return $sInput;
} else {
return $sAlias . $sInput;
}
}, $mField);
$aData['or_like'][] = ['CONCAT_WS(" ", ' . implode(',', $sMappedFields) . ')', $sKeywords];
} else {
if (strpos($mField, '.') !== false) {
$aData['or_like'][] = [$mField, $sKeywords];
} else {
$aData['or_like'][] = [$sAlias . $mField, $sKeywords];
}
}
}
} | Mutates the data array and adds the conditionals for searching
@param array $aData
@param $sKeywords |