Application::account()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace YEntWeChat\Foundation;
4
5
use Doctrine\Common\Cache\Cache as CacheInterface;
6
use Doctrine\Common\Cache\FilesystemCache;
7
use YEntWeChat\Core\AccessToken;
8
use YEntWeChat\Core\Exceptions\InvalidConfigException;
9
use YEntWeChat\Core\Http;
10
use YEntWeChat\Support\Log;
11
use Monolog\Handler\HandlerInterface;
12
use Monolog\Handler\NullHandler;
13
use Monolog\Handler\StreamHandler;
14
use Monolog\Logger;
15
use Pimple\Container;
16
use Symfony\Component\HttpFoundation\Request;
17
18
/**
19
 * Class Application.
20
 *
21
 * @property \EntWeChat\Core\AccessToken                $access_token
22
 * @property \EntWeChat\Server\Guard                    $server
23
 * @property \EntWeChat\User\User                       $user
24
 * @property \EntWeChat\User\Tag                        $user_tag
25
 * @property \EntWeChat\User\Department                 $user_department
26
 * @property \EntWeChat\User\Batch                      $user_batch
27
 * @property \EntWeChat\Js\Js                           $js
28
 * @property \EntWeChat\Js\Contact                      $js_contact
29
 * @property \EntWeChat\Menu\Menu                       $menu
30
 * @property \EntWeChat\Broadcast\Broadcast             $broadcast
31
 * @property \EntWeChat\Material\Material               $material
32
 * @property \EntWeChat\Material\Temporary              $material_temporary
33
 * @property \EntWeChat\Card\Card                       $card
34
 * @property \EntWeChat\Agent\Agent                     $agent
35
 * @property \EntWeChat\Chat\Chat                       $chat
36
 * @property \EntWeChat\ShakeAround\ShakeAround         $shakearound
37
 * @property \EntWeChat\Soter\Soter                     $soter
38
 * @property \EntWeChat\Payment\Merchant                $merchant
39
 * @property \EntWeChat\Payment\Payment                 $payment
40
 * @property \EntWeChat\Payment\LuckyMoney\LuckyMoney   $lucky_money
41
 * @property \EntWeChat\Payment\MerchantPay\MerchantPay $merchant_pay
42
 * @property \EntWeChat\Payment\CashCoupon\CashCoupon   $cash_coupon
43
 * @property \EntWeChat\Auth\App                        $oauth
44
 * @property \EntWeChat\Auth\Web                        $auth
45
 * @property \EntWeChat\Staff\Staff                     $staff
46
 * @property \EntWeChat\Suite\Suite                     $suite
47
 * @property \EntWeChat\OA\API                          $oa
48
 *
49
 * @method \EntWeChat\Support\Collection getCallbackIp()
50
 */
