ElementHelper

Packagecraft.app.helpers
NamespaceCraft
Inheritanceclass ElementHelper
Since2.0
Source Codecraft/app/helpers/ElementHelper.php

Class ElementHelper

Public Methods #

MethodDescriptionDefined By
createSlug()Creates a slug based on a given string.ElementHelper
doesUrlFormatHaveSlugTag()Returns whether a given URL format has a proper {slug} tag.ElementHelper
getEditableLocaleIdsForElement()Returns the editable locale IDs for a given element, taking user locale permissions into account.ElementHelper
isElementEditable()Returns whether the given element is editable by the current user, taking user locale permissions into account.ElementHelper
setNextPrevOnElements()Given an array of elements, will go through and set the appropriate "next" and "prev" elements on them.ElementHelper
setUniqueUri()Sets the URI on an element using a given URL format, tweaking its slug if necessary to ensure it's unique.ElementHelper
setValidSlug()Sets a valid slug on a given element.ElementHelper

Method Details #

createSlug() #

public static function createSlug($str)
{
     // Remove HTML tags
     $str = StringHelper::stripHtml($str);

     // Convert to kebab case
     $glue = craft()->config->get('slugWordSeparator');
     $lower = !craft()->config->get('allowUppercaseInSlug');
     $str = StringHelper::toKebabCase($str, $glue, $lower, false);

     return $str;
}
$strstring
Returnsstring

Creates a slug based on a given string.

doesUrlFormatHaveSlugTag() #

public static function doesUrlFormatHaveSlugTag($urlFormat)
{
     $element = (object) array('slug' => StringHelper::randomString());
     $uri = craft()->templates->renderObjectTemplate($urlFormat, $element);

     return (strpos($uri, $element->slug) !== false);
}
$urlFormatstring
Returnsbool

Returns whether a given URL format has a proper {slug} tag.

getEditableLocaleIdsForElement() #

public static function getEditableLocaleIdsForElement(BaseElementModel $element)
{
     $localeIds = array();

     if ($element->isEditable())
     {
          if (craft()->isLocalized())
          {
               foreach ($element->getLocales() as $localeId => $localeInfo)
               {
                    if (is_numeric($localeId) && is_string($localeInfo))
                    {
                         $localeId = $localeInfo;
                    }

                    if (craft()->userSession->checkPermission('editLocale:'.$localeId))
                    {
                         $localeIds[] = $localeId;
                    }
               }
          }
          else
          {
               $localeIds[] = craft()->i18n->getPrimarySiteLocaleId();
          }
     }

     return $localeIds;
}
$elementBaseElementModel
Returnsarray

Returns the editable locale IDs for a given element, taking user locale permissions into account.

isElementEditable() #

public static function isElementEditable(BaseElementModel $element)
{
     if ($element->isEditable())
     {
          if (craft()->isLocalized())
          {
               foreach ($element->getLocales() as $localeId => $localeInfo)
               {
                    if (is_numeric($localeId) && is_string($localeInfo))
                    {
                         $localeId = $localeInfo;
                    }

                    if (craft()->userSession->checkPermission('editLocale:'.$localeId))
                    {
                         return true;
                    }
               }
          }
          else
          {
               return true;
          }
     }

     return false;
}
$elementBaseElementModel
Returnsbool

Returns whether the given element is editable by the current user, taking user locale permissions into account.

setNextPrevOnElements() #

public static function setNextPrevOnElements($elements)
{
     /** @var BaseElementModel $lastElement */
     $lastElement = null;

     foreach ($elements as $i => $element)
     {
          if ($lastElement)
          {
               $lastElement->setNext($element);
               $element->setPrev($lastElement);
          }
          else
          {
               $element->setPrev(false);
          }

          $lastElement = $element;
     }

     if ($lastElement)
     {
          $lastElement->setNext(false);
     }
}
$elementsarrayThe array of elements.

Given an array of elements, will go through and set the appropriate "next" and "prev" elements on them.

setUniqueUri() #

public static function setUniqueUri(BaseElementModel $element)
{
     $urlFormat = $element->getUrlFormat();

     // No URL format, no URI.
     if (!$urlFormat)
     {
          $element->uri  = null;
          return;
     }

     // No slug, or a URL format with no {slug}, just parse the URL format and get on with our lives
     if (!$element->slug || !static::doesUrlFormatHaveSlugTag($urlFormat))
     {
          $element->uri = craft()->templates->renderObjectTemplate($urlFormat, $element);
          return;
     }

     $uniqueUriConditions = array('and',
          'locale = :locale',
          'uri = :uri'
     );

     $uniqueUriParams = array(
          ':locale' => $element->locale
     );

     if ($element->id)
     {
          $uniqueUriConditions[] = 'elementId != :elementId';
          $uniqueUriParams[':elementId'] = $element->id;
     }

     $slugWordSeparator = craft()->config->get('slugWordSeparator');
     $maxSlugIncrement = craft()->config->get('maxSlugIncrement');

     for ($i = 0; $i < $maxSlugIncrement; $i++)
     {
          $testSlug = $element->slug;

          if ($i > 0)
          {
               $testSlug .= $slugWordSeparator.$i;
          }

          $originalSlug = $element->slug;
          $element->slug = $testSlug;

          $testUri = craft()->templates->renderObjectTemplate($urlFormat, $element);

          // Make sure we're not over our max length.
          if (strlen($testUri) > 255)
          {
               // See how much over we are.
               $overage = strlen($testUri) - 255;

               // Do we have anything left to chop off?
               if (strlen($overage) > strlen($element->slug) - strlen($slugWordSeparator.$i))
               {
                    // Chop off the overage amount from the slug
                    $testSlug = $element->slug;
                    $testSlug = substr($testSlug, 0, strlen($testSlug) - $overage);

                    // Update the slug
                    $element->slug = $testSlug;

                    // Let's try this again.
                    $i -= 1;
                    continue;
               }
               else
               {
                    // We're screwed, blow things up.
                    throw new Exception(Craft::t('The maximum length of a URI is 255 characters.'));
               }
          }

          $uniqueUriParams[':uri'] = $testUri;

          $totalElements = craft()->db->createCommand()
               ->select('count(id)')
               ->from('elements_i18n')
               ->where($uniqueUriConditions, $uniqueUriParams)
               ->queryScalar();

          if ($totalElements ==  0)
          {
               // OMG!
               $element->slug = $testSlug;
               $element->uri = $testUri;
               return;
          }
          else
          {
               $element->slug = $originalSlug;
          }
     }

     throw new Exception(Craft::t('Could not find a unique URI for this element.'));
}
$elementBaseElementModel

Sets the URI on an element using a given URL format, tweaking its slug if necessary to ensure it's unique.

setValidSlug() #

public static function setValidSlug(BaseElementModel $element)
{
     $slug = $element->slug;

     if (!$slug)
     {
          // Create a slug for them, based on the element's title.
          // Replace periods, underscores, and hyphens with spaces so they get separated with the slugWordSeparator
          // to mimic the default JavaScript-based slug generation.
          $slug = str_replace(array('.', '_', '-'), ' ', $element->title);

          // Enforce the limitAutoSlugsToAscii config setting
          if (craft()->config->get('limitAutoSlugsToAscii'))
          {
               $slug = StringHelper::asciiString($slug);
          }
     }

     $element->slug = static::createSlug($slug);
}
$elementBaseElementModel

Sets a valid slug on a given element.