Last active
November 16, 2019 04:50
-
-
Save rilwanfit/e7693614ce68bdd505111b02b43a9df7 to your computer and use it in GitHub Desktop.
Use this class to practise TDD and refactoring the code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class User | |
{ | |
private $userId; | |
private $firstName; | |
private $lastName; | |
private $email; | |
private $password; | |
private $salt; | |
public function __construct(array $options) | |
{ | |
foreach ($options as $key => $value) { | |
if (property_exists($this, $key)) { | |
$this->{$key} = $value; | |
} | |
} | |
} | |
public function createPassword() | |
{ | |
$this->salt = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 15); | |
$this->password = sha1($this->password . $this->salt); | |
} | |
public function verifyPassword($password) | |
{ | |
return ($this->password === sha1($password . $this->salt)); | |
} | |
public function isInputValid() | |
{ | |
if (empty($this->firstName) || empty($this->lastName) || empty($this->email) || empty($this->password) || ! filter_var($this->email, FILTER_VALIDATE_EMAIL)) { | |
return false; | |
} | |
return true; | |
} | |
private function sendActivationEmail() | |
{ | |
global $config; | |
$email = new \Util\Mail($config); | |
$email->setEmailFrom($config->email); | |
$email->setEmailTo($this->email); | |
$email->setTitle('Your account has been activated'); | |
$email->setBody("Dear {$this->firstName}\n Your account has been activated\n"); | |
$email->send(); | |
} | |
public function createUser() | |
{ | |
global $config; | |
if (!$this->isInputValid()) { | |
return false; | |
} | |
$this->createPassword(); | |
$db = $config->db; | |
/* @var $db \PDO */ | |
$sql = "INSERT INTO users(firstname) VALUES (:firstname)"; | |
$statement = $db->prepare($sql); | |
$statement->bindParam(':firstname', $this->firstName); | |
if ($statement->execute()) { | |
$this->userId = $db->lastInsertId(); | |
$this->sendActivationEmail(); | |
return true; | |
} else { | |
throw new \Exception(implode(':', $statement->errorInfo())); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment