Example #1
0
 /**
  * Creates the slug for entity being flushed
  * 
  * @param EntityManager $em
  * @param object $entity
  * @param mixed $changeSet
  *      case array: the change set array
  *      case boolean(false): entity is not managed
  * @throws Sluggable\Exception if parameters are missing
  *      or invalid
  * @return void
  */
 protected function _generateSlug(EntityManager $em, $entity, $changeSet)
 {
     $entityClass = get_class($entity);
     $uow = $em->getUnitOfWork();
     $meta = $em->getClassMetadata($entityClass);
     $config = $this->getConfiguration($em, $entityClass);
     // collect the slug from fields
     $slug = '';
     $needToChangeSlug = false;
     foreach ($config['fields'] as $sluggableField) {
         if ($changeSet === false || isset($changeSet[$sluggableField])) {
             $needToChangeSlug = true;
         }
         $slug .= $meta->getReflectionProperty($sluggableField)->getValue($entity) . ' ';
     }
     // if slug is not changed, no need further processing
     if (!$needToChangeSlug) {
         return;
         // nothing to do
     }
     if (!strlen(trim($slug))) {
         throw Exception::slugIsEmpty();
     }
     // build the slug
     $slug = call_user_func_array(array('Gedmo\\Sluggable\\Util\\Urlizer', 'urlize'), array($slug, $config['separator'], $entity));
     // stylize the slug
     switch ($config['style']) {
         case 'camel':
             $slug = preg_replace_callback('@^[a-z]|' . $config['separator'] . '[a-z]@smi', create_function('$m', 'return strtoupper($m[0]);'), $slug);
             break;
         default:
             // leave it as is
             break;
     }
     // cut slug if exceeded in length
     $mapping = $meta->getFieldMapping($config['slug']);
     if (strlen($slug) > $mapping['length']) {
         $slug = substr($slug, 0, $mapping['length']);
     }
     // make unique slug if requested
     if ($config['unique'] && !$uow->hasPendingInsertions()) {
         // set the slug for further processing
         $meta->getReflectionProperty($config['slug'])->setValue($entity, $slug);
         $slug = $this->_makeUniqueSlug($em, $entity);
     }
     // set the final slug
     $meta->getReflectionProperty($config['slug'])->setValue($entity, $slug);
     // recompute changeset if entity is managed
     if ($changeSet !== false) {
         $uow->recomputeSingleEntityChangeSet($meta, $entity);
     } elseif ($config['unique'] && $uow->hasPendingInsertions()) {
         // @todo: make support for unique field metadata on concurrent operations
         if ($meta->isUniqueField($config['slug'])) {
             throw Exception::slugFieldIsUnique($config['slug']);
         }
         $this->_pendingEntities[] = $entity;
     }
 }