04.12
php
saved
mariano_iglesias
Note
Modified version of the Slug Behavior that uses more than one field as label to be used when generating a slug.
Modified version of the Slug Behavior that uses more than one field as label to be used when generating a slug.
- <?php
- /**
- * Slug Behavior class file.
- *
- * Model Behavior to support slugs.
- *
- * @filesource
- * @package app
- * @subpackage models.behaviors
- */
- /**
- * Add slug behavior to a model.
- *
- * @author Mariano Iglesias
- * @package app
- * @subpackage models.behaviors
- */
- class SlugBehavior extends ModelBehavior {
- /**
- * Initiate behaviour for the model using specified settings.
- *
- * @param object $model Model using the behaviour
- * @param array $settings Settings to override for model.
- *
- * @access public
- */
- $this->settings[$model->name] = $default;
- }
- }
- $this->settings[$model->name] = array_merge($this->settings[$model->name], ife(is_array($settings), $settings, array()));
- }
- /**
- * Run before a model is saved, used to set up slug for model.
- *
- * @param object $model Model about to be saved.
- *
- * @access public
- * @since 1.0
- */
- function beforeSave(&$model) {
- foreach($this->settings[$model->name]['label'] as $field) {
- if (!$model->hasField($field)) {
- return;
- }
- }
- if ($model->hasField($this->settings[$model->name]['slug'])) {
- $label = '';
- foreach($this->settings[$model->name]['label'] as $field) {
- $label .= $model->data[$model->name][$field];
- }
- return;
- }
- $slug = $this->_slug($label, $this->settings[$model->name]);
- $conditions = array($model->name . '.' . $this->settings[$model->name]['slug'] => 'LIKE ' . $slug . '%');
- $conditions[$model->name . '.' . $model->primaryKey] = '!= ' . $model->{$model->primaryKey};
- }
- $result = $model->findAll($conditions, $model->name . '.*', null, null, 1, 0);
- }
- $begginingSlug = $slug;
- $index = 1;
- while($index > 0) {
- $slug = $begginingSlug . $this->settings[$model->name]['separator'] . $index;
- $index = -1;
- }
- $index++;
- }
- }
- $model->data[$model->name][$this->settings[$model->name]['slug']] = $slug;
- }
- }
- }
- /**
- * Generate a slug for the given strung using specified settings.
- *
- * @param string $string String.
- * @param array $settings Settings to use (looks for 'separator' and 'length')
- *
- * @return string Slug for given string.
- *
- * @access private
- */
- function _slug($string, $settings) {
- $string = preg_replace('/[^a-z0-9' . $settings['separator'] . ']/i', $settings['separator'], $string);
- $string = preg_replace('/' . $settings['separator'] . '[' . $settings['separator'] . ']*/', $settings['separator'], $string);
- }
- return $string;
- }
- }
- ?>
Parsed in 0.227 seconds, using GeSHi 1.0.7.14