Bristol SU Support Package
ModuleInstance.php
Go to the documentation of this file.
1 <?php
2 
4 
21 
25 class ModuleInstance extends Model implements ModuleInstanceContract
26 {
27  use HasRevisions;
28 
34  protected $fillable = [
35  'alias',
36  'activity_id',
37  'name',
38  'slug',
39  'description',
40  'active',
41  'visible',
42  'mandatory',
43  'completion_condition_instance_id',
44  'enabled',
45  'user_id',
46  'order',
47  'grouping_id'
48  ];
49 
55  protected $casts = [
56  'enabled' => 'boolean'
57  ];
58 
64  public function __construct(array $attributes = [])
65  {
66  parent::__construct($attributes);
67  self::creating(function($model) {
68  if ($model->slug === null) {
69  $model->slug = Str::slug($model->name);
70  }
71  if($model->user_id === null && ($user = app(UserAuthentication::class)->getUser()) !== null) {
72  $model->user_id = $user->controlId();
73  }
74  });
75  }
76 
82  public function alias()
83  {
84  return $this->alias;
85  }
86 
92  public function id()
93  {
94  return $this->id;
95  }
96 
102  public function activity()
103  {
104  return $this->belongsTo(Activity::class);
105  }
106 
112  public function moduleInstanceSettings()
113  {
114  return $this->hasMany(ModuleInstanceSetting::class);
115  }
116 
122  public function moduleInstancePermissions()
123  {
124  return $this->hasMany(ModuleInstancePermission::class);
125  }
126 
132  public function completionConditionInstance()
133  {
134  return $this->belongsTo(CompletionConditionInstance::class);
135  }
136 
142  public function activeLogic()
143  {
144  return $this->belongsTo(Logic::class, 'active');
145  }
146 
152  public function visibleLogic()
153  {
154  return $this->belongsTo(Logic::class, 'visible');
155  }
156 
162  public function mandatoryLogic()
163  {
164  return $this->belongsTo(Logic::class, 'mandatory');
165  }
166 
171  public function actionInstances()
172  {
173  return $this->hasMany(ActionInstance::class);
174  }
175 
181  public function moduleInstanceServices()
182  {
183  return $this->hasMany(ModuleInstanceService::class);
184  }
185 
193  public function setting($key, $default = null)
194  {
195  try {
196  return $this->moduleInstanceSettings()->where('key', $key)->firstOrFail()->value;
197  } catch (ModelNotFoundException $e) {
198  return $default;
199  }
200  }
201 
209  public function scopeEnabled(Builder $query)
210  {
211  return $query->where('enabled', true);
212  }
213 
220  public function user(): \BristolSU\ControlDB\Contracts\Models\User
221  {
222  if($this->user_id === null) {
223  throw new \Exception(sprintf('Module Instance #%u is not owned by a user.', $this->id));
224  }
225  return app(User::class)->getById($this->user_id);
226  }
227 
228  public function grouping()
229  {
230  return $this->belongsTo(ModuleInstanceGrouping::class);
231  }
232 }