Completed
Push — master ( b6898b...f0c41e )
by Carlos
05:47 queued 02:03
created

Application::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2.0185

Importance

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