123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226 |
- <?php
- namespace catchAdmin\sms;
- use catchAdmin\sms\model\SmsConfig;
- use catcher\exceptions\FailedException;
- use Overtrue\EasySms\EasySms;
- use think\helper\Str;
- class Sms
- {
-
- protected $timeout = 5;
-
- protected $errorLog;
-
- protected $gateways = [];
-
- protected $config = [];
-
- protected $sendData = [];
-
- public function __construct(array $config)
- {
- $config['timeout'] = $this->timeout;
- $config['gateways']['errorlog'] = runtime_path('log') . 'sms.log';
- $this->config = $config;
- }
-
- public function send(string $phone, array $data)
- {
- try {
- $this->sendData['data'] = $data;
- return $this->easySms()
- ->send($phone, $this->sendData);
- } catch (\Exception $exception) {
- throw new FailedException($exception->getMessage());
- }
- }
-
- public function easySms()
- {
- return new EasySms($this->config);
- }
-
- public function content($content, $key = 'content')
- {
- $this->sendData[$key] = $content;
- return $this;
- }
-
- public function template($template, $key = 'template')
- {
- $this->sendData[$key] = $template;
- return $this;
- }
-
- public function timeout(int $timeout)
- {
- $this->config['timeout'] = $timeout;
- return $this;
- }
-
- public function errorLog(string $log)
- {
- $this->config['gateways']['errorlog'] = $log;
- return $this;
- }
-
- protected static function getGatewaysConfig($gateways)
- {
- $gatewaysConfig = [];
- $smsConfig = new SmsConfig();
- foreach ($gateways as $gate) {
- $c = $smsConfig->findByName($gate);
- if ($c) {
- $c->hasConfig()
- ->select()
- ->each(function ($item) use (&$gatewaysConfig, $gate){
- $gatewaysConfig[$gate][$item['key']] = $item['value'];
- });
- }
- }
- return $gatewaysConfig;
- }
-
- public static function __callStatic($method, $arg)
- {
- $gateways = Str::snake($method);
- if (Str::contains($gateways, '_')) {
- $gateways = explode('_', $gateways);
- } else {
- $gateways = [$gateways];
- }
- $config = [
- 'default' => [
- 'gateways' => $gateways,
- ],
- 'gateways' => static::getGatewaysConfig($gateways)
- ];
- return new self($config);
- }
- }
|