diff --git a/src/Model/Behavior/SluggableBehavior.php b/src/Model/Behavior/SluggableBehavior.php index 23da73d..d054d78 100644 --- a/src/Model/Behavior/SluggableBehavior.php +++ b/src/Model/Behavior/SluggableBehavior.php @@ -6,6 +6,7 @@ use Cake\ORM\Entity; use Cake\ORM\Query; use Cake\Utility\Inflector; +use Cake\Utility\Text; class SluggableBehavior extends Behavior { @@ -19,6 +20,7 @@ class SluggableBehavior extends Behavior 'field' => 'title', 'slug' => 'slug', 'replacement' => '-', + 'maxLength' => false, ]; /** @@ -32,6 +34,9 @@ public function slug(Entity $entity) { $config = $this->config(); $value = $entity->get($config['field']); + if ($config['maxLength'] > 0) { + $value = Text::truncate($value, $config['maxLength'], ['ellipsis' => '']); + } $entity->set($config['slug'], strtolower(Inflector::slug($value, $config['replacement']))); } diff --git a/tests/TestCase/Model/Behavior/SluggableBehaviorTest.php b/tests/TestCase/Model/Behavior/SluggableBehaviorTest.php index 731c630..4550099 100644 --- a/tests/TestCase/Model/Behavior/SluggableBehaviorTest.php +++ b/tests/TestCase/Model/Behavior/SluggableBehaviorTest.php @@ -24,7 +24,8 @@ public function setUp() { $this->Model = TableRegistry::get('Users'); $this->Model->addBehavior('Xety/Cake3Sluggable.Sluggable', [ - 'field' => 'username' + 'field' => 'username', + 'maxLength' => 5, ]); } @@ -68,6 +69,6 @@ public function testBeforeSave() $after = $this->Model->get(1); $this->assertEquals('mariano', $before->slug); - $this->assertEquals('larry-page', $after->slug); + $this->assertEquals('larry', $after->slug); } }