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