Completed
Pull Request — master (#421)
by Carlos
03:18
created

Application::addProvider()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
3
/*
4
 * This file is part of the overtrue/wechat.
5
 *
6
 * (c) overtrue <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
/**
13
 * Application.php.
14
 *
15
 * Part of Overtrue\WeChat.
16
 *
17
 * For the full copyright and license information, please view the LICENSE
18
 * file that was distributed with this source code.
19
 *
20
 * @author    overtrue <[email protected]>
21
 * @copyright 2015
22
 *
23
 * @link      https://github.com/overtrue/wechat
24
 * @link      http://overtrue.me
25
 */
26
namespace EasyWeChat\Foundation;
27
28
use Doctrine\Common\Cache\FilesystemCache;
29
use EasyWeChat\Core\AccessToken;
30
use EasyWeChat\Core\Http;
31
use EasyWeChat\Support\Log;
32
use Monolog\Handler\NullHandler;
33
use Monolog\Handler\StreamHandler;
34
use Monolog\Logger;
35
use Pimple\Container;
36
use Symfony\Component\HttpFoundation\Request;
37
38
/**
39
 * Class Application.
40
 *
41
 * @property \EasyWeChat\Server\Guard                    $server
42
 * @property \EasyWeChat\User\User                       $user
43
 * @property \EasyWeChat\User\Group                      $user_group
44
 * @property \EasyWeChat\Js\Js                           $js
45
 * @property \Overtrue\Socialite\SocialiteManager        $oauth
46
 * @property \EasyWeChat\Menu\Menu                       $menu
47
 * @property \EasyWeChat\Notice\Notice                   $notice
48
 * @property \EasyWeChat\Material\Material               $material
49
 * @property \EasyWeChat\Material\Temporary              $material_temporary
50
 * @property \EasyWeChat\Staff\Staff                     $staff
51
 * @property \EasyWeChat\Url\Url                         $url
52
 * @property \EasyWeChat\QRCode\QRCode                   $qrcode
53
 * @property \EasyWeChat\Semantic\Semantic               $semantic
54
 * @property \EasyWeChat\Stats\Stats                     $stats
55
 * @property \EasyWeChat\Payment\Merchant                $merchant
56
 * @property \EasyWeChat\Payment\Payment                 $payment
57
 * @property \EasyWeChat\Payment\LuckyMoney\LuckyMoney   $lucky_money
58
 * @property \EasyWeChat\Payment\MerchantPay\MerchantPay $merchant_pay
59
 * @property \EasyWeChat\Reply\Reply                     $reply
60
 * @property \EasyWeChat\Broadcast\Broadcast             $broadcast
61
 */
62
class Application extends Container
63
{
64
    /**
65
     * Service Providers.
66
     *
67
     * @var array
68
     */
69
    protected $providers = [
70
        ServiceProviders\ServerServiceProvider::class,
71
        ServiceProviders\UserServiceProvider::class,
72
        ServiceProviders\JsServiceProvider::class,
73
        ServiceProviders\OAuthServiceProvider::class,
74
        ServiceProviders\MenuServiceProvider::class,
75
        ServiceProviders\NoticeServiceProvider::class,
76
        ServiceProviders\MaterialServiceProvider::class,
77
        ServiceProviders\StaffServiceProvider::class,
78
        ServiceProviders\UrlServiceProvider::class,
79
        ServiceProviders\QRCodeServiceProvider::class,
80
        ServiceProviders\SemanticServiceProvider::class,
81
        ServiceProviders\StatsServiceProvider::class,
82
        ServiceProviders\PaymentServiceProvider::class,
83
        ServiceProviders\POIServiceProvider::class,
84
        ServiceProviders\ReplyServiceProvider::class,
85
        ServiceProviders\BroadcastServiceProvider::class,
86
    ];
87
88
    /**
89
     * Application constructor.
90
     *
91
     * @param array $config
92
     */
93 4
    public function __construct($config)
94
    {
95 4
        parent::__construct();
96
97
        $this['config'] = function () use ($config) {
98 4
            return new Config($config);
99
        };
100
101 4
        if ($this['config']['debug']) {
102
            error_reporting(E_ALL);
103
        }
104
105 4
        $this->registerProviders();
106 4
        $this->registerBase();
107 4
        $this->initializeLogger();
108
109 4
        Http::setDefaultOptions($this['config']->get('guzzle', ['timeout' => 5.0]));
110
111 4
        foreach (['app_id', 'secret'] as $key) {
112 4
            !isset($config[$key]) || $config[$key] = '***'.substr($config[$key], -5);
113 4
        }
114
115 4
        Log::debug('Current config:', $config);
116 4
    }
117
118
    /**
119
     * Add a provider.
120
     *
121
     * @param string $provider
122
     *
123
     * @return Application
124
     */
125 1
    public function addProvider($provider)
126
    {
127 1
        array_push($this->providers, $provider);
128
129 1
        return $this;
130
    }
131
132
    /**
133
     * Set providers.
134
     *
135
     * @param array $providers
136
     */
137 1
    public function setProviders(array $providers)
138
    {
139 1
        $this->providers = [];
140
141 1
        foreach ($providers as $provider) {
142 1
            $this->addProvider($provider);
143 1
        }
144 1
    }
145
146
    /**
147
     * Return all providers.
148
     *
149
     * @return array
150
     */
151 2
    public function getProviders()
152
    {
153 2
        return $this->providers;
154
    }
155
156
    /**
157
     * Magic get access.
158
     *
159
     * @param string $id
160
     *
161
     * @return mixed
162
     */
163 1
    public function __get($id)
164
    {
165 1
        return $this->offsetGet($id);
166
    }
167
168
    /**
169
     * Magic set access.
170
     *
171
     * @param string $id
172
     * @param mixed  $value
173
     */
174 1
    public function __set($id, $value)
175
    {
176 1
        $this->offsetSet($id, $value);
177 1
    }
178
179
    /**
180
     * Register providers.
181
     */
182 4
    private function registerProviders()
183
    {
184 4
        foreach ($this->providers as $provider) {
185 4
            $this->register(new $provider());
186 4
        }
187 4
    }
188
189
    /**
190
     * Register basic providers.
191
     */
192 4
    private function registerBase()
193
    {
194
        $this['request'] = function () {
195
            return Request::createFromGlobals();
196
        };
197
198
        $this['cache'] = function () {
199
            return new FilesystemCache(sys_get_temp_dir());
200
        };
201
202
        $this['access_token'] = function () {
203
           return new AccessToken(
204
               $this['config']['app_id'],
205
               $this['config']['secret'],
206
               $this['cache']
207
           );
208
        };
209 4
    }
210
211
    /**
212
     * Initialize logger.
213
     */
214 4
    private function initializeLogger()
215
    {
216 4
        if (Log::hasLogger()) {
217 4
            return;
218
        }
219
220
        $logger = new Logger('easywechat');
221
222
        if (!$this['config']['debug'] || defined('PHPUNIT_RUNNING')) {
223
            $logger->pushHandler(new NullHandler());
224
        } elseif ($logFile = $this['config']['log.file']) {
225
            $logger->pushHandler(new StreamHandler($logFile, $this['config']->get('log.level', Logger::WARNING)));
226
        }
227
228
        Log::setLogger($logger);
229
    }
230
}
231