Created
February 21, 2019 10:18
-
-
Save msamgan/9716c8c2439e7a1b104545d203f1be66 to your computer and use it in GitHub Desktop.
Slug creating behavior CakePhp 3.x
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Model\Behavior; | |
use Cake\Datasource\EntityInterface; | |
use Cake\Event\Event; | |
use Cake\ORM\Behavior; | |
use Cake\Utility\Inflector; | |
use Cake\ORM\Table; | |
/** | |
* Slug behavior | |
*/ | |
class SlugBehavior extends Behavior | |
{ | |
/** | |
* Default configuration. | |
* | |
* @var array | |
*/ | |
protected $_defaultConfig = []; | |
/** | |
* @param string $string | |
* @param bool $edit | |
* @param bool $oldSlug | |
* @return string | |
*/ | |
public function slug($string = '', $edit = false, $oldSlug = false) | |
{ | |
if (empty($string)) { | |
$string = 'unique-slug'; | |
} | |
if (!$edit) { | |
return strtolower(Inflector::slug($string)) . "-" . time(); | |
} | |
return strtolower(Inflector::slug($string)) . "-" . @end(explode('-', $oldSlug)); | |
} | |
/** | |
* @param Event $event | |
* @param EntityInterface $entity | |
*/ | |
public function beforeSave(Event $event, EntityInterface $entity) | |
{ | |
if (empty($entity->slug)) { | |
$slug = $this->slug($entity->name); | |
} else { | |
$slug = $this->slug( | |
$entity->name, | |
true, | |
$entity->slug | |
); | |
} | |
$entity->set(compact('slug')); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment