Add validation for setters

This commit is contained in:
William 2022-03-09 13:11:12 +01:00
parent 3296f1b078
commit 5fcefa78ee

View File

@ -6,7 +6,6 @@ use \InvalidArgumentException;
/** /**
* Represents a team in the teamtable database * Represents a team in the teamtable database
* TODO: Add validation for setters
*/ */
class Team class Team
{ {
@ -19,44 +18,92 @@ class Team
public int $participants = 0; public int $participants = 0;
public int $rounds = 0; public int $rounds = 0;
/**
* PHP by default does not include multi byte functions. Therefore we use this
*/
private function count_characters(string $string)
{
return count(preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY));
}
/**
* Check if string is longer than length
*/
private function longerThan(string $string, int $length): bool
{
if ($this->count_characters($string) > $length)
{
return TRUE;
}
return FALSE;
}
public function setName(string $name): Self public function setName(string $name): Self
{ {
if ($this->longerThan($name, 32))
{
throw new InvalidArgumentException("Name is too long!");
}
$this->name = $name; $this->name = $name;
return $this; return $this;
} }
public function setCompany(string $company): Self public function setCompany(string $company): Self
{ {
if ($this->longerThan($company, 32))
{
throw new InvalidArgumentException("Company is too long!");
}
$this->company = $company; $this->company = $company;
return $this; return $this;
} }
public function setCardnumber(string $cardnumber): Self public function setCardnumber(string $cardnumber): Self
{ {
if ($this->longerThan($cardnumber, 32))
{
throw new InvalidArgumentException("Cardnumber is too long!");
}
$this->cardnumber = $cardnumber; $this->cardnumber = $cardnumber;
return $this; return $this;
} }
public function setLeader(string $leader): Self public function setLeader(string $leader): Self
{ {
if ($this->longerThan($leader, 32))
{
throw new InvalidArgumentException("Leader is too long!");
}
$this->leader = $leader; $this->leader = $leader;
return $this; return $this;
} }
public function setPhone(int $phone): Self public function setPhone(int $phone): Self
{ {
if ($this->longerThan($phone, 32))
{
throw new InvalidArgumentException("Phone number is too long!");
}
$this->phone = $phone; $this->phone = $phone;
return $this; return $this;
} }
public function setParticipants(int $participants): Self public function setParticipants(int $participants): Self
{ {
if ($this->longerThan($participants, 32))
{
throw new InvalidArgumentException("Participants is too long!");
}
$this->participants = $participants; $this->participants = $participants;
return $this; return $this;
} }
public function setRounds(int $rounds): Self public function setRounds(int $rounds): Self
{ {
if ($this->longerThan($rounds, 32))
{
throw new InvalidArgumentException("Rounds is too long!");
}
$this->rounds = $rounds; $this->rounds = $rounds;
return $this; return $this;
} }