Completed
Pull Request — master (#449)
by
unknown
03:31
created

Application::registerBase()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 5.9862

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 3
eloc 13
c 2
b 0
f 1
nc 2
nop 0
dl 0
loc 22
ccs 4
cts 13
cp 0.3076
crap 5.9862
rs 9.2
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
27
namespace EasyWeChat\Foundation;
28
29
use Doctrine\Common\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\NullHandler;
35
use Monolog\Handler\StreamHandler;
36
use Monolog\Logger;
37
use Pimple\Container;
38
use Symfony\Component\HttpFoundation\Request;
39
40
/**
41
 * Class Application.
42
 *
43
 * @property \EasyWeChat\Server\Guard                    $server
44
 * @property \EasyWeChat\User\User                       $user
45
 * @property \EasyWeChat\User\Tag                        $user_tag
46
 * @property \EasyWeChat\User\Group                      $user_group
47
 * @property \EasyWeChat\Js\Js                           $js
48
 * @property \Overtrue\Socialite\SocialiteManager        $oauth
49
 * @property \EasyWeChat\Menu\Menu                       $menu
50
 * @property \EasyWeChat\Notice\Notice                   $notice
51
 * @property \EasyWeChat\Material\Material               $material
52
 * @property \EasyWeChat\Material\Temporary              $material_temporary
53
 * @property \EasyWeChat\Staff\Staff                     $staff
54
 * @property \EasyWeChat\Url\Url                         $url
55
 * @property \EasyWeChat\QRCode\QRCode                   $qrcode
56
 * @property \EasyWeChat\Semantic\Semantic               $semantic
57
 * @property \EasyWeChat\Stats\Stats                     $stats
58
 * @property \EasyWeChat\Payment\Merchant                $merchant
59
 * @property \EasyWeChat\Payment\Payment                 $payment
60
 * @property \EasyWeChat\Payment\LuckyMoney\LuckyMoney   $lucky_money
61
 * @property \EasyWeChat\Payment\MerchantPay\MerchantPay $merchant_pay
62
 * @property \EasyWeChat\Reply\Reply                     $reply
63
 * @property \EasyWeChat\Broadcast\Broadcast             $broadcast
64
 */
65
class Application extends Container
66
{
67
    /**
68
     * Service Providers.
69
     *
70
     * @var array
71
     */
72
    protected $providers = [
73
        ServiceProviders\ServerServiceProvider::class,
74
        ServiceProviders\UserServiceProvider::class,
75
        ServiceProviders\JsServiceProvider::class,
76
        ServiceProviders\OAuthServiceProvider::class,
77
        ServiceProviders\MenuServiceProvider::class,
78
        ServiceProviders\NoticeServiceProvider::class,
79
        ServiceProviders\MaterialServiceProvider::class,
80
        ServiceProviders\StaffServiceProvider::class,
81
        ServiceProviders\UrlServiceProvider::class,
82
        ServiceProviders\QRCodeServiceProvider::class,
83
        ServiceProviders\SemanticServiceProvider::class,
84
        ServiceProviders\StatsServiceProvider::class,
85
        ServiceProviders\PaymentServiceProvider::class,
86
        ServiceProviders\POIServiceProvider::class,
87
        ServiceProviders\ReplyServiceProvider::class,
88
        ServiceProviders\BroadcastServiceProvider::class,
89
    ];
90
91
    /**
92
     * Application constructor.
93
     *
94
     * @param array $config
95
     */
96 4
    public function __construct($config)
97
    {
98 4
        parent::__construct();
99
100
        $this['config'] = function () use ($config) {
101 4
            return new Config($config);
102
        };
103
104 4
        if ($this['config']['debug']) {
105
            error_reporting(E_ALL);
106
        }
107
108 4
        $this->registerProviders();
109 4
        $this->registerBase();
110 4
        $this->initializeLogger();
111
112 4
        Http::setDefaultOptions($this['config']->get('guzzle', ['timeout' => 5.0]));
113
114 4
        foreach (['app_id', 'secret'] as $key) {
115 4
            !isset($config[$key]) || $config[$key] = '***'.substr($config[$key], -5);
116 4
        }
117
118 4
        Log::debug('Current config:', $config);
119 4
    }
120
121
    /**
122
     * Add a provider.
123
     *
124
     * @param string $provider
125
     *
126
     * @return Application
127
     */
128 1
    public function addProvider($provider)
129
    {
130 1
        array_push($this->providers, $provider);
131
132 1
        return $this;
133
    }
134
135
    /**
136
     * Set providers.
137
     *
138
     * @param array $providers
139
     */
140 1
    public function setProviders(array $providers)
141
    {
142 1
        $this->providers = [];
143
144 1
        foreach ($providers as $provider) {
145 1
            $this->addProvider($provider);
146 1
        }
147 1
    }
148
149
    /**
150
     * Return all providers.
151
     *
152
     * @return array
153
     */
154 2
    public function getProviders()
155
    {
156 2
        return $this->providers;
157
    }
158
159
    /**
160
     * Magic get access.
161
     *
162
     * @param string $id
163
     *
164
     * @return mixed
165
     */
166 1
    public function __get($id)
167
    {
168 1
        return $this->offsetGet($id);
169
    }
170
171
    /**
172
     * Magic set access.
173
     *
174
     * @param string $id
175
     * @param mixed  $value
176
     */
177 1
    public function __set($id, $value)
178
    {
179 1
        $this->offsetSet($id, $value);
180 1
    }
181
182
    /**
183
     * Register providers.
184
     */
185 4
    private function registerProviders()
186
    {
187 4
        foreach ($this->providers as $provider) {
188 4
            $this->register(new $provider());
189 4
        }
190 4
    }
191
192
    /**
193
     * Register basic providers.
194
     */
195 4
    private function registerBase()
196
    {
197
        $this['request'] = function () {
198
            return Request::createFromGlobals();
199
        };
200
201 4
        if (!empty($this['config']['cache']) && $this['config']['cache'] instanceof CacheInterface) {
0 ignored issues
show
Bug introduced by
The class Doctrine\Common\Cache does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
202
            $this['cache'] = function () {
203
                return new FilesystemCache(sys_get_temp_dir());
204
            };
205
        } else {
206 4
            $this['cache'] = $this['config']['cache'];
207
        }
208
209
        $this['access_token'] = function () {
210
            return new AccessToken(
211
               $this['config']['app_id'],
212
               $this['config']['secret'],
213
               $this['cache']
214
           );
215
        };
216 4
    }
217
218
    /**
219
     * Initialize logger.
220
     */
221 4
    private function initializeLogger()
222
    {
223 4
        if (Log::hasLogger()) {
224 4
            return;
225
        }
226
227
        $logger = new Logger('easywechat');
228
229
        if (!$this['config']['debug'] || defined('PHPUNIT_RUNNING')) {
230
            $logger->pushHandler(new NullHandler());
231
        } elseif ($logFile = $this['config']['log.file']) {
232
            $logger->pushHandler(new StreamHandler($logFile, $this['config']->get('log.level', Logger::WARNING)));
233
        }
234
235
        Log::setLogger($logger);
236
    }
237
}
238