51
class Application extends Container
52
{
53
    /**
54
     * Service Providers.
55
     *
56
     * @var array
57
     */
58
    protected $providers = [
59
        ServiceProviders\ServerServiceProvider::class,
60
        ServiceProviders\UserServiceProvider::class,
61
        ServiceProviders\JsServiceProvider::class,
62
        ServiceProviders\MenuServiceProvider::class,
63
        ServiceProviders\BroadcastServiceProvider::class,
64
        ServiceProviders\CardServiceProvider::class,
65
        ServiceProviders\MaterialServiceProvider::class,
66
        ServiceProviders\AgentServiceProvider::class,
67
        ServiceProviders\ChatServiceProvider::class,
68
        ServiceProviders\SoterServiceProvider::class,
69
        ServiceProviders\OAuthServiceProvider::class,
70
        ServiceProviders\PaymentServiceProvider::class,
71
        ServiceProviders\ShakeAroundServiceProvider::class,
72
        ServiceProviders\StaffServiceProvider::class,
73
        ServiceProviders\SuiteServiceProvider::class,
74
        ServiceProviders\FundamentalServiceProvider::class,
75
        ServiceProviders\OAServiceProvider::class,
76
    ];
77
78
    /**
79
     * Application constructor.
80
     *
81
     * @param array $config
82
     */
83
    public function __construct($config)
84
    {
85
        parent::__construct();
86
87
        $this['config'] = function () use ($config) {
88
            return new Config($config);
89
        };
90
91
        if ($this['config']['debug']) {
92
            error_reporting(E_ALL);
93
        }
94
95
        $this->registerProviders();
96
        $this->registerBase();
0 ignored issues
show
Unused Code introduced by
The call to the method YEntWeChat\Foundation\Application::registerBase() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
97
        $this->initializeLogger();
98
99
        Http::setDefaultOptions($this['config']->get('guzzle', ['timeout' => 5.0]));
100
101
        $this->logConfiguration($config);
102
    }
103
104
    /**
105
     * Load account.
106
     *
107
     * @param string $account
108
     *
109
     * @throws InvalidConfigException
110
     *
111
     * @return Application
112
     */
113
    public function account($account)
114
    {
115
        if (!isset($this['config']['account'][$account])) {
116
            throw new InvalidConfigException('This account not exist');
117
        }
118
119
        $this['config']->merge($this['config']['account'][$account]);
120
121
        return $this;
122
    }
123
124
    /**
125
     * Log configuration.
126
     *
127
     * @param array $config
128
     */
129
    public function logConfiguration($config)
130
    {
131
        $config = new Config($config);
132
133
        if ($config->has('account')) {
134
            $config->forget('account');
135
        }
136
137
        $keys = ['corp_id', 'secret', 'suite.suite_id', 'suite.secret'];
138
        foreach ($keys as $key) {
139
            !$config->has($key) || $config[$key] = '***'.substr($config[$key], -5);
140
        }
141
142
        Log::debug('Current config:', $config->toArray());
143
    }
144
145
    /**
146
     * Add a provider.
147
     *
148
     * @param string $provider
149
     *
150
     * @return Application
151
     */
152
    public function addProvider($provider)
153
    {
154
        array_push($this->providers, $provider);
155
156
        return $this;
157
    }
158
159
    /**
160
     * Set providers.
161
     *
162
     * @param array $providers
163
     */
164
    public function setProviders(array $providers)
165
    {
166
        $this->providers = [];
167
168
        foreach ($providers as $provider) {
169
            $this->addProvider($provider);
170
        }
171
    }
172
173
    /**
174
     * Return all providers.
175
     *
176
     * @return array
177
     */
178
    public function getProviders()
179
    {
180
        return $this->providers;
181
    }
182
183
    /**
184
     * Magic get access.
185
     *
186
     * @param string $id
187
     *
188
     * @return mixed
189
     */
190
    public function __get($id)
191
    {
192
        return $this->offsetGet($id);
193
    }
194
195
    /**
196
     * Magic set access.
197
     *
198
     * @param string $id
199
     * @param mixed  $value
200
     */
201
    public function __set($id, $value)
202
    {
203
        $this->offsetSet($id, $value);
204
    }
205
206
    /**
207
     * Register providers.
208
     */
209
    private function registerProviders()
210
    {
211
        foreach ($this->providers as $provider) {
212
            $this->register(new $provider());
213
        }
214
    }
215
216
    /**
217
     * Register basic providers.
218
     */
219
    private function registerBase()
220
    {
221
        $this['request'] = function () {
222
            return Request::createFromGlobals();
223
        };
224
225
        if (!empty($this['config']['cache']) && $this['config']['cache'] instanceof CacheInterface) {
226
            $this['cache'] = $this['config']['cache'];
227
        } else {
228
            $this['cache'] = function () {
229
                return new FilesystemCache(sys_get_temp_dir());
230
            };
231
        }
232
233
        $this['access_token'] = function () {
234
            return new AccessToken(
235
                $this['config']['corp_id'],
236
                $this['config']['secret'],
237
                $this['cache']
238
            );
239
        };
240
    }
241
242
    /**
243
     * Initialize logger.
244
     */
245
    private function initializeLogger()
246
    {
247
        if (Log::hasLogger()) {
248
            return;
249
        }
250
251
        $logger = new Logger('yentwechat');
252
253
        if (!$this['config']['debug'] || defined('PHPUNIT_RUNNING')) {
254
            $logger->pushHandler(new NullHandler());
255
        } elseif ($this['config']['log.handler'] instanceof HandlerInterface) {
256
            $logger->pushHandler($this['config']['log.handler']);
257
        } elseif ($logFile = $this['config']['log.file']) {
258
            $logger->pushHandler(new StreamHandler(
259
                $logFile,
260
                $this['config']->get('log.level', Logger::WARNING),
261
                true,
262
                $this['config']->get('log.permission', null)
263
            ));
264
        }
265
266
        Log::setLogger($logger);
267
    }
268
}
269