Просмотр исходного кода

Subject setIdentity(): check is instance of identity class

Fabian Peter Hammerle 8 лет назад
Родитель
Сommit
b430402f5f
3 измененных файлов с 34 добавлено и 3 удалено
  1. 11 2
      Subject.php
  2. 1 1
      composer.json
  3. 22 0
      tests/SubjectTest.php

+ 11 - 2
Subject.php

@@ -66,8 +66,17 @@ class Subject extends \yii\db\ActiveRecord
         if($identity === null) {
             $this->identity_id = null;
         } else {
-            // @see \yii\web\IdentityInterface::getId()
-            $this->identity_id = $identity->getId();
+            $cls = self::getIdentityClass();
+            if($identity instanceof $cls) {
+                // @see \yii\web\IdentityInterface::getId()
+                $this->identity_id = $identity->getId();
+            } else {
+                throw new \TypeError(sprintf(
+                    "expected instance of %s,\n%s given",
+                    $cls,
+                    get_class($identity)
+                ));
+            }
         }
 
         // TODO: update related record

+ 1 - 1
composer.json

@@ -12,7 +12,7 @@
         "yiisoft/yii2": "^2.0"
     },
     "require-dev": {
-        "phpunit/phpunit": "4.8.*",
+        "phpunit/phpunit": "5.1.*",
         "fphammerle/helpers": "^1.2"
     },
     "autoload": {

+ 22 - 0
tests/SubjectTest.php

@@ -6,6 +6,15 @@ use \fphammerle\helpers\ArrayHelper;
 use \fphammerle\yii2\auth\clientcert\Subject;
 use \fphammerle\yii2\auth\clientcert\migrations;
 
+class DummyUser implements \yii\web\IdentityInterface
+{
+    public static function findIdentity($id) {}
+    public static function findIdentityByAccessToken($token, $type = null) {}
+    public function getId() {}
+    public function getAuthKey() {}
+    public function validateAuthKey($authKey) {}
+}
+
 class SubjectTest extends TestCase
 {
     protected $alice;
@@ -88,4 +97,17 @@ class SubjectTest extends TestCase
         $s->identity = null;
         $this->assertNull($s->identity_id);
     }
+
+    public function testSetIdentityInvalidType()
+    {
+        $s = new Subject;
+        $this->setExpectedException(\TypeError::class);
+        $s->identity = new DummyUser;
+    }
+
+    public function testConstructInvalidType()
+    {
+        $this->setExpectedException(\TypeError::class);
+        new Subject(new DummyUser);
+    }
 }