setSource('password_link'); $this->useDynamicUpdate(true); // Relationships $this->belongsTo('user_id', User::class, 'id', array('alias' => 'User')); // Behaviour $this->addBehavior(new RandomIdBehavior(array( 'field' => 'public_id', 'length' => 12, 'expression' => '(password IS NULL OR HOUR(TIMEDIFF(date, NOW())) = 0)' ))); $this->addBehavior(new SoftDelete([ 'field' => 'password', 'value' => null ])); } /** * @return int */ public function getId() { return $this->id; } /** * @param int $id * @return PasswordLink */ public function setId(int $id) : PasswordLink { $this->id = $id; return $this; } /** * @return string */ public function getPublicId() { return $this->public_id; } /** * @param string $public_id * @return PasswordLink */ public function setPublicId(string $public_id) : PasswordLink { $this->public_id = $public_id; return $this; } /** * @return int */ public function getUserId() { return $this->user_id; } /** * @param int $user_id * @return PasswordLink */ public function setUserId(int $user_id) : PasswordLink { $this->user_id = $user_id; return $this; } /** * @return string */ public function getPassword() { return $this->password; } /** * @param string $password * @return PasswordLink */ public function setPassword(string $password) : PasswordLink { $this->password = $password; return $this; } /** * Has the link been used? * * @return bool */ public function isUsed() : bool { return strlen($this->password) < 1; } /** * Is the link still valid? * * @return bool */ public function isValid() : bool { // Used links are not valid. if ($this->isUsed()) { return false; } $date = new \DateTime($this->date); $now = new \DateTime(); // Get the differerence in hours. $diff = $now->format('U') - $date->format('U'); $diff = ($diff / 60) / 60; // Only valid for an hour. return $diff >= 0 && $diff <= 1; } public function beforeCreate() { // Creating a new link automatically removes old ones. $links = self::find(["user_id = ?0", 'bind' => [ $this->user_id ]]); foreach($links as $link) { $link->delete(); } } }