Enh: Implemented generic ContentContainerActiveRecord::is() function

This commit is contained in:
buddh4 2020-09-15 16:47:39 +02:00
parent 0b1a936a0b
commit 3387242179
3 changed files with 83 additions and 16 deletions

View File

@ -154,6 +154,24 @@ abstract class ContentContainerActiveRecord extends ActiveRecord
return static::findOne(['guid' => $token]);
}
/**
* Compares this container with the given $container instance. If the $container is null this function will always
* return false. Null values are accepted in order to safely enable calls as `$user->is(Yii::$app->user->getIdentity())`
* which would otherwise fail in case of guest users.
*
* @param ContentContainerActiveRecord|null $container
* @return bool
* @since 1.7
*/
public function is(ContentContainerActiveRecord $container = null)
{
if (!$container || !($container instanceof self)) {
return false;
}
return $container->contentcontainer_id === $this->contentcontainer_id;
}
/**
* @inheritdoc
*/

View File

@ -0,0 +1,65 @@
<?php
/**
* @link https://www.humhub.org/
* @copyright Copyright (c) 2017 HumHub GmbH & Co. KG
* @license https://www.humhub.com/licences
*
*/
namespace tests\codeception\unit\modules\content;
use humhub\modules\user\models\User;
use tests\codeception\_support\HumHubDbTestCase;
use humhub\modules\space\models\Space;
use Yii;
class ContentContainerActiveRecordTest extends HumHubDbTestCase
{
public function testUserIsNotASpace()
{
$user = User::findOne(['id' => 1]);
$space = Space::findOne(['id' => 2]);
$this->assertFalse($user->is($space));
}
public function testSpaceIsSameSpace()
{
$space = Space::findOne(['id' => 1]);
$space1 = Space::findOne(['id' => 1]);
$this->assertTrue($space->is($space1));
}
public function testUserIsNotAnotherUser()
{
$user = User::findOne(['id' => 1]);
$user2 = User::findOne(['id' => 2]);
$this->assertFalse($user->is($user2));
}
public function testUserIsSameUser()
{
$user = User::findOne(['id' => 1]);
$user1 = User::findOne(['id' => 1]);
$this->assertTrue($user->is($user1));
}
public function testGuestISNotUser()
{
$user = User::findOne(['id' => 1]);
$this->assertFalse($user->is(Yii::$app->user->getIdentity()));
}
public function testNullISNotUser()
{
$space = Space::findOne(['id' => 1]);
$this->assertFalse($space->is(null));
}
}

View File

@ -618,22 +618,6 @@ class User extends ContentContainerActiveRecord implements IdentityInterface, Se
return $this->is(Yii::$app->user->getIdentity());
}
/**
* Checks if the given $user instance shares the same identity with this
* user instance.
*
* @param \humhub\modules\user\models\User $user
* @return boolean
*/
public function is(User $user = null)
{
if (!$user) {
return false;
}
return $user->id === $this->id;
}
/**
* @inheritdoc
*/