|
4 | 4 |
|
5 | 5 | class Utils
|
6 | 6 | {
|
7 |
| - public function loadInput($day, $type="day"): array |
| 7 | + protected array $env = []; |
| 8 | + |
| 9 | + /** |
| 10 | + * @param int $day |
| 11 | + * @param string $type |
| 12 | + * @return array |
| 13 | + * @throws \Exception |
| 14 | + */ |
| 15 | + public function loadInput($day, $type = "day"): array |
8 | 16 | {
|
9 | 17 | $filePath = "input/{$type}{$day}.txt";
|
10 | 18 | if (!file_exists($filePath)) {
|
11 |
| - // TODO: download input |
12 |
| - throw new \Exception("Input missing: '$filePath'", 1670457206416); |
| 19 | + if ($this->downloadInput($day, $filePath) === false) { |
| 20 | + throw new \Exception("Input missing: '$filePath'", 1670457206416); |
| 21 | + } |
13 | 22 | }
|
14 | 23 | $content = file_get_contents($filePath);
|
15 | 24 | return explode("\n", $content);
|
16 | 25 | }
|
| 26 | + |
| 27 | + /** |
| 28 | + * @param int $day |
| 29 | + * @param string $filePath |
| 30 | + * @return bool |
| 31 | + * @throws \Exception |
| 32 | + */ |
| 33 | + protected function downloadInput($day, $filePath): bool |
| 34 | + { |
| 35 | + if (empty($this->env)) { |
| 36 | + $this->loadDotEnv(); |
| 37 | + } |
| 38 | + if (!isset($this->env["SESSION"])) { |
| 39 | + return false; |
| 40 | + } |
| 41 | + |
| 42 | + $curl = \curl_init(); |
| 43 | + $options = [ |
| 44 | + CURLOPT_URL => "https://adventofcode.com/2022/day/$day/input", |
| 45 | + CURLOPT_RETURNTRANSFER => true, |
| 46 | + CURLOPT_COOKIE => "session=" . $this->env["SESSION"], |
| 47 | + CURLOPT_USERAGENT => "https://github.com/FailedCode/adventofcode-2022-php by xeres666@googlemail.com", |
| 48 | + ]; |
| 49 | + \curl_setopt_array($curl, $options); |
| 50 | + $result = \curl_exec($curl); |
| 51 | + $err = \curl_errno($curl); |
| 52 | + $errmsg = \curl_error($curl); |
| 53 | + \curl_close($curl); |
| 54 | + |
| 55 | + if ($err) { |
| 56 | + throw new \Exception("Error downloading input for day {$day}:\n{$errmsg}\n", 1670546029246); |
| 57 | + } |
| 58 | + return file_put_contents($filePath, $result) !== false; |
| 59 | + } |
| 60 | + |
| 61 | + /** |
| 62 | + * @return void |
| 63 | + */ |
| 64 | + protected function loadDotEnv() |
| 65 | + { |
| 66 | + $envFile = __dir__ . '/../.env'; |
| 67 | + if (!file_exists($envFile)) { |
| 68 | + return; |
| 69 | + } |
| 70 | + $lines = array_filter(explode("\n", file_get_contents($envFile)), 'strlen'); |
| 71 | + foreach ($lines as $line) { |
| 72 | + // skip comments |
| 73 | + if (preg_match('~^\s*#~', $line)) { |
| 74 | + continue; |
| 75 | + } |
| 76 | + if (strpos($line, '=') !== false) { |
| 77 | + list($var, $value) = explode('=', $line, 2); |
| 78 | + $var = strtoupper(trim($var)); |
| 79 | + if (strlen($var) > 1) { |
| 80 | + $this->env[$var] = $value; |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + } |
17 | 85 | }
|
0 commit comments