Application.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. <?php
  2. /*
  3. * This file is part of the overtrue/wechat.
  4. *
  5. * (c) overtrue <i@overtrue.me>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. /**
  11. * Application.php.
  12. *
  13. * Part of Overtrue\WeChat.
  14. *
  15. * For the full copyright and license information, please view the LICENSE
  16. * file that was distributed with this source code.
  17. *
  18. * @author overtrue <i@overtrue.me>
  19. * @copyright 2015
  20. *
  21. * @see https://github.com/overtrue
  22. * @see http://overtrue.me
  23. */
  24. namespace EasyWeChat\Foundation;
  25. use Doctrine\Common\Cache\Cache as CacheInterface;
  26. use Doctrine\Common\Cache\FilesystemCache;
  27. use EasyWeChat\Core\AbstractAPI;
  28. use EasyWeChat\Core\AccessToken;
  29. use EasyWeChat\Core\Http;
  30. use EasyWeChat\Support\Log;
  31. use Monolog\Handler\HandlerInterface;
  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. * Class Application.
  39. *
  40. * @property \EasyWeChat\Core\AccessToken $access_token
  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\Providers\WeChatProvider $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\Payment\CashCoupon\CashCoupon $cash_coupon
  61. * @property \EasyWeChat\Reply\Reply $reply
  62. * @property \EasyWeChat\Broadcast\Broadcast $broadcast
  63. * @property \EasyWeChat\Card\Card $card
  64. * @property \EasyWeChat\Device\Device $device
  65. * @property \EasyWeChat\Comment\Comment $comment
  66. * @property \EasyWeChat\ShakeAround\ShakeAround $shakearound
  67. * @property \EasyWeChat\OpenPlatform\OpenPlatform $open_platform
  68. * @property \EasyWeChat\MiniProgram\MiniProgram $mini_program
  69. *
  70. * @method \EasyWeChat\Support\Collection clearQuota()
  71. * @method \EasyWeChat\Support\Collection getCallbackIp()
  72. */
  73. class Application extends Container
  74. {
  75. /**
  76. * Service Providers.
  77. *
  78. * @var array
  79. */
  80. protected $providers = [
  81. ServiceProviders\FundamentalServiceProvider::class,
  82. ServiceProviders\ServerServiceProvider::class,
  83. ServiceProviders\UserServiceProvider::class,
  84. ServiceProviders\JsServiceProvider::class,
  85. ServiceProviders\OAuthServiceProvider::class,
  86. ServiceProviders\MenuServiceProvider::class,
  87. ServiceProviders\NoticeServiceProvider::class,
  88. ServiceProviders\MaterialServiceProvider::class,
  89. ServiceProviders\StaffServiceProvider::class,
  90. ServiceProviders\UrlServiceProvider::class,
  91. ServiceProviders\QRCodeServiceProvider::class,
  92. ServiceProviders\SemanticServiceProvider::class,
  93. ServiceProviders\StatsServiceProvider::class,
  94. ServiceProviders\PaymentServiceProvider::class,
  95. ServiceProviders\POIServiceProvider::class,
  96. ServiceProviders\ReplyServiceProvider::class,
  97. ServiceProviders\BroadcastServiceProvider::class,
  98. ServiceProviders\CardServiceProvider::class,
  99. ServiceProviders\DeviceServiceProvider::class,
  100. ServiceProviders\ShakeAroundServiceProvider::class,
  101. ServiceProviders\OpenPlatformServiceProvider::class,
  102. ServiceProviders\MiniProgramServiceProvider::class,
  103. ServiceProviders\CommentServiceProvider::class,
  104. ];
  105. /**
  106. * Application constructor.
  107. *
  108. * @param array $config
  109. */
  110. public function __construct($config)
  111. {
  112. parent::__construct();
  113. $this['config'] = function () use ($config) {
  114. return new Config($config);
  115. };
  116. $this->registerProviders();
  117. $this->registerBase();
  118. $this->initializeLogger();
  119. Http::setDefaultOptions($this['config']->get('guzzle', ['timeout' => 5.0]));
  120. AbstractAPI::maxRetries($this['config']->get('max_retries', 2));
  121. $this->logConfiguration($config);
  122. }
  123. /**
  124. * Log configuration.
  125. *
  126. * @param array $config
  127. */
  128. public function logConfiguration($config)
  129. {
  130. $config = new Config($config);
  131. $keys = ['app_id', 'secret', 'open_platform.app_id', 'open_platform.secret', 'mini_program.app_id', 'mini_program.secret'];
  132. foreach ($keys as $key) {
  133. !$config->has($key) || $config[$key] = '***'.substr($config[$key], -5);
  134. }
  135. Log::debug('Current config:', $config->toArray());
  136. }
  137. /**
  138. * Add a provider.
  139. *
  140. * @param string $provider
  141. *
  142. * @return Application
  143. */
  144. public function addProvider($provider)
  145. {
  146. array_push($this->providers, $provider);
  147. return $this;
  148. }
  149. /**
  150. * Set providers.
  151. *
  152. * @param array $providers
  153. */
  154. public function setProviders(array $providers)
  155. {
  156. $this->providers = [];
  157. foreach ($providers as $provider) {
  158. $this->addProvider($provider);
  159. }
  160. }
  161. /**
  162. * Return all providers.
  163. *
  164. * @return array
  165. */
  166. public function getProviders()
  167. {
  168. return $this->providers;
  169. }
  170. /**
  171. * Magic get access.
  172. *
  173. * @param string $id
  174. *
  175. * @return mixed
  176. */
  177. public function __get($id)
  178. {
  179. return $this->offsetGet($id);
  180. }
  181. /**
  182. * Magic set access.
  183. *
  184. * @param string $id
  185. * @param mixed $value
  186. */
  187. public function __set($id, $value)
  188. {
  189. $this->offsetSet($id, $value);
  190. }
  191. /**
  192. * Register providers.
  193. */
  194. private function registerProviders()
  195. {
  196. foreach ($this->providers as $provider) {
  197. $this->register(new $provider());
  198. }
  199. }
  200. /**
  201. * Register basic providers.
  202. */
  203. private function registerBase()
  204. {
  205. $this['request'] = function () {
  206. return Request::createFromGlobals();
  207. };
  208. if (!empty($this['config']['cache']) && $this['config']['cache'] instanceof CacheInterface) {
  209. $this['cache'] = $this['config']['cache'];
  210. } else {
  211. $this['cache'] = function () {
  212. return new FilesystemCache(sys_get_temp_dir());
  213. };
  214. }
  215. $this['access_token'] = function () {
  216. return new AccessToken(
  217. $this['config']['app_id'],
  218. $this['config']['secret'],
  219. $this['cache']
  220. );
  221. };
  222. }
  223. /**
  224. * Initialize logger.
  225. */
  226. private function initializeLogger()
  227. {
  228. if (Log::hasLogger()) {
  229. return;
  230. }
  231. $logger = new Logger('easywechat');
  232. if (!$this['config']['debug'] || defined('PHPUNIT_RUNNING')) {
  233. $logger->pushHandler(new NullHandler());
  234. } elseif ($this['config']['log.handler'] instanceof HandlerInterface) {
  235. $logger->pushHandler($this['config']['log.handler']);
  236. } elseif ($logFile = $this['config']['log.file']) {
  237. $logger->pushHandler(new StreamHandler(
  238. $logFile,
  239. $this['config']->get('log.level', Logger::WARNING),
  240. true,
  241. $this['config']->get('log.permission', null))
  242. );
  243. }
  244. Log::setLogger($logger);
  245. }
  246. /**
  247. * Magic call.
  248. *
  249. * @param string $method
  250. * @param array $args
  251. *
  252. * @return mixed
  253. *
  254. * @throws \Exception
  255. */
  256. public function __call($method, $args)
  257. {
  258. if (is_callable([$this['fundamental.api'], $method])) {
  259. return call_user_func_array([$this['fundamental.api'], $method], $args);
  260. }
  261. throw new \Exception("Call to undefined method {$method}()");
  262. }
  263. }