Completed
Pull Request — master (#590)
by
unknown
03:20
created

Application::__set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
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\OpenPlatform\OpenPlatform       $open_platform
70
 * @property \EasyWeChat\MiniProgram\MiniProgram         $mini_program
71
 */
72
class Application extends Container
73
{
74
    /**
75
     * Service Providers.
76
     *
77
     * @var array
78
     */
79
    protected $providers = [
80
        ServiceProviders\ServerServiceProvider::class,
81
        ServiceProviders\UserServiceProvider::class,
82
        ServiceProviders\JsServiceProvider::class,
83
        ServiceProviders\OAuthServiceProvider::class,
84
        ServiceProviders\MenuServiceProvider::class,
85
        ServiceProviders\NoticeServiceProvider::class,
86
        ServiceProviders\MaterialServiceProvider::class,
87
        ServiceProviders\StaffServiceProvider::class,
88
        ServiceProviders\UrlServiceProvider::class,
89
        ServiceProviders\QRCodeServiceProvider::class,
90
        ServiceProviders\SemanticServiceProvider::class,
91
        ServiceProviders\StatsServiceProvider::class,
92
        ServiceProviders\PaymentServiceProvider::class,
93
        ServiceProviders\POIServiceProvider::class,
94
        ServiceProviders\ReplyServiceProvider::class,
95
        ServiceProviders\BroadcastServiceProvider::class,
96
        ServiceProviders\CardServiceProvider::class,
97
        ServiceProviders\DeviceServiceProvider::class,
98
        ServiceProviders\ShakeAroundServiceProvider::class,
99
        ServiceProviders\OpenPlatformServiceProvider::class,
100
        ServiceProviders\MiniProgramServiceProvider::class,
101
    ];
102
103
    /**
104
     * Application constructor.
105
     *
106
     * @param array $config
107
     */
108 5
    public function __construct($config)
109
    {
110 5
        parent::__construct();
111
112
        $this['config'] = function () use ($config) {
113 5
            return new Config($config);
114
        };
115
116 5
        if ($this['config']['debug']) {
117
            error_reporting(E_ALL);
118
        }
119
120 5
        $this->registerProviders();
121 5
        $this->registerBase();
122 5
        $this->initializeLogger();
123
124 5
        Http::setDefaultOptions($this['config']->get('guzzle', ['timeout' => 5.0]));
125
126 5
        foreach (['app_id', 'secret'] as $key) {
127 5
            !isset($config[$key]) || $config[$key] = '***'.substr($config[$key], -5);
128
        }
129
130 5
        Log::debug('Current config:', $config);
131 5
    }
132
133
    /**
134
     * Add a provider.
135
     *
136
     * @param string $provider
137
     *
138
     * @return Application
139
     */
140 1
    public function addProvider($provider)
141
    {
142 1
        array_push($this->providers, $provider);
143
144 1
        return $this;
145
    }
146
147
    /**
148
     * Set providers.
149
     *
150
     * @param array $providers
151
     */
152 1
    public function setProviders(array $providers)
153
    {
154 1
        $this->providers = [];
155
156 1
        foreach ($providers as $provider) {
157 1
            $this->addProvider($provider);
158
        }
159 1
    }
160
161
    /**
162
     * Return all providers.
163
     *
164
     * @return array
165
     */
166 2
    public function getProviders()
167
    {
168 2
        return $this->providers;
169
    }
170
171
    /**
172
     * Magic get access.
173
     *
174
     * @param string $id
175
     *
176
     * @return mixed
177
     */
178 1
    public function __get($id)
179
    {
180 1
        return $this->offsetGet($id);
181
    }
182
183
    /**
184
     * Magic set access.
185
     *
186
     * @param string $id
187
     * @param mixed  $value
188
     */
189 1
    public function __set($id, $value)
190
    {
191 1
        $this->offsetSet($id, $value);
192 1
    }
193
194
    /**
195
     * Register providers.
196
     */
197 5
    private function registerProviders()
198
    {
199 5
        foreach ($this->providers as $provider) {
200 5
            $this->register(new $provider());
201
        }
202 5
    }
203
204
    /**
205
     * Register basic providers.
206
     */
207 5
    private function registerBase()
208
    {
209
        $this['request'] = function () {
210
            return Request::createFromGlobals();
211
        };
212
213 5
        if (!empty($this['config']['cache']) && $this['config']['cache'] instanceof CacheInterface) {
214
            $this['cache'] = $this['config']['cache'];
215
        } else {
216
            $this['cache'] = function () {
217 1
                return new FilesystemCache(sys_get_temp_dir());
218
            };
219
        }
220
221 1
        $this['access_token'] = function () {
222 1
            return new AccessToken(
223 1
                $this['config']['app_id'],
224 1
                $this['config']['secret'],
225 1
                $this['cache']
226
            );
227
        };
228 5
    }
229
230
    /**
231
     * Initialize logger.
232
     */
233 5
    private function initializeLogger()
234
    {
235 5
        if (Log::hasLogger()) {
236 5
            return;
237
        }
238
239
        $logger = new Logger('easywechat');
240
241
        if (!$this['config']['debug'] || defined('PHPUNIT_RUNNING')) {
242
            $logger->pushHandler(new NullHandler());
243
        } elseif ($this['config']['log.handler'] instanceof HandlerInterface) {
244
            $logger->pushHandler($this['config']['log.handler']);
245
        } elseif ($logFile = $this['config']['log.file']) {
246
            $logger->pushHandler(new StreamHandler(
247
                $logFile,
248
                $this['config']->get('log.level', Logger::WARNING),
249
                true,
250
                $this['config']->get('log.permission', null))
251
            );
252
        }
253
254
        Log::setLogger($logger);
255
    }
256
}
257