-
Notifications
You must be signed in to change notification settings - Fork 2
/
PokemonRepository.php
50 lines (40 loc) · 1.4 KB
/
PokemonRepository.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php namespace App\Repositories;
use Illuminate\Filesystem\Filesystem;
use App\Exceptions\PokemonNotFoundException;
use App\Pokemon;
class PokemonRepository
{
private $filesystem;
public function __construct()
{
$this->filesystem = new Filesystem();
}
public function getAll()
{
return json_decode($this->filesystem->get(storage_path('app/pokemons.json')));
}
public function findByName($name)
{
$pokemons = array_filter($this->getAll(), function($pokemon) use ($name) {
return $pokemon->name === $name;
});
if (empty($pokemons)) {
throw new PokemonNotFoundException("The pokémon '$name' does not exist!");
}
$pokemonFound = reset($pokemons);
$pokemon = new Pokemon($pokemonFound->name, $pokemonFound->type,
$pokemonFound->avatar, $pokemonFound->health, $pokemonFound->agility,
$pokemonFound->attack, $pokemonFound->defense, $pokemonFound->attacks
);
return $pokemon;
}
public function getRandom()
{
$pokemons = $this->getAll();
$pokemonFound = $pokemons[array_rand($pokemons)];
return new Pokemon($pokemonFound->name, $pokemonFound->type,
$pokemonFound->avatar, $pokemonFound->health, $pokemonFound->agility,
$pokemonFound->attack, $pokemonFound->defense, $pokemonFound->attacks
);
}
}