diff --git a/lib/Doctrine/Template/Listener/Sluggable.php b/lib/Doctrine/Template/Listener/Sluggable.php new file mode 100644 index 000000000..b7913f15b --- /dev/null +++ b/lib/Doctrine/Template/Listener/Sluggable.php @@ -0,0 +1,94 @@ +. + */ + +/** + * Doctrine_Template_Listener_Sluggable + * + * Easily create a slug for each record based on a specified set of fields + * + * @package Doctrine + * @subpackage Template + * @license http://www.opensource.org/licenses/lgpl-license.php LGPL + * @link www.phpdoctrine.com + * @since 1.0 + * @version $Revision$ + * @author Konsta Vesterinen + */ +class Doctrine_Template_Listener_Sluggable extends Doctrine_Record_Listener +{ + /** + * Array of timestampable options + * + * @var string + */ + protected $_options = array('name' => 'slug', + 'type' => 'clob', + 'length' => null, + 'options' => array(), + 'columns' => array()); + + /** + * __construct + * + * @param string $array + * @return void + */ + public function __construct(array $options) + { + $this->_options = array_merge($options, $this->_options); + } + + public function preInsert(Doctrine_Event $event) + { + $name = $this->_options['name']; + + $record = $event->getInvoker(); + + $record->$name = $this->buildSlug($record); + } + + protected function buildSlug($record) + { + if (empty($this->_columns)) { + $value = (string) $record; + } else { + $value = ''; + foreach ($this->_columns as $column) { + $value = $record->$column . ' '; + } + } + + $value = trim($value); + $value = strtolower($value); + + // strip all non word chars + $value = preg_replace('/\W/', ' ', $value); + + // replace all white space sections with a dash + $value = preg_replace('/\ +/', '-', $value); + + // trim dashes + $value = preg_replace('/\-$/', '', $value); + $value = preg_replace('/^\-/', '', $value); + + return $value; + } +} diff --git a/lib/Doctrine/Timestampable/Listener.php b/lib/Doctrine/Template/Listener/Timestampable.php similarity index 100% rename from lib/Doctrine/Timestampable/Listener.php rename to lib/Doctrine/Template/Listener/Timestampable.php