Skip to content

Commit

Permalink
Initial Commit
Browse files Browse the repository at this point in the history
Version 1
  • Loading branch information
itssamtaylor committed Apr 8, 2017
0 parents commit d630bde
Show file tree
Hide file tree
Showing 8 changed files with 338 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2016 taylornetwork

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# ModelSlugger

## Credits

- Main Author: [Sam Taylor][link-author]

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

[link-author]: https://github.com/taylornetwork
20 changes: 20 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "taylornetwork/model-slugger",
"description": "Automatically add slugs to eloquent models",
"require": {
"php": ">=5.4.0",
"laravel/framework": "5.4.*",
"cocur/slugify": "^2.3"
},
"authors": [
{
"name": "Sam Taylor",
"email": "[email protected]"
}
],
"autoload": {
"psr-4": {
"TaylorNetwork\\ModelSlugger\\": "src/"
}
}
}
86 changes: 86 additions & 0 deletions src/ModelSlugger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

namespace TaylorNetwork\ModelSlugger;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

trait ModelSlugger
{
/**
* Attach observer
*/
public static function bootModelSlugger ()
{
static::observe(SluggerObserver::class);
}

/**
* Allow for implicit route model binding if set.
*
* @see Model::getRouteKeyName()
* @return mixed
*/
public function getRouteKeyName()
{
if (isset($this->sluggerRouteModelBind) && $this->sluggerRouteModelBind)
{
if (isset($this->sluggerConfig()['column']))
{
return $this->sluggerConfig()['column'];
}
return config('slugger.defaults.column');
}
return parent::getRouteKeyName();
}

/**
* Find similar slugs with the same parents
*
* @param Builder $query
* @param Model $model
* @param $config
* @param $slug
* @param null $parent_column
* @return mixed
*/
public function scopeParentSimilarSlugs (Builder $query, Model $model, $config, $slug, $parent_column = null)
{
if ($parent_column === null)
{
if (!isset($config['parentColumn']) || $config['parentColumn'] === null)
{
$parent_column = strtolower(class_basename($config['parent'])) . '_' . (new $config['parent'])->getKeyName();
}
else
{
$parent_column = $config['parentColumn'];
}
}

return $query->where($parent_column, $model->$parent_column)->similarSlugs($config, $slug);
}

/**
* Find similar slugs
*
* @param Builder $query
* @param $config
* @param $slug
* @return Builder|static
*/
public function scopeSimilarSlugs (Builder $query, $config, $slug)
{
return $query->where($config['column'], $slug)->orWhere($config['column'], 'LIKE', $slug . $config['separator'] . '%');
}

/**
* Slugger config
*
* Minimum:
* return [ 'source' => 'sourceField' ];
*
* @return mixed
*/
abstract public function sluggerConfig();
}
32 changes: 32 additions & 0 deletions src/ServiceProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace TaylorNetwork\ModelSlugger;

use Illuminate\Support\ServiceProvider as BaseProvider;

class ServiceProvider extends BaseProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/config/slugger.php' => config_path('slugger.php'),
]);
}

/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/config/slugger.php', 'slugger'
);
}
}
140 changes: 140 additions & 0 deletions src/Slugger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
<?php

namespace TaylorNetwork\ModelSlugger;

use Illuminate\Database\Eloquent\Model;
use Cocur\Slugify\Slugify;

class Slugger
{
/**
* @var Model
*/
protected $model;

/**
* Slugger Config
*
* @var array
*/
protected $config;

/**
* Slug generator engine
*
* @var object
*/
protected $generator;

/**
* Slug generator method to call
*
* @var string
*/
protected $method;

/**
* Slugger constructor.
*
* @param Model $model
*/
public function __construct(Model $model)
{
$this->model = $model;
$this->config = $model->sluggerConfig() + config('slugger.defaults');
$this->generator = new Slugify([ 'separator' => $this->getConfig('separator') ]);
$this->method = 'slugify';
}

/**
* Generate slug for model
*/
public function slug ()
{
$slug = $this->buildSlug($this->model->{$this->getConfig('source')});
$this->saveSlug($slug);
}

/**
* Build the slug
*
* @param $text
* @return string
*/
public function buildSlug($text)
{
return $this->makeUnique($this->generator->{$this->method}($text));
}

/**
* Make slug unique either with all slugs, similar parents, or not at all
*
* @param $slug
* @return string
*/
public function makeUnique($slug)
{
switch (strtolower($this->getConfig('unique')))
{
case 'parent':
$total = count($this->model->newQuery()->parentSimilarSlugs($this->model, $this->getConfig(), $slug)->get());
return $this->appendIfNeeded($slug, $total);
break;
case 'all':
$total = count($this->model->newQuery()->similarSlugs($this->getConfig(), $slug)->get());
return $this->appendIfNeeded($slug, $total);
break;
}
return $slug;
}

/**
* Append a number to make slug unique if needed
*
* @param $slug
* @param $total
* @return string
*/
public function appendIfNeeded($slug, $total)
{
if ($total > 0)
{
return $slug . $this->getConfig('separator') . $total;
}
return $slug;
}

/**
* Save the slug to the model
*
* @param $slug
*/
public function saveSlug($slug)
{
$this->model->setAttribute($this->getConfig('column'), $slug);
}


/**
* Get config
*
* @param mixed $key
* @return mixed
*/
public function getConfig($key = null)
{
switch(gettype($key))
{
case 'string':
return $this->config[$key];
break;
case 'array':
return array_only($this->config, $key);
break;
case 'object':
return array_only($this->config, (array) $key);
break;
}
return $this->config;
}
}
18 changes: 18 additions & 0 deletions src/SluggerObserver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace TaylorNetwork\ModelSlugger;

use Illuminate\Database\Eloquent\Model;

class SluggerObserver
{
/**
* On model saving, add slug.
*
* @param Model $model
*/
public function saving(Model $model)
{
(new Slugger($model))->slug();
}
}
10 changes: 10 additions & 0 deletions src/config/slugger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

return [

'defaults' => [
'unique' => 'none',
'column' => 'slug',
'separator' => '-',
],
];

0 comments on commit d630bde

Please sign in to comment.