diff --git a/controller/Account/CheckUsernameController.php b/controller/Account/CheckUsernameController.php index 96692f8acd848c41b88815b8aed07d5633a5aa9e..88180510884939be729feaa00b6ca0f3d19a3402 100644 --- a/controller/Account/CheckUsernameController.php +++ b/controller/Account/CheckUsernameController.php @@ -1,39 +1,39 @@ -<?php -namespace JLAS\Book\Controller\Account; -use \JLAS\Book\Controller\BaseController; -use \JLAS\Book\Model as Model; -use \JLAS\Book\Entity as Entity; - -class CheckUsernameController extends BaseController { - - /** - * Get the data needed for this controller. - * @return array data passed to the view. - */ - protected function run($params) { - if ($this->useArgs('username')) { - $valid = Entity\AccountEntity::isUsernameValid($this->getArg('username')); - if (!$valid['valid']) { - $this->setResponse(200, $valid['message']); - return false; - } - $model_account = new Model\AccountModel(); - $user = $model_account->findByID($this->getArg('username')); - if (isset($user)) { - // User already exists. - $this->setResponse(200, "Username {$this->getArg('username')} is not available."); - return false; - } else { - // User doesn't exists. - $this->setResponse(200); - return true; - } - } else { - $this->setResponse(400); - return false; - } - } - -} - +<?php +namespace JLAS\Book\Controller\Account; +use \JLAS\Book\Controller\BaseController; +use \JLAS\Book\Model as Model; +use \JLAS\Book\Entity as Entity; + +class CheckUsernameController extends BaseController { + + /** + * Get the data needed for this controller. + * @return array data passed to the view. + */ + protected function run($params) { + if ($this->useArgs('username')) { + $valid = Entity\AccountEntity::isUsernameValid($this->getArg('username')); + if (!$valid['valid']) { + $this->setResponse(200, $valid['message']); + return false; + } + $model_account = new Model\AccountModel(); + $user = $model_account->findByID($this->getArg('username')); + if (isset($user)) { + // User already exists. + $this->setResponse(200, "Username {$this->getArg('username')} is not available."); + return false; + } else { + // User doesn't exists. + $this->setResponse(200); + return true; + } + } else { + $this->setResponse(400); + return false; + } + } + +} + ?> \ No newline at end of file diff --git a/controller/Account/LoginController.php b/controller/Account/LoginController.php index eec0265cf0db5d57cf6244c65f6769db65c2729d..848c7e9c50c586539e278f4520a14687a5bb04a7 100644 --- a/controller/Account/LoginController.php +++ b/controller/Account/LoginController.php @@ -1,76 +1,76 @@ -<?php -namespace JLAS\Book\Controller\Account; -use \JLAS\Book\Controller\BaseController; -use \JLAS\Book\Model as Model; -use \JLAS\Book\Entity as Entity; - -class LoginController extends BaseController { - - public static $TokenDuration = "1 days"; - - /** - * Generate access token. - */ - public static function generateAccessToken($username, $length = 20) { - $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; - $charactersLength = strlen($characters); - $randomString = ''; - for ($i = 0; $i < $length; $i++) { - $randomString .= $characters[rand(0, $charactersLength - 1)]; - } - return hash('md5', base64_encode($username . $randomString)); - } - - /** - * Get the data needed for this controller. - * @return array data passed to the view. - */ - protected function run($params) { - if ($this->useArgs('username', 'password')) { - $model_account = new Model\AccountModel(); - $model_token = new Model\TokenModel(); - $user = $model_account->findByID($this->getArg('username')); - $token = $model_token->findByID($this->getArg('username')); - if (isset($this->token, $token)) { - // Test if the access-token is valid. - if ($token->validate($this->token)) { - $token->expiry = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' + ' . LoginController::$TokenDuration)); - $model_token->update($token); - $this->setResponse(200, "Already logged in"); - return $token->asArray(); - } - } - if (isset($user)) { - if ($user->password === $this->getArg('password')) { - $this->setResponse(200, "Logged in"); - // Do logging in. - if (isset($token)) { - // Update current token. - $token->token = LoginController::generateAccessToken($user->username); - $token->expiry = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' + ' . LoginController::$TokenDuration)); - $model_token->update($token); - } else { - // Create a new token. - $token = new Entity\TokenEntity(array( - "username" => $user->username, - "access-token" => LoginController::generateAccessToken($user->username), - "expiry" => date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' + ' . LoginController::$TokenDuration)) - )); - $model_token->create($token); - } - return $token->asArray(); - } else { - $this->setResponse(401, "Invalid username/password."); - return $this->getArg('username'); - } - } else { - $this->setResponse(401, "Invalid username/password."); - return $this->getArg('username'); - } - } - $this->setResponse(400); - } - -} - +<?php +namespace JLAS\Book\Controller\Account; +use \JLAS\Book\Controller\BaseController; +use \JLAS\Book\Model as Model; +use \JLAS\Book\Entity as Entity; + +class LoginController extends BaseController { + + public static $TokenDuration = "1 days"; + + /** + * Generate access token. + */ + public static function generateAccessToken($username, $length = 20) { + $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + $charactersLength = strlen($characters); + $randomString = ''; + for ($i = 0; $i < $length; $i++) { + $randomString .= $characters[rand(0, $charactersLength - 1)]; + } + return hash('md5', base64_encode($username . $randomString)); + } + + /** + * Get the data needed for this controller. + * @return array data passed to the view. + */ + protected function run($params) { + if ($this->useArgs('username', 'password')) { + $model_account = new Model\AccountModel(); + $model_token = new Model\TokenModel(); + $user = $model_account->findByID($this->getArg('username')); + $token = $model_token->findByID($this->getArg('username')); + if (isset($this->token, $token)) { + // Test if the access-token is valid. + if ($token->validate($this->token)) { + $token->expiry = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' + ' . LoginController::$TokenDuration)); + $model_token->update($token); + $this->setResponse(200, "Already logged in"); + return $token->asArray(); + } + } + if (isset($user)) { + if ($user->password === $this->getArg('password')) { + $this->setResponse(200, "Logged in"); + // Do logging in. + if (isset($token)) { + // Update current token. + $token->token = LoginController::generateAccessToken($user->username); + $token->expiry = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' + ' . LoginController::$TokenDuration)); + $model_token->update($token); + } else { + // Create a new token. + $token = new Entity\TokenEntity(array( + "username" => $user->username, + "access-token" => LoginController::generateAccessToken($user->username), + "expiry" => date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' + ' . LoginController::$TokenDuration)) + )); + $model_token->create($token); + } + return $token->asArray(); + } else { + $this->setResponse(401, "Invalid username/password."); + return $this->getArg('username'); + } + } else { + $this->setResponse(401, "Invalid username/password."); + return $this->getArg('username'); + } + } + $this->setResponse(400); + } + +} + ?> \ No newline at end of file diff --git a/controller/Account/RegisterController.php b/controller/Account/RegisterController.php index a485639870cac6dc400ba700fb2e1f8baa16bbc6..da6f83ab0a68dd8e2a08672f894303dce1c8193e 100644 --- a/controller/Account/RegisterController.php +++ b/controller/Account/RegisterController.php @@ -1,72 +1,72 @@ -<?php -namespace JLAS\Book\Controller\Account; -use \JLAS\Book\Controller\BaseController; -use \JLAS\Book\Model as Model; -use \JLAS\Book\Entity as Entity; - -class RegisterController extends BaseController { - - /** - * Get the data needed for this controller. - * @return array data passed to the view. - */ - protected function run($params) { - if ($this->useArgs('username', 'password', 'name', 'email', 'address', 'phone')) { - $model_account = new Model\AccountModel(); - $model_biodata = new Model\BiodataModel(); - $user = $model_account->findByID($this->getArg('username')); - $biodata = $model_biodata->where()->field('email')->equals($this->getArg('email'))->finish(); - if (isset($user)) { - // User already exists. - $this->setResponse(700, "Username {$this->getArg('username')} already exists"); - return; - } else { - $biodata = new Entity\GenericEntity(array( - "username" => $this->getArg('username'), - "name" => $this->getArg('name'), - "email" => $this->getArg('email'), - "address" => $this->getArg('address'), - "phone" => $this->getArg('phone'), - )); - try { - // Create user. - $user = new Entity\AccountEntity(array( - "username" => $this->getArg('username'), - "password" => $this->getArg('password') - )); - } catch (Entity\InvalidValueException $e) { - $this->setResponse(400, $e->getMessage()); - return; - } - $model_account->create($user); - $model_biodata->create($biodata); - - $model_token = new Model\TokenModel(); - $token = $model_token->findByID($this->getArg('username')); - - if (isset($token)) { - // Update current token. - $token->token = LoginController::generateAccessToken($user->username); - $token->expiry = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' + ' . LoginController::$TokenDuration)); - $model_token->update($token); - } else { - // Create a new token. - $token = new Entity\TokenEntity(array( - "username" => $user->username, - "access-token" => LoginController::generateAccessToken($user->username), - "expiry" => date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' + ' . LoginController::$TokenDuration)) - )); - $model_token->create($token); - } - $this->setResponse(200, "User {$this->getArg('username')} created"); - return $token->asArray(); - } - } else { - $this->setResponse(400); - return; - } - } - -} - +<?php +namespace JLAS\Book\Controller\Account; +use \JLAS\Book\Controller\BaseController; +use \JLAS\Book\Model as Model; +use \JLAS\Book\Entity as Entity; + +class RegisterController extends BaseController { + + /** + * Get the data needed for this controller. + * @return array data passed to the view. + */ + protected function run($params) { + if ($this->useArgs('username', 'password', 'name', 'email', 'address', 'phone')) { + $model_account = new Model\AccountModel(); + $model_biodata = new Model\BiodataModel(); + $user = $model_account->findByID($this->getArg('username')); + $biodata = $model_biodata->where()->field('email')->equals($this->getArg('email'))->finish(); + if (isset($user)) { + // User already exists. + $this->setResponse(700, "Username {$this->getArg('username')} already exists"); + return; + } else { + $biodata = new Entity\GenericEntity(array( + "username" => $this->getArg('username'), + "name" => $this->getArg('name'), + "email" => $this->getArg('email'), + "address" => $this->getArg('address'), + "phone" => $this->getArg('phone'), + )); + try { + // Create user. + $user = new Entity\AccountEntity(array( + "username" => $this->getArg('username'), + "password" => $this->getArg('password') + )); + } catch (Entity\InvalidValueException $e) { + $this->setResponse(400, $e->getMessage()); + return; + } + $model_account->create($user); + $model_biodata->create($biodata); + + $model_token = new Model\TokenModel(); + $token = $model_token->findByID($this->getArg('username')); + + if (isset($token)) { + // Update current token. + $token->token = LoginController::generateAccessToken($user->username); + $token->expiry = date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' + ' . LoginController::$TokenDuration)); + $model_token->update($token); + } else { + // Create a new token. + $token = new Entity\TokenEntity(array( + "username" => $user->username, + "access-token" => LoginController::generateAccessToken($user->username), + "expiry" => date('Y-m-d H:i:s', strtotime(date('Y-m-d H:i:s') . ' + ' . LoginController::$TokenDuration)) + )); + $model_token->create($token); + } + $this->setResponse(200, "User {$this->getArg('username')} created"); + return $token->asArray(); + } + } else { + $this->setResponse(400); + return; + } + } + +} + ?> \ No newline at end of file diff --git a/controller/BaseController.php b/controller/BaseController.php index 376807a26b4ae8ebf7421eef4a1356129639cef9..743e4e199678cc3b9e6f73ffe5548aa80c6cf54c 100644 --- a/controller/BaseController.php +++ b/controller/BaseController.php @@ -1,140 +1,140 @@ -<?php -namespace JLAS\Book\Controller; -use JLAS\Book\Model as Model; - -abstract class BaseController { - - protected $data; - /** - * Override response_code and response_message. - * Defaults at 200 OK - */ - protected $response = array( - "code" => 200 - ); - - private $authenticated = null; - private $username = null; - - function __construct($views, $params=null) { - $this->params = $params; - if (isset($params, $params['cookie'], $params['cookie']['access-token'])) { - $this->token = $params['cookie']['access-token']; - } else { - $this->token = null; - } - $this->path = $this->params['path']; - $this->method = $this->params['method']; - $this->cookie = $this->params['cookie']; - $this->data = $this->run($params); - $this->loadView($views); - } - - /** - * @return string the name of the currently logged in user if logged in; otherwise null. - */ - protected function getUsername() { - if ($this->isAuthenticated()) { - return $this->username; - } - return null; - } - - /** - * @return boolean true if the request is an authenticated one; otherwise false. - */ - protected function isAuthenticated() { - if (isset($this->token)) { - if (isset($this->authenticated)) { - return $this->authenticated; - } else { - $model_token = new Model\TokenModel(); - $token = $model_token->where()->field('access-token')->equals($this->token)->finish(); - if (count($token) > 0) { - $this->username = $token[0]->username; - return $this->authenticated = $token[0]->validate($this->token); - } else { - return $this->authenticated = false; - } - } - } - return false; - } - - /** - * Set the response status of this controller. - * @param int $code the status code of the response. - * @param string $message message to pass along. - */ - protected function setResponse($code, $message="") { - $this->response["code"] = $code; - if (!empty($message)) { - $this->response["message"] = $message; - } - } - - /** - * Array of views to be loaded with this controller. - * @param array $views array of path to view's file (.php). - */ - protected function loadView($views) { - ob_start(); - $data = $this->data; - $response = $this->response; - $names = explode('\\', get_class($this)); - $controller = array_pop($names); - foreach ($views as $view) { - include $view; - } - $content = ob_get_contents(); - ob_end_clean(); - $this->content = $content; - return $this->content; - } - - public function out() { - return $this->content; - } - - /** - * Get the data needed for this controller. - * @return array data passed to the view. - */ - protected abstract function run($params); - - /** - * Use a set of arguments. - * Arguments are passed via $params as 'data'. - * @return boolean true if all arguments exist; otherwise false. - */ - protected function useArgs(...$names) { - $valid = true; - foreach ($names as $name) { - if (!$this->hasArg($name)) { - $valid = false; - $this->response["message"] = "Missing parameter $name"; - break; - } - } - return $valid; - } - - /** - * @param string $name the name of the argument. - * @return boolean true if the argument exists; otherwise false. - */ - protected function hasArg($name) { - return isset($this->params, $this->params['data'],$this->params['data'][$name]); - } - - /** - * @param string $name the name of the argument. - * @return mixed the value of the argument. - */ - protected function getArg($name) { - return $this->params['data'][$name]; - } - -} - +<?php +namespace JLAS\Book\Controller; +use JLAS\Book\Model as Model; + +abstract class BaseController { + + protected $data; + /** + * Override response_code and response_message. + * Defaults at 200 OK + */ + protected $response = array( + "code" => 200 + ); + + private $authenticated = null; + private $username = null; + + function __construct($views, $params=null) { + $this->params = $params; + if (isset($params, $params['cookie'], $params['cookie']['access-token'])) { + $this->token = $params['cookie']['access-token']; + } else { + $this->token = null; + } + $this->path = $this->params['path']; + $this->method = $this->params['method']; + $this->cookie = $this->params['cookie']; + $this->data = $this->run($params); + $this->loadView($views); + } + + /** + * @return string the name of the currently logged in user if logged in; otherwise null. + */ + protected function getUsername() { + if ($this->isAuthenticated()) { + return $this->username; + } + return null; + } + + /** + * @return boolean true if the request is an authenticated one; otherwise false. + */ + protected function isAuthenticated() { + if (isset($this->token)) { + if (isset($this->authenticated)) { + return $this->authenticated; + } else { + $model_token = new Model\TokenModel(); + $token = $model_token->where()->field('access-token')->equals($this->token)->finish(); + if (count($token) > 0) { + $this->username = $token[0]->username; + return $this->authenticated = $token[0]->validate($this->token); + } else { + return $this->authenticated = false; + } + } + } + return false; + } + + /** + * Set the response status of this controller. + * @param int $code the status code of the response. + * @param string $message message to pass along. + */ + protected function setResponse($code, $message="") { + $this->response["code"] = $code; + if (!empty($message)) { + $this->response["message"] = $message; + } + } + + /** + * Array of views to be loaded with this controller. + * @param array $views array of path to view's file (.php). + */ + protected function loadView($views) { + ob_start(); + $data = $this->data; + $response = $this->response; + $names = explode('\\', get_class($this)); + $controller = array_pop($names); + foreach ($views as $view) { + include $view; + } + $content = ob_get_contents(); + ob_end_clean(); + $this->content = $content; + return $this->content; + } + + public function out() { + return $this->content; + } + + /** + * Get the data needed for this controller. + * @return array data passed to the view. + */ + protected abstract function run($params); + + /** + * Use a set of arguments. + * Arguments are passed via $params as 'data'. + * @return boolean true if all arguments exist; otherwise false. + */ + protected function useArgs(...$names) { + $valid = true; + foreach ($names as $name) { + if (!$this->hasArg($name)) { + $valid = false; + $this->response["message"] = "Missing parameter $name"; + break; + } + } + return $valid; + } + + /** + * @param string $name the name of the argument. + * @return boolean true if the argument exists; otherwise false. + */ + protected function hasArg($name) { + return isset($this->params, $this->params['data'],$this->params['data'][$name]); + } + + /** + * @param string $name the name of the argument. + * @return mixed the value of the argument. + */ + protected function getArg($name) { + return $this->params['data'][$name]; + } + +} + ?> \ No newline at end of file diff --git a/controller/Image/GetImageController.php b/controller/Image/GetImageController.php index a3d91261b09dcafe3984d4e30ff74ac666090a5c..41fecdbc97b0e4e8e7021e04550192b17fe1ec32 100644 --- a/controller/Image/GetImageController.php +++ b/controller/Image/GetImageController.php @@ -1,31 +1,31 @@ -<?php -namespace JLAS\Book\Controller\Image; -use \JLAS\Book\Controller\BaseController; -use \JLAS\Book\Model as Model; -use \JLAS\Book\Entity as Entity; - -class GetImageController extends BaseController { - - /** - * Get the data needed for this controller. - * @return array data passed to the view. - */ - protected function run($params) { - if ($this->useArgs('id')) { - $model_image = new Model\ImageModel(); - $image = $model_image->findByID($this->getArg('id')); - if (isset($image)) { - $this->setResponse(200); - return $image->asArray(); - } else { - $this->setResponse(400, "Invalid image id"); - return null; - } - } - $this->setResponse(400); - return null; - } - -} - +<?php +namespace JLAS\Book\Controller\Image; +use \JLAS\Book\Controller\BaseController; +use \JLAS\Book\Model as Model; +use \JLAS\Book\Entity as Entity; + +class GetImageController extends BaseController { + + /** + * Get the data needed for this controller. + * @return array data passed to the view. + */ + protected function run($params) { + if ($this->useArgs('id')) { + $model_image = new Model\ImageModel(); + $image = $model_image->findByID($this->getArg('id')); + if (isset($image)) { + $this->setResponse(200); + return $image->asArray(); + } else { + $this->setResponse(400, "Invalid image id"); + return null; + } + } + $this->setResponse(400); + return null; + } + +} + ?> \ No newline at end of file diff --git a/entity/AccountEntity.php b/entity/AccountEntity.php index 8b91d9c3ba1975b890b957315710a5b052b70507..b13024ae6c428a96123da216846780e6cdf43950 100644 --- a/entity/AccountEntity.php +++ b/entity/AccountEntity.php @@ -1,57 +1,57 @@ -<?php -namespace JLAS\Book\Entity; - -class AccountEntity extends BaseEntity { - - /** - * Username of the account. - */ - public $username; - - /** - * Password of the account. - */ - public $password; - - /** - * Load this entity from an associative array. - * @param $data data in which the entity is loaded from. - */ - public function load($data) { - $this->username = BaseEntity::get($data, "username", ['JLAS\\Book\\Entity\\AccountEntity', 'isUsernameValid']); - $this->password = BaseEntity::get($data, "password", ['JLAS\\Book\\Entity\\AccountEntity', 'isPasswordValid']); - } - - /** - * Returns entity as associative array. - * @return array - */ - public function asArray() { - return array( - "username" => $this->username, - "password" => $this->password - ); - } - - public static function isUsernameValid($username) { - if (strlen($username) < 5) { - return array("valid"=>false, "message"=>"Username length must be greater than or equal to 5."); - } - if (!preg_match('/^\w+$/', $username)) { - return array("valid"=>false, "message"=>"Invalid username {$username}."); - } - return array("valid"=>true); - } - - public static function isPasswordValid($password) { - if (strlen($password) < 6) { - return array("valid"=>false, "message"=>"Password length must be a minimal of 6."); - } - if (!preg_match('/^\w+$/', $password)) { - return array("valid"=>false, "message"=>"Illegal character in password."); - } - return array("valid"=>true); - } -} - +<?php +namespace JLAS\Book\Entity; + +class AccountEntity extends BaseEntity { + + /** + * Username of the account. + */ + public $username; + + /** + * Password of the account. + */ + public $password; + + /** + * Load this entity from an associative array. + * @param $data data in which the entity is loaded from. + */ + public function load($data) { + $this->username = BaseEntity::get($data, "username", ['JLAS\\Book\\Entity\\AccountEntity', 'isUsernameValid']); + $this->password = BaseEntity::get($data, "password", ['JLAS\\Book\\Entity\\AccountEntity', 'isPasswordValid']); + } + + /** + * Returns entity as associative array. + * @return array + */ + public function asArray() { + return array( + "username" => $this->username, + "password" => $this->password + ); + } + + public static function isUsernameValid($username) { + if (strlen($username) < 5) { + return array("valid"=>false, "message"=>"Username length must be greater than or equal to 5."); + } + if (!preg_match('/^\w+$/', $username)) { + return array("valid"=>false, "message"=>"Invalid username {$username}."); + } + return array("valid"=>true); + } + + public static function isPasswordValid($password) { + if (strlen($password) < 6) { + return array("valid"=>false, "message"=>"Password length must be a minimal of 6."); + } + if (!preg_match('/^\w+$/', $password)) { + return array("valid"=>false, "message"=>"Illegal character in password."); + } + return array("valid"=>true); + } +} + ?> \ No newline at end of file diff --git a/entity/BaseEntity.php b/entity/BaseEntity.php index 7ddc1a7dc4704dab11c1a8d47b3324b9d7719552..d23ddbe804c937619bd57627f06fbd5621a2b6be 100644 --- a/entity/BaseEntity.php +++ b/entity/BaseEntity.php @@ -1,57 +1,57 @@ -<?php -namespace JLAS\Book\Entity; -use Exception; -use JsonSerializable; - -class MissingValueException extends Exception {} -class InvalidValueException extends Exception {} - -abstract class BaseEntity implements JsonSerializable { - - /** - * Create a base entity. - */ - function __construct($data) { - $this->load($data); - } - - /** - * Get a value from array with name. - * @param array $array array containing the values. - * @param string $name of the field. - */ - protected static function get($array, $name, $validator=null) { - if (isset($array[$name])) { - if ($validator){ - $valid = call_user_func_array($validator, array($array[$name])); - if (!$valid['valid']) { - throw new InvalidValueException("Invalid value for $name"); - } - } - return $array[$name]; - } - throw new MissingValueException("Missing value for $name"); - } - - /** - * Load this entity from an associative array. - * @param $data data in which the entity is loaded from. - */ - public abstract function load($data); - - /** - * Returns entity as associative array. - * @return array - */ - public abstract function asArray(); - - /** - * Serialize this object as json. - */ - public function jsonSerialize() { - return $this->asArray(); - } - -} - +<?php +namespace JLAS\Book\Entity; +use Exception; +use JsonSerializable; + +class MissingValueException extends Exception {} +class InvalidValueException extends Exception {} + +abstract class BaseEntity implements JsonSerializable { + + /** + * Create a base entity. + */ + function __construct($data) { + $this->load($data); + } + + /** + * Get a value from array with name. + * @param array $array array containing the values. + * @param string $name of the field. + */ + protected static function get($array, $name, $validator=null) { + if (isset($array[$name])) { + if ($validator){ + $valid = call_user_func_array($validator, array($array[$name])); + if (!$valid['valid']) { + throw new InvalidValueException("Invalid value for $name"); + } + } + return $array[$name]; + } + throw new MissingValueException("Missing value for $name"); + } + + /** + * Load this entity from an associative array. + * @param $data data in which the entity is loaded from. + */ + public abstract function load($data); + + /** + * Returns entity as associative array. + * @return array + */ + public abstract function asArray(); + + /** + * Serialize this object as json. + */ + public function jsonSerialize() { + return $this->asArray(); + } + +} + ?> \ No newline at end of file diff --git a/entity/GenericEntity.php b/entity/GenericEntity.php index 02cfbde777d20d1b1da27c7a7e4263811a838521..3ce8b1a9a3867387c53bf4d0f19b5384169d440c 100644 --- a/entity/GenericEntity.php +++ b/entity/GenericEntity.php @@ -1,57 +1,57 @@ -<?php -namespace JLAS\Book\Entity; - -class GenericEntity extends BaseEntity { - - private $data; - - /** - * Load this entity from an associative array. - * @param $data data in which the entity is loaded from. - */ - public function load($data) { - $this->data = $data; - } - - /** - * Returns entity as associative array. - * @return array - */ - public function asArray() { - return $this->data; - } - - /** - * Overload the default get method. - */ - public function __get($name) { - if (isset($this->data[$name])) { - return $this->data[$name]; - } - return null; - } - - /** - * Overload the default set method. - */ - public function __set($name, $value) { - $this->data[$name] = $value; - } - - /** - * Overload the default isset method. - */ - public function __isset($name) { - return isset($this->data[$name]); - } - - /** - * Overload the default unset method. - */ - public function __unset($name) { - unset($this->data[$name]); - } - -} - +<?php +namespace JLAS\Book\Entity; + +class GenericEntity extends BaseEntity { + + private $data; + + /** + * Load this entity from an associative array. + * @param $data data in which the entity is loaded from. + */ + public function load($data) { + $this->data = $data; + } + + /** + * Returns entity as associative array. + * @return array + */ + public function asArray() { + return $this->data; + } + + /** + * Overload the default get method. + */ + public function __get($name) { + if (isset($this->data[$name])) { + return $this->data[$name]; + } + return null; + } + + /** + * Overload the default set method. + */ + public function __set($name, $value) { + $this->data[$name] = $value; + } + + /** + * Overload the default isset method. + */ + public function __isset($name) { + return isset($this->data[$name]); + } + + /** + * Overload the default unset method. + */ + public function __unset($name) { + unset($this->data[$name]); + } + +} + ?> \ No newline at end of file diff --git a/entity/ImageEntity.php b/entity/ImageEntity.php index 17138e50fb3e5f385b4d19fb128cf9de25b67c14..ec00953c871ab0cac9dd154a5992547baa46da30 100644 --- a/entity/ImageEntity.php +++ b/entity/ImageEntity.php @@ -1,44 +1,44 @@ -<?php -namespace JLAS\Book\Entity; - -class ImageEntity extends BaseEntity { - - /** - * ID of the image. - */ - public $id; - - /** - * Data of the image. - */ - public $data; - - /** - * Type of the image. - */ - public $type; - - /** - * Load this entity from an associative array. - * @param $data data in which the entity is loaded from. - */ - public function load($data) { - $this->id = BaseEntity::get($data, "id"); - $this->data = BaseEntity::get($data, "data"); - $this->type = BaseEntity::get($data, "type"); - } - - /** - * Returns entity as associative array. - * @return array - */ - public function asArray() { - return array( - "id" => $this->id, - "data" => $this->data, - "type" => $this->type, - ); - } -} - +<?php +namespace JLAS\Book\Entity; + +class ImageEntity extends BaseEntity { + + /** + * ID of the image. + */ + public $id; + + /** + * Data of the image. + */ + public $data; + + /** + * Type of the image. + */ + public $type; + + /** + * Load this entity from an associative array. + * @param $data data in which the entity is loaded from. + */ + public function load($data) { + $this->id = BaseEntity::get($data, "id"); + $this->data = BaseEntity::get($data, "data"); + $this->type = BaseEntity::get($data, "type"); + } + + /** + * Returns entity as associative array. + * @return array + */ + public function asArray() { + return array( + "id" => $this->id, + "data" => $this->data, + "type" => $this->type, + ); + } +} + ?> \ No newline at end of file diff --git a/entity/TokenEntity.php b/entity/TokenEntity.php index d120ff939ed5f85f117ad3dbd54e84eff9d3b81f..d94d765d9c3d1a670613ce74487fd8096f10be53 100644 --- a/entity/TokenEntity.php +++ b/entity/TokenEntity.php @@ -1,63 +1,63 @@ -<?php -namespace JLAS\Book\Entity; - -class TokenEntity extends BaseEntity { - - /** - * Username of the account. - */ - public $username; - - /** - * The access token. - */ - public $token; - - /** - * The expiry date of the token. - */ - public $expiry; - - /** - * Load this entity from an associative array. - * @param $data data in which the entity is loaded from. - */ - public function load($data) { - $this->username = BaseEntity::get($data, "username"); - $this->token = BaseEntity::get($data, "access-token"); - $this->expiry = BaseEntity::get($data, "expiry"); - } - - /** - * Returns entity as associative array. - * @return array - */ - public function asArray() { - return array( - "username" => $this->username, - "access-token" => $this->token, - "expiry" => $this->expiry, - ); - } - - /** - * @param $current_time (optional) set the current time dynamically. - * @return boolean true if the token is expired; otherwise false. - */ - public function isExpired($current_time=null) { - if (!isset($current_time)) { - $current_time = time(); - } - return $current_time > strtotime($this->expiry); - } - - public function validate($access_token, $current_time=null) { - if ($this->isExpired($current_time)) { - return false; - } - return $this->token === $access_token; - } - -} - +<?php +namespace JLAS\Book\Entity; + +class TokenEntity extends BaseEntity { + + /** + * Username of the account. + */ + public $username; + + /** + * The access token. + */ + public $token; + + /** + * The expiry date of the token. + */ + public $expiry; + + /** + * Load this entity from an associative array. + * @param $data data in which the entity is loaded from. + */ + public function load($data) { + $this->username = BaseEntity::get($data, "username"); + $this->token = BaseEntity::get($data, "access-token"); + $this->expiry = BaseEntity::get($data, "expiry"); + } + + /** + * Returns entity as associative array. + * @return array + */ + public function asArray() { + return array( + "username" => $this->username, + "access-token" => $this->token, + "expiry" => $this->expiry, + ); + } + + /** + * @param $current_time (optional) set the current time dynamically. + * @return boolean true if the token is expired; otherwise false. + */ + public function isExpired($current_time=null) { + if (!isset($current_time)) { + $current_time = time(); + } + return $current_time > strtotime($this->expiry); + } + + public function validate($access_token, $current_time=null) { + if ($this->isExpired($current_time)) { + return false; + } + return $this->token === $access_token; + } + +} + ?> \ No newline at end of file diff --git a/index.php b/index.php index 8a86cc2ba899435357924104796425794ebae502..3fa89521f2cdd1524e590800a3a1c3ccb8a2203a 100644 --- a/index.php +++ b/index.php @@ -1,14 +1,14 @@ -<?php -namespace JLAS\Book; -define('ROOT', __DIR__ . '/'); -define('ROUTING', __DIR__ . '/routing/'); -require_once "framework/su.php"; - -// Load all routing. -foreach (glob(ROUTING . "*.php") as $filename) { - include $filename; -} - -\SuPHP\start(); - +<?php +namespace JLAS\Book; +define('ROOT', __DIR__ . '/'); +define('ROUTING', __DIR__ . '/routing/'); +require_once "framework/su.php"; + +// Load all routing. +foreach (glob(ROUTING . "*.php") as $filename) { + include $filename; +} + +\SuPHP\start(); + ?> \ No newline at end of file diff --git a/model/AccountModel.php b/model/AccountModel.php index 998b2649fae1728555028c67c276459c143bc390..32b0a7aa451a84e6d3d80c254ae294acfcaa3692 100644 --- a/model/AccountModel.php +++ b/model/AccountModel.php @@ -1,91 +1,91 @@ -<?php -namespace JLAS\Book\Model; - -class AccountModel extends BaseModel { - - function __construct() { - parent::__construct("AccountEntity"); - $this->table = "account"; - } - - /** - * Find an account with specific username. - * @param string $id The username of the account. - * @return AccountEntity the entity with matching id. - */ - public function findByID($id) { - $result = $this->query("SELECT * FROM $this->table WHERE `username` = :id LIMIT 1", array(":id"=>$id)); - if (count($this->queryResult) > 0) { - return $this->newEntity($this->queryResult[0]); - } - return null; - } - - /** - * Find an entity matching the criteria. - * @return array an array containing all matching entities. - */ - public function find($criteria, $data) { - $result = $this->query("SELECT * FROM $this->table WHERE $criteria", $data); - $retval = array(); - if ($result) { - foreach ($this->queryResult as $row) { - array_push($retval, $this->newEntity($row)); - } - } - return $retval; - } - - /** - * Insert a new entity into the database. - * @param AccountEntity $entity the entity to be created. - * @return boolean if the creation is successful. - */ - public function create($entity) { - if ($this->findByID($entity->username) != null) { - return false; - } - $result = $this->query( - "INSERT INTO $this->table (`username`, `password`) VALUES (:username, :password)", - array( - ":username" => $entity->username, - ":password" => $entity->password, - ) - ); - return $result; - } - - /** - * Update an entity in the database. - * @param AccountEntity $entity the entity to be updated. - * @return boolean if the update is successful. - */ - public function update($entity) { - $result = $this->query( - "UPDATE $this->table SET `password`=:password WHERE `username`=:username", - array( - ":username" => $entity->username, - ":password" => $entity->password, - ) - ); - return $result; - } - - /** - * Delete an entity from the database. - * @param AccountEntity $entity the entity to be deleted. - * @return boolean if the deletion is successful. - */ - public function delete($entity) { - $result = $this->query( - "DELETE FROM $this->table WHERE `username`=:username", - array( - ":username" => $entity->username, - ) - ); - return $result; - } - -} - +<?php +namespace JLAS\Book\Model; + +class AccountModel extends BaseModel { + + function __construct() { + parent::__construct("AccountEntity"); + $this->table = "account"; + } + + /** + * Find an account with specific username. + * @param string $id The username of the account. + * @return AccountEntity the entity with matching id. + */ + public function findByID($id) { + $result = $this->query("SELECT * FROM $this->table WHERE `username` = :id LIMIT 1", array(":id"=>$id)); + if (count($this->queryResult) > 0) { + return $this->newEntity($this->queryResult[0]); + } + return null; + } + + /** + * Find an entity matching the criteria. + * @return array an array containing all matching entities. + */ + public function find($criteria, $data) { + $result = $this->query("SELECT * FROM $this->table WHERE $criteria", $data); + $retval = array(); + if ($result) { + foreach ($this->queryResult as $row) { + array_push($retval, $this->newEntity($row)); + } + } + return $retval; + } + + /** + * Insert a new entity into the database. + * @param AccountEntity $entity the entity to be created. + * @return boolean if the creation is successful. + */ + public function create($entity) { + if ($this->findByID($entity->username) != null) { + return false; + } + $result = $this->query( + "INSERT INTO $this->table (`username`, `password`) VALUES (:username, :password)", + array( + ":username" => $entity->username, + ":password" => $entity->password, + ) + ); + return $result; + } + + /** + * Update an entity in the database. + * @param AccountEntity $entity the entity to be updated. + * @return boolean if the update is successful. + */ + public function update($entity) { + $result = $this->query( + "UPDATE $this->table SET `password`=:password WHERE `username`=:username", + array( + ":username" => $entity->username, + ":password" => $entity->password, + ) + ); + return $result; + } + + /** + * Delete an entity from the database. + * @param AccountEntity $entity the entity to be deleted. + * @return boolean if the deletion is successful. + */ + public function delete($entity) { + $result = $this->query( + "DELETE FROM $this->table WHERE `username`=:username", + array( + ":username" => $entity->username, + ) + ); + return $result; + } + +} + ?> \ No newline at end of file diff --git a/view/json.php b/view/json.php index f83cc00f87d04ee8e0a8c1d6515e84674730e72e..c8e16597fcf1d69e8c80be2d6de575a0ca7fdb97 100644 --- a/view/json.php +++ b/view/json.php @@ -1,11 +1,11 @@ -<?php -$object = array( - "code" => $response['code'], - "data" => $data -); -if (isset($response['message'])) { - $object['message'] = $response['message']; -} -header("Content-Type: application/json"); -echo json_encode($object) +<?php +$object = array( + "code" => $response['code'], + "data" => $data +); +if (isset($response['message'])) { + $object['message'] = $response['message']; +} +header("Content-Type: application/json"); +echo json_encode($object) ?> \ No newline at end of file