1 | <?php |
||
9 | class Fetcher |
||
10 | { |
||
11 | /** |
||
12 | * @var ClientInterface |
||
13 | */ |
||
14 | private $client; |
||
15 | |||
16 | /** |
||
17 | * @param ClientInterface $client |
||
18 | */ |
||
19 | public function __construct(ClientInterface $client) |
||
23 | |||
24 | /** |
||
25 | * Retrieve information about a book given its ISBN. |
||
26 | * |
||
27 | * @param string $isbn |
||
28 | * |
||
29 | * @throws InvalidArgumentException When the ISBN has not the expected format |
||
30 | * @throws InvalidResponseException When the client got an unexpected response |
||
31 | * |
||
32 | * @return Book |
||
33 | */ |
||
34 | public function forISBN($isbn) |
||
60 | |||
61 | private function extractBook($res) |
||
62 | { |
||
63 | $item = $res['items'][0]; |
||
64 | |||
65 | $publishedDate = $this->getOrDefault($item['volumeInfo'], 'publishedDate', null); |
||
66 | list($publishedDate, $publishedDateFormat) = $this->parseDate($publishedDate); |
||
67 | |||
68 | return new Book($item['volumeInfo']['title'], |
||
69 | $this->getOrDefault($item['volumeInfo'], 'subtitle', null), |
||
70 | $this->getOrDefault($item['volumeInfo'], 'authors', null), |
||
71 | $this->getOrDefault($item['volumeInfo'], 'printType', null), |
||
72 | intval($this->getOrDefault($item['volumeInfo'], 'pageCount', null)), |
||
73 | $this->getOrDefault($item['volumeInfo'], 'publisher', null), |
||
74 | $publishedDate, |
||
75 | $publishedDateFormat, |
||
76 | $this->getOrDefault($item['volumeInfo'], 'averageRating', null), |
||
77 | $item['volumeInfo']['imageLinks']['thumbnail'], |
||
78 | $this->getOrDefault($item['volumeInfo'], 'language', null), |
||
79 | $this->getOrDefault($item['volumeInfo'], 'categories', [])); |
||
80 | } |
||
81 | |||
82 | /** |
||
83 | * Parse the publication date. |
||
84 | * |
||
85 | * @param string $rawDate |
||
86 | * |
||
87 | * @return array The publication in DateTime and the date format |
||
88 | */ |
||
89 | private function parseDate($rawDate) |
||
104 | |||
105 | private function getOrDefault($array, $key, $default) |
||
113 | |||
114 | /** |
||
115 | * Check if a given ISBN is valid. |
||
116 | * |
||
117 | * @param string $isbn |
||
118 | * |
||
119 | * @return bool |
||
120 | */ |
||
121 | private function isValidISBN($isbn) |
||
125 | } |
||
126 |
If you define a variable conditionally, it can happen that it is not defined for all execution paths.
Let’s take a look at an example:
In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.
Available Fixes
Check for existence of the variable explicitly:
Define a default value for the variable:
Add a value for the missing path: