Completed
Push — master ( 6214df...f7ef88 )
by Igor
03:39
created

SignupProviderForm::savePhoto()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 9
ccs 7
cts 7
cp 1
rs 9.6666
cc 2
eloc 6
nc 2
nop 2
crap 2
1
<?php
2
3
namespace app\models\forms;
4
5
use Yii;
6
use yii\base\DynamicModel;
7
use yii\helpers\FileHelper;
8
use yii\web\UploadedFile;
9
use app\models\User;
10
11
class SignupProviderForm extends \yii\base\Model
12
{
13
    /**
14
     * @var string
15
     */
16
    public $email;
17
    /**
18
     * @var \app\models\User
19
     */
20
    private $user = null;
21
22
    /**
23
     * @param User $user
24
     */
25 8
    public function __construct($user)
26
    {
27 8
        $this->user = $user;
28 8
    }
29
30
    /**
31
     * @inheritdoc
32
     */
33 8
    public function rules()
34
    {
35
        return [
36 8
            ['email', 'filter', 'filter' => 'trim'],
37
            ['email', 'required'],
38
            ['email', 'string', 'max' => 255],
39
            ['email', 'email'],
40 8
            ['email', 'unique',
41 8
                'targetClass' => '\app\models\User',
42 8
                'message' => Yii::t('app.validators', 'This email address has already been taken')
43
            ],
44
        ];
45
    }
46
47
    /**
48
     * @inheritdoc
49
     */
50 7
    public function attributeLabels()
51
    {
52 7
        return (new User())->attributeLabels();
53
    }
54
55
    /**
56
     * Create manually UploadedFile instance by file path
57
     *
58
     * @param string $path file path
59
     * @return UploadedFile
60
     */
61 6
    private function makeUploadedFile($path)
62
    {
63 6
        $tmpFile = tempnam(sys_get_temp_dir(), 'app');
64 6
        file_put_contents($tmpFile, file_get_contents($path));
65
66 6
        $uploadedFile = new UploadedFile();
67 6
        $uploadedFile->name = pathinfo($path, PATHINFO_BASENAME);
68 6
        $uploadedFile->tempName = $tmpFile;
69 6
        $uploadedFile->type = FileHelper::getMimeType($tmpFile);
70 6
        $uploadedFile->size = filesize($tmpFile);
71 6
        $uploadedFile->error = 0;
72
73 6
        return $uploadedFile;
74
    }
75
76
    /**
77
     * Save photo
78
     *
79
     * @param \app\models\UserProfile $profile
80
     * @param string $photo
81
     * @return void
82
     */
83 6
    private function savePhoto($profile, $photo)
84
    {
85 6
        $file = $this->makeUploadedFile($photo);
86 6
        $model = new DynamicModel(compact('file'));
87 6
        $model->addRule('file', 'image', $profile->fileRules('photo', true))->validate();
0 ignored issues
show
Documentation Bug introduced by
The method fileRules does not exist on object<app\models\UserProfile>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
88 6
        if (!$model->hasErrors()) {
89 5
            $profile->createFile('photo', $file->tempName, $model->file->name);
0 ignored issues
show
Documentation Bug introduced by
The method createFile does not exist on object<app\models\UserProfile>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
90
        }
91 6
    }
92
93
    /**
94
     * Signs user up
95
     *
96
     * @param bool $checkExistEmail
97
     * @return \app\models\User
98
     */
99 8
    public function signup($checkExistEmail = true)
100
    {
101 8
        if ($this->validate($checkExistEmail ? null : [])) {
102 6
            $this->user->email = $this->email;
103
104 6
            $profile = $this->user->profile;
0 ignored issues
show
Documentation introduced by
The property profile does not exist on object<app\models\User>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
105 6
            if ($profile->isNewRecord && !empty($profile->photo)) {
106 6
                $this->savePhoto($profile, $profile->photo);
107
            }
108
109 6
            if ($this->user->save()) {
110 6
                if ($this->user->authorize(true)) {
111 6
                    return $this->user;
112
                }
113
            } // @codeCoverageIgnore
114
        } // @codeCoverageIgnore
115
116 2
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by app\models\forms\SignupProviderForm::signup of type app\models\User.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
117
    }
118
119
    /**
120
     * Sends an email with a link, for confirm the email
121
     *
122
     * @return boolean
123
     */
124 5
    public function sendEmail()
125
    {
126 5
        if (!User::isTokenValid($this->user->email_confirm_token)) {
127 5
            $this->user->generateEmailConfirmToken();
128 5
            $this->user->updateAttributes([
129 5
                'email_confirm_token' => $this->user->email_confirm_token,
130 5
                'date_confirm' => $this->user->date_confirm,
131
            ]);
132
        }
133
134 5
        return Yii::$app->notify->sendMessage(
135 5
            $this->email,
136 5
            Yii::t('app', 'Activate Your Account'),
137 5
            'emailConfirmToken',
138 5
            ['user' => $this->user]
139
        );
140
    }
141
}
142