|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Hogus\LaravelMiniProgram; |
| 4 | + |
| 5 | +use Hogus\LaravelMiniProgram\Supports\Config; |
| 6 | + |
| 7 | +/** |
| 8 | + * Class MiniProgramManager |
| 9 | + * @package Hogus\LaravelMiniProgram |
| 10 | + */ |
| 11 | +class MiniProgramManager |
| 12 | +{ |
| 13 | + /** |
| 14 | + * @var Config |
| 15 | + */ |
| 16 | + protected $config; |
| 17 | + |
| 18 | + /** |
| 19 | + * @var array |
| 20 | + */ |
| 21 | + protected $gateways = []; |
| 22 | + |
| 23 | + /** |
| 24 | + * MiniProgramManager constructor. |
| 25 | + * @param array $config |
| 26 | + */ |
| 27 | + public function __construct(array $config) |
| 28 | + { |
| 29 | + $this->config = new Config($config); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * gateway |
| 34 | + * |
| 35 | + * @param null $driver |
| 36 | + * @return mixed |
| 37 | + */ |
| 38 | + public function gateway($driver = null) |
| 39 | + { |
| 40 | + $driver = $driver ?: $this->getDefaultGateway(); |
| 41 | + |
| 42 | + if (!isset($this->gateways[$driver])) { |
| 43 | + $this->gateways[$driver] = $this->createGateway($driver); |
| 44 | + } |
| 45 | + |
| 46 | + return $this->gateways[$driver]; |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * getDefaultGateway |
| 51 | + * |
| 52 | + * @return array|mixed|null |
| 53 | + */ |
| 54 | + protected function getDefaultGateway() |
| 55 | + { |
| 56 | + return $this->config->get('default'); |
| 57 | + } |
| 58 | + |
| 59 | + /** |
| 60 | + * createGateway |
| 61 | + * |
| 62 | + * @param $driver |
| 63 | + * @return mixed |
| 64 | + */ |
| 65 | + public function createGateway($driver) |
| 66 | + { |
| 67 | + $config = $this->config->get("gateways.".$driver); |
| 68 | + |
| 69 | + if (is_null($config)) { |
| 70 | + throw new \UnexpectedValueException("Gateway [$driver] is not defined."); |
| 71 | + } |
| 72 | + |
| 73 | + $class = __NAMESPACE__.'\\Providers\\'.$config['driver'].'Provider'; |
| 74 | + |
| 75 | + if (!class_exists($class)) { |
| 76 | + throw new \UnexpectedValueException("Class '$class' not found"); |
| 77 | + } |
| 78 | + |
| 79 | + return $this->buildProvider($class, $config); |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * buildProvider |
| 84 | + * |
| 85 | + * @param $provider |
| 86 | + * @param $config |
| 87 | + * @return mixed |
| 88 | + */ |
| 89 | + public function buildProvider($provider, $config) |
| 90 | + { |
| 91 | + return new $provider($config['appid'], $config['secret']); |
| 92 | + } |
| 93 | +} |
| 94 | + |
0 commit comments