| 1 |
<?php |
| 2 |
/* |
| 3 |
* Copyright 2015 Google Inc. |
| 4 |
* |
| 5 |
* Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 |
* you may not use this file except in compliance with the License. |
| 7 |
* You may obtain a copy of the License at |
| 8 |
* |
| 9 |
* http://www.apache.org/licenses/LICENSE-2.0 |
| 10 |
* |
| 11 |
* Unless required by applicable law or agreed to in writing, software |
| 12 |
* distributed under the License is distributed on an "AS IS" BASIS, |
| 13 |
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 |
* See the License for the specific language governing permissions and |
| 15 |
* limitations under the License. |
| 16 |
*/ |
| 17 |
|
| 18 |
namespace Google\Auth\Subscriber; |
| 19 |
|
| 20 |
use GuzzleHttp\Event\BeforeEvent; |
| 21 |
use GuzzleHttp\Event\RequestEvents; |
| 22 |
use GuzzleHttp\Event\SubscriberInterface; |
| 23 |
|
| 24 |
/** |
| 25 |
* SimpleSubscriber is a Guzzle Subscriber that implements Google's Simple API |
| 26 |
* access. |
| 27 |
* |
| 28 |
* Requests are accessed using the Simple API access developer key. |
| 29 |
*/ |
| 30 |
class SimpleSubscriber implements SubscriberInterface |
| 31 |
{ |
| 32 |
/** @var configuration */ |
| 33 |
private $config; |
| 34 |
|
| 35 |
/** |
| 36 |
* Create a new Simple plugin. |
| 37 |
* |
| 38 |
* The configuration array expects one option |
| 39 |
* - key: required, otherwise InvalidArgumentException is thrown |
| 40 |
* |
| 41 |
* @param array $config Configuration array |
| 42 |
*/ |
| 43 |
public function __construct(array $config) |
| 44 |
{ |
| 45 |
if (!isset($config['key'])) { |
| 46 |
throw new \InvalidArgumentException('requires a key to have been set'); |
| 47 |
} |
| 48 |
|
| 49 |
$this->config = array_merge([], $config); |
| 50 |
} |
| 51 |
|
| 52 |
/* Implements SubscriberInterface */ |
| 53 |
public function getEvents() |
| 54 |
{ |
| 55 |
return ['before' => ['onBefore', RequestEvents::SIGN_REQUEST]]; |
| 56 |
} |
| 57 |
|
| 58 |
/** |
| 59 |
* Updates the request query with the developer key if auth is set to simple |
| 60 |
* |
| 61 |
* use Google\Auth\Subscriber\SimpleSubscriber; |
| 62 |
* use GuzzleHttp\Client; |
| 63 |
* |
| 64 |
* $my_key = 'is not the same as yours'; |
| 65 |
* $subscriber = new SimpleSubscriber(['key' => $my_key]); |
| 66 |
* |
| 67 |
* $client = new Client([ |
| 68 |
* 'base_url' => 'https://www.googleapis.com/discovery/v1/', |
| 69 |
* 'defaults' => ['auth' => 'simple'] |
| 70 |
* ]); |
| 71 |
* $client->getEmitter()->attach($subscriber); |
| 72 |
* |
| 73 |
* $res = $client->get('drive/v2/rest'); |
| 74 |
*/ |
| 75 |
public function onBefore(BeforeEvent $event) |
| 76 |
{ |
| 77 |
// Requests using "auth"="simple" with the developer key. |
| 78 |
$request = $event->getRequest(); |
| 79 |
if ($request->getConfig()['auth'] != 'simple') { |
| 80 |
return; |
| 81 |
} |
| 82 |
$request->getQuery()->overwriteWith($this->config); |
| 83 |
} |
| 84 |
} |
| 85 |
|