Robert Marshall 9 anni fa
parent
commit
ac9b38b0af

+ 81 - 37
Controller/Member.php

@@ -1,93 +1,110 @@
 <?php
+
 class Member extends Controller {
-	public function Index($permission_error,$submit_form,$email,$password,$confirm_password) {
+
+	public function Index(IUserSettingsRepository $userSettingsRepo, $permission_error, $submit_form, $email, $password, $confirm_password) {
 		if (Session::IsUserLoggedIn())
-			return $this->Manage($email,$password,$confirm_password);
+			return $this->Manage($userSettingsRepo);
 		else
-			return $this->Login($permission_error,$submit_form,$email,$password);
+			return $this->Login($permission_error, $submit_form, $email, $password);
 	}
-	
-	public function Login($permission_error,$submit_form,$email,$password){
-		if (Session::IsUserLoggedIn()){
+
+	public function Login($permission_error, $submit_form, $email, $password) {
+		if (Session::IsUserLoggedIn()) {
 			header("location:/member/manage");
 			return;
 		}
-		
+
 		if (!isset($email))
 			$email="";
-		
+
 		$errors=array();
-		
-		if (isset($permission_error) && $permission_error==true)
+
+		if (isset($permission_error)&&$permission_error==true)
 			$errors[]="You don't have permission to access this page.";
-		
-		if (isset($submit_form) && $email!=""){
+
+		if (isset($submit_form)&&$email!="") {
 			$user=new User($email);
-			if ($user->UserId!=null && $user->ValidatePassword($password)){
+			if ($user->UserId!=null&&$user->ValidatePassword($password)) {
 				Session::SetLoggedInUser($user);
 				header("location:/member/manage");
 				return;
 			}
-			
+
 			$errors[]="Unable to log in. Please check your login details and try again.";
 		}
-		
-		return new View("Member/login.view",array(
+
+		return new View("Member/login.view", array(
 			"errors"=>$errors,
 			"loginEmail"=>$email
 		));
 	}
-	
-	public function Logout(){
+
+	public function Logout() {
 		Session::Destroy();
 		header("location:/member");
 	}
-	
-	public function Register($email,$password){
-		if (!isset($email,$password))
+
+	public function Register($email, $password) {
+		if (!isset($email, $password))
 			return $this->Login(null, null, $email, $password);
-		
+
 		$errors=array();
 		if ($email=="")
 			$errors[]="Email blank";
-		if  ($password=="")
+		if ($password=="")
 			$errors[]="Password blank";
-		
+
 		if (!Utils::IsValidEmail($email))
 			$errors[]="Invalid email address";
-		
+
 		$user=new User($email);
 		if ($user->UserId!=0)
 			$errors[]="Email already in use";
-		
+
 		if (count($errors)>0)
-			return new View("Member/login.view",array(
+			return new View("Member/login.view", array(
 				"errors"=>$errors,
 				"registerEmail"=>$email
 			));
-		
+
 		$user=new User();
 		$user->UserEmail=$email;
 		$user->UserPassword=$password;
 		$user->UserCreated=time();
 		$user->Save();
-		
+
 		Session::SetLoggedInUser($user);
-		
+
 		header("location:/member/manage");
 	}
-	
-	public function Manage($submit_form,$new_password,$confirm_password){
-		if (!Session::IsUserLoggedIn()){
+
+	public function Manage(IUserSettingsRepository $userSettingsRepo, $errors=array()) {
+		if (!Session::IsUserLoggedIn()) {
 			header("location:/member/");
 			return;
 		}
+
+		$user=Session::GetLoggedInUser();
+		$settings=array(
+			"height"=>$heightSetting=$userSettingsRepo->GetSetting($user, "height")->Value
+		);
 		
+		$user=Session::GetLoggedInUser();
+		return new View("Member/manage.view", array("user"=>$user, "errors"=>$errors, "settings"=>$settings));
+	}
+
+	public function SavePassword($submit_form, $new_password, $confirm_password) {
+		if (!Session::IsUserLoggedIn()) {
+			header("location:/member/");
+			return;
+		}
+
 		$user=Session::GetLoggedInUser();
 		$errors=array();
-		
-		if (isset($submit_form) && $new_password!=""){
-			if ($new_password==$confirm_password){
+
+		if (isset($submit_form) && $new_password!="") {
+			if ($new_password==$confirm_password) {
 				$user->UserPassword=$new_password;
 				$user->Save();
 				header("location:/member/manage");
@@ -95,7 +112,34 @@ class Member extends Controller {
 			} else
 				$errors[]="Passwords did not match";
 		}
+
+		if (count($errors)==0){
+			header("location:/member/");
+			return;
+		}
 		
-		return new View("Member/manage.view",array("user"=>$user,"errors"=>$errors));
+		return $this->Manage($errors);
+	}
+
+	public function SaveSettings($submit_form, $user_setting_height, IUserSettingsRepository $userSettingsRepo) {
+		if (!isset($submit_form) || !Session::IsUserLoggedIn()) {
+			header("location:/member/");
+			return;
+		}
+
+		$user=Session::GetLoggedInUser();
+		$errors=array();
+
+		$heightSetting=$userSettingsRepo->GetSetting($user, "height");
+		$heightSetting->Value=(int)$user_setting_height;
+		$heightSetting->Save();
+
+		if (count($errors)==0){
+			header("location:/member/");
+			return;
+		}
+
+		return $this->Manage($errors);
 	}
+
 }

+ 7 - 0
DB Scripts/7/create_user_settings.sql

@@ -0,0 +1,7 @@
+CREATE TABLE user_settings (
+  user_id int(11) NOT NULL,
+  `key` varchar(255) NOT NULL,
+  `value` longtext NOT NULL,
+  `type` int(11) NOT NULL DEFAULT '0',
+  PRIMARY KEY (user_id,`key`)
+) ENGINE=InnoDB DEFAULT CHARSET=latin1;

+ 0 - 9
Database/BaseRepository.php

@@ -5,11 +5,6 @@ ApplicationSettings::RegisterDefaultSetting("database", "username", "root");
 ApplicationSettings::RegisterDefaultSetting("database", "password", "");
 
 class BaseRepository {
-
-	/**
-	 * @var DependencyInjector
-	 */
-	private $DependencyInjector;
 	protected static $PDO=null;
 
 	protected static function SetupPDO(){
@@ -49,8 +44,4 @@ class BaseRepository {
 		$prep->execute($execData);
 		return $prep->fetchAll(PDO::FETCH_COLUMN);
 	}
-	
-	protected function ResolveDependency($dependency) {
-		return $this->DependencyInjector->Resolve($dependency);
-	}
 }

+ 3 - 3
Database/UserSettingsRepository.php

@@ -1,10 +1,10 @@
 <?php
 class UserSettingsRepository implements IUserSettingsRepository {
 	public function GetSetting(User $user, $settingName) {
-		$PDO=BaseRepository::GetPDO();
+		/*$PDO=BaseRepository::GetPDO();
 		$prep=$PDO->prepare("SELECT setting_id FROM user_settings WHERE user_id=? AND key=?");
 		$prep->execute(array($user->UserId,$settingName));
-		$settingId=$prep->FetchColumn();
-		return new UserSetting($settingId);
+		$settingId=$prep->FetchColumn();*/
+		return new UserSetting($user, $settingName);
 	}
 }

+ 9 - 2
Database/WeightReadingRepository.php

@@ -1,10 +1,17 @@
 <?php
 class WeightReadingRepository extends BaseRepository implements IWeightReadingRepository {
+	private $_userSettingsRepo;
+
+	public function __construct(IUserSettingsRepository $userSettingsRepo) {
+		parent::__construct();
+		$this->_userSettingsRepo=$userSettingsRepo;
+	}
+	
 	public function GetAll($userId){
 		$readings=array();
 		$ids=self::$PDO->query("SELECT reading_id FROM weight_readings WHERE user_id=".(int)$userId)->fetchAll(PDO::FETCH_COLUMN);
 		foreach ($ids as $id)
-			$readings[]=new WeightReading(parent::ResolveDependency("IUserSettingsRepository") ,$id);
+			$readings[]=new WeightReading($this->_userSettingsRepo ,$id);
 		return $readings;
 	}
 	
@@ -18,7 +25,7 @@ class WeightReadingRepository extends BaseRepository implements IWeightReadingRe
 		));
 		$results=$prep->fetchAll(PDO::FETCH_COLUMN);
 		foreach ($results as $id)
-			$readings[]=new WeightReading(parent::ResolveDependency("IUserSettingsRepository") ,$id);
+			$readings[]=new WeightReading($this->_userSettingsRepo ,$id);
 		return $readings;
 	}
 }

+ 90 - 51
Model/DBObject.php

@@ -1,115 +1,154 @@
 <?php
-class DBObject implements ISavableObject{
+
+class DBObject implements ISavableObject {
+
 	protected static $PREPARED_STATEMENTS=array();
-	
 	private static $_classFields=array();
-	
 	protected $_fields=array();
 	protected $_changedFields=array();
-	
-	private $_table,$_key,$_id;
-	
+	private $_table, $_keys, $_ids;
+
 	public static function VariableToDBField($variableName) {
 		$parts=preg_split('/(?=[A-Z])/', $variableName);
-		for ($i=0;$i<count($parts);$i++)
+		for ($i=0; $i<count($parts); $i++)
 			$parts[$i]=strtolower($parts[$i]);
-		return trim(implode("_", $parts),"_"); // If the variable name start with upper case then we get an extra blank entry in the array causing an extra _
+		return trim(implode("_", $parts), "_"); // If the variable name start with upper case then we get an extra blank entry in the array causing an extra _
 	}
-	
+
 	public static function DBFieldToVariable($fieldName) {
-		$parts=explode("_",$fieldName);
-		for ($i=0;$i<count($parts);$i++)
+		$parts=explode("_", $fieldName);
+		for ($i=0; $i<count($parts); $i++)
 			$parts[$i]=ucfirst($parts[$i]);
 		return implode("", $parts);
 	}
+
+	private function ReIndexKeyAndIdArrays(){
+		$newKeyArray=array();
+		foreach ($this->_keys as $index=>$key){
+			$newKeyArray[':'.$index]=$key;
+		}
+		$this->_keys=$newKeyArray;
+		
+		$newIdArray=array();
+		foreach ($this->_ids as $index=>$id){
+			$newIdArray[':'.$index]=$id;
+		}
+		$this->_ids=$newIdArray;
+	}
+	
+	private function GetWhereClause(){
+		$qualifiers=array();
+		foreach ($this->_keys as $index=>$key)
+			$qualifiers[]=" `$key`=$index";
+		return implode(" AND", $qualifiers);
+	}
 	
 	function __construct($table, $key, $id) {
 		$this->_table=$table;
-		$this->_key=$key;
-		$this->_id=$id;
-		
+
+		if (is_array($key)&&is_array($id)) {
+			$this->_keys=$key;
+			$this->_ids=$id;
+		} else {
+			$this->_keys=array($key);
+			$this->_ids=array($id);
+		}
+
+		$this->ReIndexKeyAndIdArrays();
 		$this->Load();
 	}
-	
+
 	public function __get($name) {
-		if (array_key_exists($name,$this->_fields))
+		if (array_key_exists($name, $this->_fields))
 			return $this->_fields[$name];
 		return null;
 	}
-	
+
 	public function __set($name, $value) {
-		if (array_key_exists($name,$this->_fields) && $this->_fields[$name]!=$value){
+		if (array_key_exists($name, $this->_fields)&&$this->_fields[$name]!=$value) {
 			$this->_changedFields[$name]=$name;
 			$this->_fields[$name]=$value;
 		}
 	}
-	
+
 	public function __isset($name) {
 		return array_key_exists($name, $this->_fields);
 	}
-	
-	public function Load(){
+
+	public function Load() {
 		$PDO=BaseRepository::GetPDO();
-		
+
 		$class=get_class($this);
-		
-		if (!isset(self::$_classFields[$class])){
+
+		if (!isset(self::$_classFields[$class])) {
 			self::$_classFields[$class]=$PDO->query("DESCRIBE `{$this->_table}`")->fetchAll(PDO::FETCH_COLUMN);
 		}
-		
-		$statementKey=$class.'_construct_'.$this->_key;
-		if (!isset(self::$PREPARED_STATEMENTS[$statementKey])){
-			$fields=implode(", ", self::$_classFields[$class]);
-			$sql="SELECT $fields FROM `{$this->_table}` WHERE `{$this->_key}`=?";
+
+		$statementKey=$class.'_construct_'.$this->_table;
+		if (!isset(self::$PREPARED_STATEMENTS[$statementKey])) {
+			$fields=implode("`, `", self::$_classFields[$class]);
+			$sql="SELECT `$fields` FROM `{$this->_table}` WHERE".$this->GetWhereClause();
+			//var_dump($sql, $this->_ids);
 			self::$PREPARED_STATEMENTS[$statementKey]=$PDO->prepare($sql);
 		}
 		$prep=self::$PREPARED_STATEMENTS[$statementKey];
-		$prep->execute(array($this->_id));
+		$prep->execute($this->_ids);
+		
+		$errorInfo=$prep->errorInfo();
+		if ($errorInfo[0]!='00000')
+			throw new Exception($errorInfo[2]);
+		
 		$record=$prep->fetch();
 		if ($record!==false)
-			foreach ($record as $key=>$value)
+			foreach ($record as $key=> $value)
 				$this->_fields[self::DBFieldToVariable($key)]=$value;
 		else {
 			foreach (self::$_classFields[$class] as $field)
 				$this->_fields[self::DBFieldToVariable($field)]=null;
-			$this->_id=0;
+			$this->_ids=0;
 		}
 	}
-	
+
 	public function Save() {
 		$PDO=BaseRepository::GetPDO();
-		
+
 		if (count($this->_changedFields)==0)
 			return;
-		
+
 		$fields=array();
 		$execData=array();
-		foreach ($this->_changedFields as $field){
-			$fields[]=self::VariableToDBField($field).'=:'.$field;
+		foreach ($this->_changedFields as $field) {
+			$fields[]='`'.self::VariableToDBField($field).'`=:'.$field;
 			$execData[':'.$field]=$this->_fields[$field];
 		}
-		
-		if ($this->_id!==0){
-			$sql="UPDATE `{$this->_table}` SET ".implode(", ", $fields)." WHERE `{$this->_key}`=:soi5yh58y";
-			$execData[':soi5yh58y']=$this->_id;
-		}else{
+
+		if ($this->_ids!==0) {
+			#$sql="UPDATE `{$this->_table}` SET ".implode(", ", $fields)." WHERE `{$this->_keys}`=:soi5yh58y";
+			#$execData[':soi5yh58y']=$this->_ids;
+			$sql="UPDATE `{$this->_table}` SET ".implode(", ", $fields)." WHERE".$this->GetWhereClause();
+			$execData=array_merge($execData,$this->_ids);
+		} else {
 			$sql="INSERT INTO `{$this->_table}` SET ".implode(", ", $fields);
 		}
-		
 		$prep=$PDO->prepare($sql);
 		$prep->execute($execData);
-		
-		//var_dump($prep->errorInfo());
-		/*$errorInfo=$prep->errorInfo();
+
+		$errorInfo=$prep->errorInfo();
 		if ($errorInfo[0]!='00000')
-			trigger_error($errorInfo[2]);*/
-		
-		if ($this->_id===0){ // If this is a new object we want to reload fromt he DB to make sure all fields are correct.
+			throw new Exception($errorInfo[2]);
+
+		if (count($this->_ids)===0) { // If this is a new object we want to reload fromt he DB to make sure all fields are correct.
 			// In order to do so we need to find the value for the key we're using
 			$id=$PDO->lastInsertId();
-			$key=$PDO->query("SHOW INDEX FROM `{$this->_table}` WHERE Key_name='PRIMARY'")->fetch()['Column_name'];
-			$this->_id=$PDO->query("SELECT `{$this->_key}` FROM `{$this->_table}` WHERE `$key`=$id")->fetchColumn();
+			if ($id!=0 && count($this->_keys)==0){
+				$this->_keys=$this->_ids=array();
+				$key=$PDO->query("SHOW INDEX FROM `{$this->_table}` WHERE Key_name='PRIMARY'")->fetch()['Column_name'];
+				$this->_keys[]=$key;
+				$this->_ids[]=$PDO->query("SELECT `$key` FROM `{$this->_table}` WHERE `$key`=$id")->fetchColumn();
+				$this->ReIndexKeyAndIdArrays();
+			}
 			$this->Load();
 		}
 	}
+
 }

+ 6 - 2
Model/UserSetting.php

@@ -1,7 +1,11 @@
 <?php
 class UserSetting extends DBObject {	
-	public function __construct($settingId) {
-		parent::__construct("user_settings", "setting_id", $settingId);
+	public function __construct(User $user, $key) {
+		parent::__construct("user_settings", array("user_id", "key"), array($user->UserId, $key));
+		if (!$this->UserId)
+			$this->UserId=$user->UserId;
+		if (!$this->Key)
+			$this->Key=$key;
 	}
 
 	public function GetValue(){

+ 2 - 1
Model/WeightReading.php

@@ -24,7 +24,8 @@ class WeightReading extends DBObject {
 	public function Save(User $user=null) {
 		if ($user==null)
 			throw new Exception("Please specify user");
-		$height=$this->_userSettingsRepo->GetSetting($user, "height")->GetValue;
+		$height=$this->_userSettingsRepo->GetSetting($user, "height")->GetValue();
+		$height*=0.01;//convert from cm to metres;
 		$this->Bmi=self::CalculateBMI($this->Weight, $height);
 		$this->UserId=$user->UserId;
 		parent::Save();

+ 27 - 9
View/Member/manage.view

@@ -1,16 +1,34 @@
 @Title{Member Area}@
 @Body{
 <p>You are currently logged in as: <?=$user->UserEmail?></p>
-<?=Utils::TableMaker(array(
+<h3>Password</h3>
+<?=Utils::TableMaker(
 	array(
-		"display"=>"New password",
-		"type"=>"password",
-		"name"=>"new_password"
+		array(
+			"display"=>"New password",
+			"type"=>"password",
+			"name"=>"new_password"
+		),
+		array(
+			"display"=>"Confirm password",
+			"type"=>"password",
+			"name"=>"confirm_password"
+		)
 	),
+	"Save",
+	"savepassword"
+);?>
+<h3>Weight tracker</h3>
+<?=Utils::TableMaker(
 	array(
-		"display"=>"Confirm password",
-		"type"=>"password",
-		"name"=>"confirm_password"
-	)
-));?>
+		array(
+			"display"=>"Height (cm)",
+			"type"=>"nubmer",
+			"name"=>"user_setting_height",
+			"value"=>$settings['height']
+		)
+	),
+	"Save",
+	"savesettings"
+);?>
 }@

+ 4 - 4
View/Weight/index.view

@@ -80,7 +80,7 @@
 		if (data!=""){
 			var reading=JSON.parse(data);
 			AddData(reading.Weight, reading.BMI, reading.Fat);
-			$("form input[type=text]").val("");
+			$("form input[type=number]").val("");
 		}
 	}
 	
@@ -98,11 +98,11 @@
 	<div class="row col-md-4">
 		<div class="col input">
 			<label for="weight">Weight (KG)</label>
-			<input type="number" id="weight" name="weight" />
+			<input type="number" id="weight" name="weight" step="any" />
 		</div>
 		<div class="col input">
 			<label for="fat">Fat %</label>
-			<input type="number" id="fat" name="fat" />
+			<input type="number" id="fat" name="fat" step="any" />
 		</div>
 		<div class="col input">
 			<label for="save">Action</label>
@@ -124,7 +124,7 @@
 			<?php
 				$last10=array_slice($readings, count($readings)-10);
 				foreach ($last10 as $reading){
-					echo '<tr><td>',$reading->Weight,'</td><td>',$reading->Bmi,'</td><td>',$reading->Fat,'</td></tr>';
+					echo '<tr><td>',$reading->Weight,'</td><td>',round($reading->Bmi,1),'</td><td>',$reading->Fat,'</td></tr>';
 				}
 			?>
 		</table>

+ 23 - 7
base/DependencyInjector.php

@@ -1,17 +1,33 @@
 <?php
+
 class DependencyInjector {
+
 	private $_dependencyArray=array();
-	
-	public function Register($interface,$class) {
-		if (isset(class_implements($class)[$interface])){
+
+	public function Register($interface, $class) {
+		if (isset(class_implements($class)[$interface])) {
 			$this->_dependencyArray[$interface]=$class;
-		}else
+		} else
 			throw new Exception("Class '$class' does not implement interface '$interface'");
 	}
-	
+
 	public function Resolve($interface) {
-		$item = new $this->_dependencyArray[$interface];
-		$item->DependencyInjector=$this;
+		$class=new ReflectionClass($this->_dependencyArray[$interface]);
+		$constructor=$class->getConstructor();
+		$callArgs=array();
+		if ($constructor!=null){
+			$methodParams=$constructor->getParameters();
+			foreach ($methodParams as $methodParam) {
+				$index=$methodParam->getPosition();
+				$type=$methodParam->getClass();
+				$callArgs[$index]=$this->Resolve($type->getName());
+			}
+			$item=$class->newInstanceArgs($callArgs);
+		}else{
+			$item=new $this->_dependencyArray[$interface];
+		}
+		#$item->DependencyInjector=$this;
 		return $item;
 	}
+
 }