Completed
Pull Request — master (#499)
by
unknown
08:38
created

Application::registerProviders()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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