FileSource.php
61 lines
| 1 | <?php |
| 2 | |
| 3 | /* |
| 4 | * Copyright 2023 Google Inc. |
| 5 | * |
| 6 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | * you may not use this file except in compliance with the License. |
| 8 | * You may obtain a copy of the License at |
| 9 | * |
| 10 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | * |
| 12 | * Unless required by applicable law or agreed to in writing, software |
| 13 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | * See the License for the specific language governing permissions and |
| 16 | * limitations under the License. |
| 17 | */ |
| 18 | namespace WPMailSMTP\Vendor\Google\Auth\CredentialSource; |
| 19 | |
| 20 | use WPMailSMTP\Vendor\Google\Auth\ExternalAccountCredentialSourceInterface; |
| 21 | use InvalidArgumentException; |
| 22 | use UnexpectedValueException; |
| 23 | /** |
| 24 | * Retrieve a token from a file. |
| 25 | */ |
| 26 | class FileSource implements ExternalAccountCredentialSourceInterface |
| 27 | { |
| 28 | private string $file; |
| 29 | private ?string $format; |
| 30 | private ?string $subjectTokenFieldName; |
| 31 | /** |
| 32 | * @param string $file The file to read the subject token from. |
| 33 | * @param string $format The format of the token in the file. Can be null or "json". |
| 34 | * @param string $subjectTokenFieldName The name of the field containing the token in the file. This is required |
| 35 | * when format is "json". |
| 36 | */ |
| 37 | public function __construct(string $file, ?string $format = null, ?string $subjectTokenFieldName = null) |
| 38 | { |
| 39 | $this->file = $file; |
| 40 | if ($format === 'json' && \is_null($subjectTokenFieldName)) { |
| 41 | throw new InvalidArgumentException('subject_token_field_name must be set when format is JSON'); |
| 42 | } |
| 43 | $this->format = $format; |
| 44 | $this->subjectTokenFieldName = $subjectTokenFieldName; |
| 45 | } |
| 46 | public function fetchSubjectToken(?callable $httpHandler = null) : string |
| 47 | { |
| 48 | $contents = \file_get_contents($this->file); |
| 49 | if ($this->format === 'json') { |
| 50 | if (!($json = \json_decode((string) $contents, \true))) { |
| 51 | throw new UnexpectedValueException('Unable to decode JSON file'); |
| 52 | } |
| 53 | if (!isset($json[$this->subjectTokenFieldName])) { |
| 54 | throw new UnexpectedValueException('subject_token_field_name not found in JSON file'); |
| 55 | } |
| 56 | $contents = $json[$this->subjectTokenFieldName]; |
| 57 | } |
| 58 | return $contents; |
| 59 | } |
| 60 | } |
| 61 |