Subversion Repositories cheapmusic

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
103 - 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
    /**
33
     * @var array
34
     */
35
    private $config;
36
 
37
    /**
38
     * Create a new Simple plugin.
39
     *
40
     * The configuration array expects one option
41
     * - key: required, otherwise InvalidArgumentException is thrown
42
     *
43
     * @param array $config Configuration array
44
     */
45
    public function __construct(array $config)
46
    {
47
        if (!isset($config['key'])) {
48
            throw new \InvalidArgumentException('requires a key to have been set');
49
        }
50
 
51
        $this->config = array_merge([], $config);
52
    }
53
 
54
    /**
55
     * @return array
56
     */
57
    public function getEvents()
58
    {
59
        return ['before' => ['onBefore', RequestEvents::SIGN_REQUEST]];
60
    }
61
 
62
    /**
63
     * Updates the request query with the developer key if auth is set to simple.
64
     *
65
     *   use Google\Auth\Subscriber\SimpleSubscriber;
66
     *   use GuzzleHttp\Client;
67
     *
68
     *   $my_key = 'is not the same as yours';
69
     *   $subscriber = new SimpleSubscriber(['key' => $my_key]);
70
     *
71
     *   $client = new Client([
72
     *      'base_url' => 'https://www.googleapis.com/discovery/v1/',
73
     *      'defaults' => ['auth' => 'simple']
74
     *   ]);
75
     *   $client->getEmitter()->attach($subscriber);
76
     *
77
     *   $res = $client->get('drive/v2/rest');
78
     *
79
     * @param BeforeEvent $event
80
     */
81
    public function onBefore(BeforeEvent $event)
82
    {
83
        // Requests using "auth"="simple" with the developer key.
84
        $request = $event->getRequest();
85
        if ($request->getConfig()['auth'] != 'simple') {
86
            return;
87
        }
88
        $request->getQuery()->overwriteWith($this->config);
89
    }
90
}