Completed
Pull Request — master (#554)
by
unknown
02:32
created

Application::__get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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