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