|
4 | 4 |
|
5 | 5 | use Github\Api\AbstractApi;
|
6 | 6 | use Github\Exception\MissingArgumentException;
|
| 7 | +use Github\Exception\InvalidArgumentException; |
| 8 | +use Github\Exception\ErrorException; |
7 | 9 |
|
8 | 10 | /**
|
9 | 11 | * @link http://developer.github.com/v3/repos/contents/
|
@@ -72,4 +74,38 @@ public function archive($username, $repository, $format, $reference = null)
|
72 | 74 | 'ref' => $reference
|
73 | 75 | ));
|
74 | 76 | }
|
| 77 | + |
| 78 | + /** |
| 79 | + * Get the contents of a file in a repository |
| 80 | + * |
| 81 | + * @param string $username the user who owns the repository |
| 82 | + * @param string $repository the name of the repository |
| 83 | + * @param string $path path to file |
| 84 | + * @param string $reference reference to a branch or commit |
| 85 | + * |
| 86 | + * @return string|null content of file, or null in case of base64_decode failure |
| 87 | + * |
| 88 | + * @throws InvalidArgumentException If $path is not a file or if its encoding is different from base64 |
| 89 | + * @throws ErrorException If $path doesn't include a 'content' index |
| 90 | + */ |
| 91 | + public function download($username, $repository, $path, $reference = null) |
| 92 | + { |
| 93 | + $file = $this->show($username, $repository, $path, $reference); |
| 94 | + |
| 95 | + if (!isset($file['type']) || 'file' !== $file['type']) { |
| 96 | + throw new InvalidArgumentException(sprintf('Path "%s" is not a file.', $path)); |
| 97 | + } |
| 98 | + |
| 99 | + if (!isset($file['content'])) { |
| 100 | + throw new ErrorException(sprintf('Unable to access "content" for file "%s" (possible keys: "%s").', $path, implode(', ', array_keys($file)))); |
| 101 | + } |
| 102 | + |
| 103 | + if (!isset($file['encoding'])) { |
| 104 | + throw new InvalidArgumentException(sprintf('Can\t decode contents of file "%s" as no encoding is defined.', $path)); |
| 105 | + } elseif ('base64' !== $file['encoding']) { |
| 106 | + throw new InvalidArgumentException(sprintf('Encoding "%s" of file "%s" is not supported.', $file['encoding'], $path)); |
| 107 | + } |
| 108 | + |
| 109 | + return base64_decode($file['content']) ?: null; |
| 110 | + } |
75 | 111 | }
|
0 commit comments