daily pastebin goal
21%
SHARE
TWEET

Untitled

a guest Feb 24th, 2019 61 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. namespace App\Model\Behavior;
  3.  
  4. use Cake\Datasource\EntityInterface;
  5. use Cake\Event\Event;
  6. use Cake\ORM\Behavior;
  7. use Cake\Utility\Inflector;
  8. use Cake\ORM\Table;
  9.  
  10. /**
  11.  * Slug behavior
  12.  */
  13. class SlugBehavior extends Behavior
  14. {
  15.  
  16.     /**
  17.      * Default configuration.
  18.      *
  19.      * @var array
  20.      */
  21.     protected $_defaultConfig = [];
  22.  
  23.     /**
  24.      * @param string $string
  25.      * @param bool $edit
  26.      * @param bool $oldSlug
  27.      * @return string
  28.      */
  29.     public function slug($string = '', $edit = false, $oldSlug = false)
  30.     {
  31.         if (empty($string)) {
  32.             $string = 'unique-slug';
  33.         }
  34.  
  35.         if (!$edit) {
  36.             return strtolower(Inflector::slug($string)) . "-" . time();
  37.         }
  38.  
  39.         return strtolower(Inflector::slug($string)) . "-" . @end(explode('-', $oldSlug));
  40.     }
  41.  
  42.     /**
  43.      * @param Event $event
  44.      * @param EntityInterface $entity
  45.      */
  46.     public function beforeSave(Event $event, EntityInterface $entity)
  47.     {
  48.         if (empty($entity->slug)) {
  49.             $slug = $this->slug($entity->name);
  50.         } else {
  51.             $slug = $this->slug(
  52.                 $entity->name,
  53.                 true,
  54.                 $entity->slug
  55.             );
  56.         }
  57.  
  58.         $entity->set(compact('slug'));
  59.     }
  60. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top