|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace ProAI\Inheritance; |
| 4 | + |
| 5 | +use Illuminate\Support\Str; |
| 6 | + |
| 7 | +trait Inheritance |
| 8 | +{ |
| 9 | + /** |
| 10 | + * Defines the column name for use with single table inheritance. |
| 11 | + * |
| 12 | + * @var string |
| 13 | + */ |
| 14 | + public static $inheritanceColumn = 'type'; |
| 15 | + |
| 16 | + /** |
| 17 | + * Defines the type name for use with single table inheritance. |
| 18 | + * |
| 19 | + * @var mixed |
| 20 | + */ |
| 21 | + public static $inheritanceType; |
| 22 | + |
| 23 | + /** |
| 24 | + * Bootstrap the inheritance trait. |
| 25 | + * |
| 26 | + * @return void |
| 27 | + */ |
| 28 | + protected static function bootInheritance() |
| 29 | + { |
| 30 | + if (! static::modelInherited()) { |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + static::addGlobalScope(function ($query) { |
| 35 | + $query->where(static::$inheritanceColumn, static::getInheritanceType()); |
| 36 | + }); |
| 37 | + |
| 38 | + static::creating(function ($model) { |
| 39 | + $model->{static::$inheritanceColumn} = static::getInheritanceType(); |
| 40 | + }); |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Check if model is inherited. |
| 45 | + * |
| 46 | + * @return bool |
| 47 | + */ |
| 48 | + protected static function modelInherited() |
| 49 | + { |
| 50 | + return self::class !== static::class; |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Get the column name for use with single table inheritance. |
| 55 | + * |
| 56 | + * @return mixed |
| 57 | + */ |
| 58 | + protected static function getInheritanceType() |
| 59 | + { |
| 60 | + if (isset(static::$inheritanceType)) { |
| 61 | + return static::$inheritanceType; |
| 62 | + } |
| 63 | + |
| 64 | + return static::$inheritanceType = static::class; |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * Get the table associated with the model. |
| 69 | + * |
| 70 | + * @return string |
| 71 | + */ |
| 72 | + public function getTable() |
| 73 | + { |
| 74 | + return $this->table ?? Str::snake(Str::pluralStudly(class_basename($this->getRootClass()))); |
| 75 | + } |
| 76 | + |
| 77 | + /** |
| 78 | + * Get the default foreign key name for the model. |
| 79 | + * |
| 80 | + * @return string |
| 81 | + */ |
| 82 | + public function getForeignKey() |
| 83 | + { |
| 84 | + return Str::snake(class_basename($this->getRootClass())).'_'.$this->getKeyName(); |
| 85 | + } |
| 86 | + |
| 87 | + /** |
| 88 | + * Get the class name of the root class. |
| 89 | + * |
| 90 | + * @return string |
| 91 | + */ |
| 92 | + protected function getRootClass() |
| 93 | + { |
| 94 | + return self::class; |
| 95 | + } |
| 96 | +} |
0 commit comments