/**
  * @param BaseElementModel $element
  * @param $data
  *
  * @return null|CategoryModel
  */
 private function prepareAncestorsForElement(BaseElementModel $element, $data)
 {
     $parentCategory = null;
     $data = $this->freshenString($data);
     // Don't connect empty fields
     if (!empty($data)) {
         // This we append before the slugified path
         $categoryUrl = str_replace('{slug}', '', $element->getUrlFormat());
         // Find matching element by URI (dirty, not all categories have URI's)
         $criteria = craft()->elements->getCriteria(ElementType::Category);
         $criteria->groupId = $element->groupId;
         $criteria->uri = $categoryUrl . craft()->import->slugify($data);
         $criteria->limit = 1;
         $parentCategory = $criteria->first();
     }
     return $parentCategory;
 }
 /**
  * Sets the URI on an element using a given URL format, tweaking its slug if necessary to ensure it's unique.
  *
  * @param BaseElementModel $element
  *
  * @throws Exception
  */
 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.'));
 }