Completed
Push — master ( 1280db...f286a8 )
by Carlos
03:04
created

Application::setProviders()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 8
ccs 6
cts 6
cp 1
crap 2
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 Closure;
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 InvalidArgumentException;
35
use Monolog\Handler\HandlerInterface;
36
use Monolog\Handler\NullHandler;
37
use Monolog\Handler\StreamHandler;
38
use Monolog\Logger;
39
use Pimple\Container;
40
use Symfony\Component\HttpFoundation\Request;
41
42
/**
43
 * Class Application.
44
 *
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
 */
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
    ];
94
95
    /**
96
     * Application constructor.
97
     *
98
     * @param array $config
99
     */
100 5
    public function __construct($config)
101
    {
102 5
        parent::__construct();
103
104
        $this['config'] = function () use ($config) {
105 5
            return new Config($config);
106
        };
107
108 5
        if ($this['config']['debug']) {
109
            error_reporting(E_ALL);
110
        }
111
112 5
        $this->registerProviders();
113 5
        $this->registerBase();
114 5
        $this->initializeLogger();
115
116 5
        Http::setDefaultOptions($this['config']->get('guzzle', ['timeout' => 5.0]));
117
118 5
        foreach (['app_id', 'secret'] as $key) {
119 5
            !isset($config[$key]) || $config[$key] = '***'.substr($config[$key], -5);
120 5
        }
121
122 5
        Log::debug('Current config:', $config);
123 5
    }
124
125
    /**
126
     * Add a provider.
127
     *
128
     * @param string $provider
129
     *
130
     * @return Application
131
     */
132 1
    public function addProvider($provider)
133
    {
134 1
        array_push($this->providers, $provider);
135
136 1
        return $this;
137
    }
138
139
    /**
140
     * Set providers.
141
     *
142
     * @param array $providers
143
     */
144 1
    public function setProviders(array $providers)
145
    {
146 1
        $this->providers = [];
147
148 1
        foreach ($providers as $provider) {
149 1
            $this->addProvider($provider);
150 1
        }
151 1
    }
152
153
    /**
154
     * Return all providers.
155
     *
156
     * @return array
157
     */
158 2
    public function getProviders()
159
    {
160 2
        return $this->providers;
161
    }
162
163
    /**
164
     * Magic get access.
165
     *
166
     * @param string $id
167
     *
168
     * @return mixed
169
     */
170 1
    public function __get($id)
171
    {
172 1
        return $this->offsetGet($id);
173
    }
174
175
    /**
176
     * Magic set access.
177
     *
178
     * @param string $id
179
     * @param mixed  $value
180
     */
181 1
    public function __set($id, $value)
182
    {
183 1
        $this->offsetSet($id, $value);
184 1
    }
185
186
    /**
187
     * Register providers.
188
     */
189 5
    private function registerProviders()
190
    {
191 5
        foreach ($this->providers as $provider) {
192 5
            $this->register(new $provider());
193 5
        }
194 5
    }
195
196
    /**
197
     * Register basic providers.
198
     */
199 5
    private function registerBase()
200
    {
201
        $this['request'] = function () {
202
            return Request::createFromGlobals();
203
        };
204
205 5
        if (!empty($this['config']['cache']) && $this['config']['cache'] instanceof CacheInterface) {
206
            $this['cache'] = $this['config']['cache'];
207
        } else {
208
            $this['cache'] = function () {
209 1
                return new FilesystemCache(sys_get_temp_dir());
210
            };
211
        }
212
213 1
        $this['access_token'] = function () {
214 1
            return new AccessToken(
215 1
                $this['config']['app_id'],
216 1
                $this['config']['secret'],
217 1
                $this['cache']
218 1
            );
219
        };
220 5
    }
221
222
    /**
223
     * Initialize logger.
224
     */
225 5
    private function initializeLogger()
226
    {
227 5
        if (Log::hasLogger()) {
228 5
            return;
229
        }
230
231
        $logger = new Logger('easywechat');
232
233
        if (!$this['config']['debug'] || defined('PHPUNIT_RUNNING')) {
234
            $logger->pushHandler(new NullHandler());
235
        } elseif ($this['config']['log.handler'] instanceof HandlerInterface) {
236
            $logger->pushHandler($this['config']['log.handler']);
237
        } elseif ($logFile = $this['config']['log.file']) {
238
            $logger->pushHandler(new StreamHandler($logFile, $this['config']->get('log.level', Logger::WARNING)));
239
        }
240
241
        Log::setLogger($logger);
242
    }
243
}
244