Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save abdolrhman/29d4cfe036e42cbe279fc1af6d06da1a to your computer and use it in GitHub Desktop.
Save abdolrhman/29d4cfe036e42cbe279fc1af6d06da1a to your computer and use it in GitHub Desktop.
task_php
<?php
# TASK: Refactor the following code.
# Exception: Do not split code into files. Keep everything in one file.
class Zoo {
private $animals = [];
private $db;
public function __construct( $animals, DBMysql $db ) {
foreach( $animals as $animal ) {
if( $animal instanceof AnimalInterface ) {
$this->animals[] = $animal;
} else {
throw new Exception("animal is an animal interface");
}
}
$this->db = $db;
}
public function foodCosts() {
mail( "[email protected]", "Costs for food", $costs );
}
private function sendEmail(string $to, string $subject, $costs) {
mail( $to, $subject, $costs );
}
public function flyingShow() {
foreach( $this->animals as $animal ) {
try{
$animal->fly();
} catch( \Exception $e ) {
// The animal cannot fly.
}
}
}
public function moveAnimalToEnclosure( $animal, $enclosure ) {
$animal->setEnclosure = $enclosure;
$this->db->saveAnimal( $animal );
}
// save cost to file
public function saveFoodCostToFile(): void {
$cost = $this->calFoodCost();
$filePath = 'foodcost.txt';
file_put_contents($filePath, $cost);
}
private function calFoodCost() :int
{
$costs = 0;
foreach( $this->animals as $animal ) {
if( $animal instanceof Lion ) {
$costs += 100;
} elseif( $animal instanceof Eagle::class ) {
$costs += 50;
} else {
throw new \Exception( "Don't know animal." );
}
}
return $costs;
}
}
interface AnimalInterface {
public function walk(): void;
public function fly(): void;
public function setEnclosure($enclosure): void;
}
class Lion implements AnimalInterface {
private $enclosure;
public function walk(): void {
// Implementation does not matter.
}
public function fly(): void {
throw new \Exception( "Lions can not fly." );
}
//set enclouser in here
public function setEnclosure(string $enclosure)
{
$this->enclosure = $enclosure;
}
}
class Eagle implements AnimalInterface {
private $enclosure;
public function walk(): void {
// Implementation does not matter.
}
public function fly(): void {
// Implementation does not matter.
}
//set enclouser in here
public function setEnclosure(string $enclosure)
{
$this->enclosure = $enclosure;
}
}
class DBMysql {
public function saveAnimal( $animal ) {
// Implementation does not matter.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment