Skip to content

Instantly share code, notes, and snippets.

@msamgan
Created February 21, 2019 10:18
Show Gist options
  • Save msamgan/9716c8c2439e7a1b104545d203f1be66 to your computer and use it in GitHub Desktop.
Save msamgan/9716c8c2439e7a1b104545d203f1be66 to your computer and use it in GitHub Desktop.
Slug creating behavior CakePhp 3.x
<?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