Blame view

common/behaviors/Slug.php 2.31 KB
4253cbec   root   first commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
  <?php

  

  namespace common\behaviors;

  

  use yii;

  use yii\base\Behavior;

  use yii\db\ActiveRecord;

  use dosamigos\transliterator\TransliteratorHelper;

  class Slug extends Behavior

  {

      public $in_attribute = 'name';

      public $out_attribute = 'slug';

      public $translit = true;

  

      public function events()

      {

          return [

              ActiveRecord::EVENT_BEFORE_INSERT=> 'getSlug',

              ActiveRecord::EVENT_BEFORE_UPDATE=> 'getSlug'

          ];

      }

  

      public function getSlug( $event )

      {

          if(!empty($this->owner->{$this->in_attribute})){

              if ( empty( $this->owner->{$this->out_attribute} ) ) {

                  $this->owner->{$this->out_attribute} = $this->generateSlug( $this->owner->{$this->in_attribute} );

              } else {

                  $this->owner->{$this->out_attribute} = $this->generateSlug( $this->owner->{$this->out_attribute} );

              }

          }

  

      }

  

      private function generateSlug( $slug )

      {

          $slug = $this->slugify( $slug );

          if ( $this->checkUniqueSlug( $slug ) ) {

              return $slug;

          } else {

              for ( $suffix = 2; !$this->checkUniqueSlug( $new_slug = $slug . '-' . $suffix ); $suffix++ ) {}

              return $new_slug;

          }

      }

  

      private function slugify( $slug )

      {

          if ( $this->translit ) {

              return  yii\helpers\Inflector::slug( TransliteratorHelper::process( $slug ), '-', true );

          } else {

              return $this->slug( $slug, '-', true );

          }

      }

  

      private function slug( $string, $replacement = '-', $lowercase = true )

      {

          $string = preg_replace( '/[^\p{L}\p{Nd}]+/u', $replacement, $string );

          $string = trim( $string, $replacement );

          return $lowercase ? strtolower( $string ) : $string;

      }

  

      private function checkUniqueSlug( $slug )

      {

          $pk = $this->owner->primaryKey();

          $pk = $pk[0];

  

          $condition = $this->out_attribute . ' = :out_attribute';

          $params = [ ':out_attribute' => $slug ];

          if ( !$this->owner->isNewRecord ) {

              $condition .= ' and ' . $pk . ' != :pk';

              $params[':pk'] = $this->owner->{$pk};

          }

  

          return !$this->owner->find()

              ->where( $condition, $params )

              ->one();

      }

  

  }