Enh: Added PolymorphicRelation::strict to throw exceptions when accessing invalid polymorphic relations

This commit is contained in:
buddh4 2018-07-31 14:08:18 +02:00
parent efb7a5d41e
commit 0c777b63af
4 changed files with 17 additions and 0 deletions

View File

@ -15,6 +15,7 @@ use Yii;
use yii\base\Behavior; use yii\base\Behavior;
use yii\db\ActiveRecord; use yii\db\ActiveRecord;
use yii\db\BaseActiveRecord; use yii\db\BaseActiveRecord;
use Yii\db\IntegrityException;
/** /**
* PolymorphicRelations behavior provides simple support for polymorphic relations in ActiveRecords. * PolymorphicRelations behavior provides simple support for polymorphic relations in ActiveRecords.
@ -34,6 +35,11 @@ class PolymorphicRelation extends Behavior
*/ */
public $pkAttribute = 'object_id'; public $pkAttribute = 'object_id';
/**
* @var boolean if set to true an exception is thrown if `object_model` and `object_id` is set but does not exist
*/
public $strict = false;
/** /**
* @var array the related object needs to be a "instanceof" at least one of these given classnames * @var array the related object needs to be a "instanceof" at least one of these given classnames
*/ */
@ -60,6 +66,10 @@ class PolymorphicRelation extends Behavior
$this->owner->getAttribute($this->pkAttribute) $this->owner->getAttribute($this->pkAttribute)
); );
if($this->strict && !$object && !empty($this->classAttribute) && !empty($this->pkAttribute)) {
throw new IntegrityException('Call to an inconsistent polymorphic relation detected on '.get_class($this->owner).' ('.$this->classAttribute.' : '.$this->pkAttribute.')');
}
if ($object !== null && $this->validateUnderlyingObjectType($object)) { if ($object !== null && $this->validateUnderlyingObjectType($object)) {
$this->_cached = $object; $this->_cached = $object;
return $object; return $object;

View File

@ -1,6 +1,11 @@
HumHub Change Log HumHub Change Log
================= =================
1.3.0
-----------------------------
- Enh: Added `PolymorphicRelation::strict` to throw exceptions when accessing invalid polymorphic relations
1.3.0-beta.3 (July 30, 2018) 1.3.0-beta.3 (July 30, 2018)
----------------------------- -----------------------------

View File

@ -54,6 +54,7 @@ class Activity extends ContentActiveRecord
return [ return [
[ [
'class' => PolymorphicRelation::class, 'class' => PolymorphicRelation::class,
'strict' => true,
'mustBeInstanceOf' => [ 'mustBeInstanceOf' => [
ActiveRecord::class, ActiveRecord::class,
] ]

View File

@ -51,6 +51,7 @@ class Notification extends \humhub\components\ActiveRecord
'class' => PolymorphicRelation::class, 'class' => PolymorphicRelation::class,
'classAttribute' => 'source_class', 'classAttribute' => 'source_class',
'pkAttribute' => 'source_pk', 'pkAttribute' => 'source_pk',
'strict' => true,
'mustBeInstanceOf' => [ 'mustBeInstanceOf' => [
\yii\db\ActiveRecord::class, \yii\db\ActiveRecord::class,
], ],