Completed
Pull Request — master (#64)
by lan tian
04:52
created

Sms::config()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
cc 2
eloc 4
nc 1
nop 2
crap 2
1
<?php
2
3
namespace Toplan\PhpSms;
4
5
use SuperClosure\Serializer;
6
use Toplan\TaskBalance\Balancer;
7
use Toplan\TaskBalance\Task;
8
9
/**
10
 * Class Sms
11
 *
12
 * @author toplan<[email protected]>
13
 */
14
class Sms
15
{
16
    const TASK_NAME = 'PhpSms';
17
    const TYPE_SMS = 1;
18
    const TYPE_VOICE = 2;
19
20
    /**
21
     * The instances of Agent.
22
     *
23
     * @var array
24
     */
25
    protected static $agents = [];
26
27
    /**
28
     * The dispatch scheme of agent,
29
     * and these agents are available.
30
     * example:
31
     * [
32
     *   'Agent1' => '10 backup',
33
     *   'Agent2' => '20 backup',
34
     * ]
35
     *
36
     * @var array
37
     */
38
    protected static $scheme = [];
39
40
    /**
41
     * The configuration information of agents.
42
     *
43
     * @var array
44
     */
45
    protected static $agentsConfig = [];
46
47
    /**
48
     * Whether to use the queue.
49
     *
50
     * @var bool
51
     */
52
    protected static $enableQueue = false;
53
54
    /**
55
     * How to use the queue.
56
     *
57
     * @var \Closure
58
     */
59
    protected static $howToUseQueue = null;
60
61
    /**
62
     * The available hooks for balancing task.
63
     *
64
     * @var array
65
     */
66
    protected static $availableHooks = [
67
        'beforeRun',
68
        'beforeDriverRun',
69
        'afterDriverRun',
70
        'afterRun',
71
    ];
72
73
    /**
74
     * An instance of class [SuperClosure\Serializer] use for serialization closures.
75
     *
76
     * @var Serializer
77
     */
78
    protected static $serializer = null;
79
80
    /**
81
     * The data container of SMS/voice verify.
82
     *
83
     * @var array
84
     */
85
    protected $smsData = [
86
        'type'         => self::TYPE_SMS,
87
        'to'           => null,
88
        'templates'    => [],
89
        'templateData' => [],
90
        'content'      => null,
91
        'voiceCode'    => null,
92
    ];
93
94
    /**
95
     * The name of first agent.
96
     *
97
     * @var string|null
98
     */
99
    protected $firstAgent = null;
100
101
    /**
102
     * Whether the current instance has already pushed to the queue system.
103
     *
104
     * @var bool
105
     */
106
    protected $pushedToQueue = false;
107
108
    /**
109
     * Status container,
110
     * store some configuration information before serialize current instance(before enqueue).
111
     *
112
     * @var array
113
     */
114
    protected $_status_before_enqueue_ = [];
115
116
    /**
117
     * Constructor
118
     *
119
     * @param bool $autoBoot
120
     */
121 6
    public function __construct($autoBoot = true)
122
    {
123 6
        if ($autoBoot) {
124 3
            self::bootstrap();
125 3
        }
126 6
    }
127
128
    /**
129
     * Boot balancing task for send SMS/voice verify.
130
     *
131
     * Note: 判断drivers是否为空不能用'empty',因为在TaskBalance库的中Task类的drivers属性是受保护的(不可访问),
132
     * 虽然通过魔术方法可以获取到其值,但在其目前版本(v0.4.2)其内部却并没有使用'__isset'魔术方法对'empty'或'isset'函数进行逻辑补救.
133
     */
134 6
    public static function bootstrap()
135
    {
136 6
        $task = self::getTask();
137 6
        if (!count($task->drivers)) {
138 3
            self::configuration();
139 3
            self::createDrivers($task);
140 3
        }
141 6
    }
142
143
    /**
144
     * Get or generate a balancing task instance for send SMS/voice verify.
145
     *
146
     * @return Task
147
     */
148 15
    public static function getTask()
149
    {
150 15
        if (!Balancer::hasTask(self::TASK_NAME)) {
151 3
            Balancer::task(self::TASK_NAME);
152 3
        }
153
154 15
        return Balancer::getTask(self::TASK_NAME);
155
    }
156
157
    /**
158
     * Configuration.
159
     */
160 6
    protected static function configuration()
161
    {
162 6
        $config = [];
163 6
        if (!count(self::scheme())) {
164 3
            self::initScheme($config);
165 3
        }
166 6
        $diff = array_diff_key(self::scheme(), self::$agentsConfig);
167 6
        self::initAgentsConfig(array_keys($diff), $config);
168 6
        self::validateConfig();
169 6
    }
170
171
    /**
172
     * Try to read the dispatch scheme of agent from config file.
173
     *
174
     * @param array $config
175
     */
176 3
    protected static function initScheme(array &$config)
177
    {
178 3
        $config = empty($config) ? include __DIR__ . '/../config/phpsms.php' : $config;
179 3
        $scheme = isset($config['scheme']) ? $config['scheme'] : [];
180 3
        self::scheme($scheme);
181 3
    }
182
183
    /**
184
     * Try to initialize the specified agents` configuration information.
185
     *
186
     * @param array $agents
187
     * @param array $config
188
     */
189 6
    protected static function initAgentsConfig(array $agents, array &$config)
190
    {
191 6
        if (empty($agents)) {
192 3
            return;
193
        }
194 3
        $config = empty($config) ? include __DIR__ . '/../config/phpsms.php' : $config;
195 3
        $agentsConfig = isset($config['agents']) ? $config['agents'] : [];
196 3
        foreach ($agents as $name) {
197 3
            $agentConfig = isset($agentsConfig[$name]) ? $agentsConfig[$name] : [];
198 3
            self::config($name, $agentConfig);
199 3
        }
200 3
    }
201
202
    /**
203
     * validate configuration.
204
     *
205
     * @throws PhpSmsException
206
     */
207 6
    protected static function validateConfig()
208
    {
209 6
        if (!count(self::scheme())) {
210
            throw new PhpSmsException('Please configure at least one agent');
211
        }
212 6
    }
213
214
    /**
215
     * Create drivers for the balancing task.
216
     *
217
     * @param Task $task
218
     */
219 18
    protected static function createDrivers(Task $task)
220
    {
221 3
        foreach (self::scheme() as $name => $scheme) {
222
            //解析代理器数组模式的调度配置
223 3
            if (is_array($scheme)) {
224 3
                $data = self::parseScheme($scheme);
225 3
                $scheme = $data['scheme'];
226 3
            }
227
            //创建任务驱动器
228
            $task->driver("$name $scheme")->work(function ($driver) {
229 18
                $agent = self::getAgent($driver->name);
230 18
                $smsData = $driver->getTaskData();
231 18
                extract($smsData);
232 18
                $template = isset($templates[$driver->name]) ? $templates[$driver->name] : 0;
233 18
                if ($type === self::TYPE_VOICE) {
234
                    $agent->voiceVerify($to, $voiceCode, $template, $templateData);
235 18
                } elseif ($type === self::TYPE_SMS) {
236 18
                    $agent->sendSms($to, $content, $template, $templateData);
237 18
                }
238 18
                $result = $agent->result();
239 18
                if ($result['success']) {
240 18
                    $driver->success();
241 18
                }
242 18
                unset($result['success']);
243
244 18
                return $result;
245 3
            });
246 3
        }
247 3
    }
248
249
    /**
250
     * Parsing the dispatch scheme.
251
     * 解析代理器的数组模式的调度配置
252
     *
253
     * @param array $options
254
     *
255
     * @return array
256
     */
257 9
    protected static function parseScheme(array $options)
258
    {
259 9
        $agentClass = Util::pullFromArrayByKey($options, 'agentClass');
260 9
        $sendSms = Util::pullFromArrayByKey($options, 'sendSms');
261 9
        $voiceVerify = Util::pullFromArrayByKey($options, 'voiceVerify');
262 9
        $backup = Util::pullFromArrayByKey($options, 'backup') ? 'backup' : '';
263 9
        $scheme = implode(' ', array_values($options)) . " $backup";
264
265 9
        return compact('agentClass', 'sendSms', 'voiceVerify', 'scheme');
266
    }
267
268
    /**
269
     * Get a sms agent instance by agent name,
270
     * if null, will try to create a new agent instance.
271
     *
272
     * @param string $name
273
     *
274
     * @throws PhpSmsException
275
     *
276
     * @return mixed
277
     */
278 27
    public static function getAgent($name)
279
    {
280 27
        if (!self::hasAgent($name)) {
281 9
            $scheme = self::scheme($name);
282 9
            $data = self::parseScheme(is_array($scheme) ? $scheme : [$scheme]);
283 9
            $data = array_merge(self::config($name), $data);
284 9
            $className = $data['agentClass'] ?: ('Toplan\\PhpSms\\' . $name . 'Agent');
285 9
            if (is_callable($data['sendSms']) || is_callable($data['voiceVerify'])) {
286 3
                self::$agents[$name] = new ParasiticAgent($data);
287 9
            } elseif (class_exists($className)) {
288 6
                self::$agents[$name] = new $className($data);
289 6
            } else {
290
                throw new PhpSmsException("Dont support [$name] agent.");
291
            }
292 9
        }
293
294 27
        return self::$agents[$name];
295
    }
296
297
    /**
298
     * Whether to has specified agent.
299
     *
300
     * @param string $name
301
     *
302
     * @return bool
303
     */
304 36
    public static function hasAgent($name)
305
    {
306 36
        return isset(self::$agents[$name]);
307
    }
308
309
    /**
310
     * Set or get the dispatch scheme of agent by name.
311
     *
312
     * @param mixed $name
313
     * @param mixed $scheme
314
     *
315
     * @return mixed
316
     */
317 18
    public static function scheme($name = null, $scheme = null)
318
    {
319
        return Util::operateArray(self::$scheme, $name, $scheme, null, function ($key, $value) {
320 6
            if (is_string($key)) {
321 3
                self::modifyScheme($key, is_array($value) ? $value : "$value");
322 6
            } elseif (is_int($key)) {
323 6
                self::modifyScheme($value, '');
324 6
            }
325 18
        });
326
    }
327
328
    /**
329
     * Modify the dispatch scheme of agent by name.
330
     *
331
     * @param $key
332
     * @param $value
333
     *
334
     * @throws PhpSmsException
335
     */
336 6
    protected static function modifyScheme($key, $value)
337
    {
338 6
        self::validateAgentName($key);
339 6
        self::$scheme[$key] = $value;
340 6
    }
341
342
    /**
343
     * Set or get configuration information by agent name.
344
     *
345
     * @param mixed $name
346
     * @param mixed $config
347
     *
348
     * @throws PhpSmsException
349
     *
350
     * @return array
351
     */
352
    public static function config($name = null, $config = null)
353
    {
354 18
        return Util::operateArray(self::$agentsConfig, $name, $config, [], function ($key, $value) {
355 9
            if (is_array($value)) {
356 9
                self::modifyConfig($key, $value);
357 9
            }
358 18
        });
359
    }
360
361
    /**
362
     * Modify the configuration information of agent by name.
363
     *
364
     * @param string $key
365
     * @param array  $value
366
     *
367
     * @throws PhpSmsException
368
     */
369 9
    protected static function modifyConfig($key, array $value)
370
    {
371 9
        self::validateAgentName($key);
372 9
        self::$agentsConfig[$key] = $value;
373 9
        if (self::hasAgent($key)) {
374 3
            self::getAgent($key)->config($value);
375 3
        }
376 9
    }
377
378
    /**
379
     * Validate the agent name.
380
     * Agent name must be a string, but not be a number string
381
     *
382
     * @param string $name
383
     *
384
     * @throws PhpSmsException
385
     */
386 12
    protected static function validateAgentName($name)
387
    {
388 12
        if (!$name || !is_string($name) || preg_match('/^[0-9]+$/', $name)) {
389
            throw new PhpSmsException("The agent name [$name] is illegal. Agent name must be a string, but not be a number string.");
390
        }
391 12
    }
392
393
    /**
394
     * Tear down agent use scheme and prepare to create and start a new balancing task,
395
     * so before do it must destroy old task instance.
396
     */
397 6
    public static function cleanScheme()
398
    {
399 6
        Balancer::destroy(self::TASK_NAME);
400 6
        self::$scheme = [];
401 6
    }
402
403
    /**
404
     * Tear down all the configuration information of agent.
405
     */
406 6
    public static function cleanConfig()
407
    {
408 6
        foreach (array_keys(self::config()) as $name) {
409 6
            if (self::hasAgent($name)) {
410 3
                self::getAgent($name)->config([], true);
411 3
            }
412 6
        }
413 6
        self::$agentsConfig = [];
414 6
    }
415
416
    /**
417
     * Create a sms instance send SMS,
418
     * your can also set SMS templates or content at the same time.
419
     *
420
     * @param mixed $agentName
421
     * @param mixed $tempId
422
     *
423
     * @return Sms
424
     */
425
    public static function make($agentName = null, $tempId = null)
426
    {
427
        $sms = new self();
428
        $sms->smsData['type'] = self::TYPE_SMS;
429
        if (is_array($agentName)) {
430
            $sms->template($agentName);
431
        } elseif ($agentName && is_string($agentName)) {
432
            if ($tempId === null) {
433
                $sms->content($agentName);
434
            } elseif (is_string($tempId) || is_int($tempId)) {
435
                $sms->template($agentName, "$tempId");
436
            }
437
        }
438
439
        return $sms;
440
    }
441
442
    /**
443
     * Create a sms instance send voice verify,
444
     * your can also set verify code at the same time.
445
     *
446
     * @param int|string|null $code
447
     *
448
     * @return Sms
449
     */
450 3
    public static function voice($code = null)
451
    {
452 3
        $sms = new self();
453 3
        $sms->smsData['type'] = self::TYPE_VOICE;
454 3
        $sms->smsData['voiceCode'] = $code;
455
456 3
        return $sms;
457
    }
458
459
    /**
460
     * Set whether to use the queue system, and define how to use it.
461
     *
462
     * @param mixed $enable
463
     * @param mixed $handler
464
     *
465
     * @return bool
466
     */
467 3
    public static function queue($enable = null, $handler = null)
468
    {
469 3
        if ($enable === null && $handler === null) {
470 3
            return self::$enableQueue;
471
        }
472 3
        if (is_callable($enable)) {
473 3
            $handler = $enable;
474 3
            $enable = true;
475 3
        }
476 3
        self::$enableQueue = (bool) $enable;
477 3
        if (is_callable($handler)) {
478 3
            self::$howToUseQueue = $handler;
0 ignored issues
show
Documentation Bug introduced by
It seems like $handler of type callable is incompatible with the declared type object<Closure> of property $howToUseQueue.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
479 3
        }
480
481 3
        return self::$enableQueue;
482
    }
483
484
    /**
485
     * Set the recipient`s mobile number.
486
     *
487
     * @param string $mobile
488
     *
489
     * @return $this
490
     */
491 6
    public function to($mobile)
492
    {
493 6
        $this->smsData['to'] = $mobile;
494
495 6
        return $this;
496
    }
497
498
    /**
499
     * Set the content for content SMS.
500
     *
501
     * @param string $content
502
     *
503
     * @return $this
504
     */
505 3
    public function content($content)
506
    {
507 3
        $this->smsData['content'] = trim((string) $content);
508
509 3
        return $this;
510
    }
511
512
    /**
513
     * Set the template id for template SMS.
514
     *
515
     * @param mixed $agentName
516
     * @param mixed $tempId
517
     *
518
     * @return $this
519
     */
520 3
    public function template($agentName, $tempId = null)
521
    {
522 3
        Util::operateArray($this->smsData['templates'], $agentName, $tempId);
523
524 3
        return $this;
525
    }
526
527
    /**
528
     * Set the template data for template SMS.
529
     *
530
     * @param array $data
531
     *
532
     * @return $this
533
     */
534 3
    public function data(array $data)
535
    {
536 3
        $this->smsData['templateData'] = $data;
537
538 3
        return $this;
539
    }
540
541
    /**
542
     * Set the first agent by name.
543
     *
544
     * @param string $name
545
     *
546
     * @return $this
547
     */
548 3
    public function agent($name)
549
    {
550 3
        $this->firstAgent = (string) $name;
551
552 3
        return $this;
553
    }
554
555
    /**
556
     * Start send SMS/voice verify.
557
     *
558
     * If give a true parameter, this system will immediately start request to send SMS/voice verify whatever whether to use the queue.
559
     * if you are already pushed sms instance to the queue, you can recall the method `send()` in queue system without `true` parameter,
560
     * so this mechanism in order to make you convenient use the method `send()` in queue system.
561
     *
562
     * @param bool $immediately
563
     *
564
     * @return mixed
565
     */
566 18
    public function send($immediately = false)
567
    {
568 18
        if (!self::$enableQueue || $this->pushedToQueue) {
569 18
            $immediately = true;
570 18
        }
571 18
        if ($immediately) {
572 18
            $result = Balancer::run(self::TASK_NAME, [
573 18
                'data'   => $this->getData(),
574 18
                'driver' => $this->firstAgent,
575 18
            ]);
576 18
        } else {
577 3
            $result = $this->push();
578
        }
579
580 18
        return $result;
581
    }
582
583
    /**
584
     * Push to the queue by a custom method.
585
     *
586
     * @throws \Exception | PhpSmsException
587
     *
588
     * @return mixed
589
     */
590 3
    public function push()
591
    {
592 3
        if (is_callable(self::$howToUseQueue)) {
593
            try {
594 3
                $this->pushedToQueue = true;
595
596 3
                return call_user_func_array(self::$howToUseQueue, [$this, $this->getData()]);
597
            } catch (\Exception $e) {
598
                $this->pushedToQueue = false;
599
                throw $e;
600
            }
601
        } else {
602
            throw new PhpSmsException('Please define how to use queue by method `queue($available, $handler)`');
603
        }
604
    }
605
606
    /**
607
     * Get all the data of SMS/voice verify.
608
     *
609
     * @param null|string $name
610
     *
611
     * @return mixed
612
     */
613 36
    public function getData($name = null)
614
    {
615 36
        if (is_string($name) && isset($this->smsData["$name"])) {
616 3
            return $this->smsData[$name];
617
        }
618
619 36
        return $this->smsData;
620
    }
621
622
    /**
623
     * Overload static method.
624
     *
625
     * @param string $name
626
     * @param array  $args
627
     *
628
     * @throws PhpSmsException
629
     */
630 9
    public static function __callStatic($name, $args)
631
    {
632 9
        $name = $name === 'beforeSend' ? 'beforeRun' : $name;
633 9
        $name = $name === 'afterSend' ? 'afterRun' : $name;
634 9
        $name = $name === 'beforeAgentSend' ? 'beforeDriverRun' : $name;
635 9
        $name = $name === 'afterAgentSend' ? 'afterDriverRun' : $name;
636 9
        if (in_array($name, self::$availableHooks)) {
637 9
            $handler = $args[0];
638 9
            $override = isset($args[1]) ? (bool) $args[1] : false;
639 9
            if (is_callable($handler)) {
640 9
                $task = self::getTask();
641 9
                $task->hook($name, $handler, $override);
642 9
            } else {
643
                throw new PhpSmsException("Please give method $name() a callable parameter");
644
            }
645 9
        } else {
646
            throw new PhpSmsException("Dont find method $name()");
647
        }
648 9
    }
649
650
    /**
651
     * Overload method.
652
     *
653
     * @param string $name
654
     * @param array  $args
655
     *
656
     * @throws PhpSmsException
657
     * @throws \Exception
658
     */
659 3
    public function __call($name, $args)
660
    {
661
        try {
662 3
            $this->__callStatic($name, $args);
663 3
        } catch (\Exception $e) {
664
            throw $e;
665
        }
666 3
    }
667
668
    /**
669
     * Serialize magic method.
670
     *
671
     * @return array
672
     */
673 3
    public function __sleep()
674
    {
675
        try {
676 3
            $this->_status_before_enqueue_['scheme'] = self::serializeOrDeserializeScheme(self::scheme());
677 3
            $this->_status_before_enqueue_['agentsConfig'] = self::config();
678 3
            $this->_status_before_enqueue_['handlers'] = self::serializeHandlers();
679 3
        } catch (\Exception $e) {
680
            //swallow exception
681
        }
682
683 3
        return ['smsData', 'firstAgent', 'pushedToQueue', '_status_before_enqueue_'];
684
    }
685
686
    /**
687
     * Deserialize magic method.
688
     */
689 3
    public function __wakeup()
690
    {
691 3
        if (empty($this->_status_before_enqueue_)) {
692
            return;
693
        }
694 3
        $status = $this->_status_before_enqueue_;
695 3
        self::$scheme = self::serializeOrDeserializeScheme($status['scheme']);
696 3
        self::$agentsConfig = $status['agentsConfig'];
697 3
        Balancer::destroy(self::TASK_NAME);
698 3
        self::bootstrap();
699 3
        self::reinstallHandlers($status['handlers']);
700 3
    }
701
702
    /**
703
     * Get a closure serializer.
704
     *
705
     * @return Serializer
706
     */
707 3
    protected static function getSerializer()
708
    {
709 3
        if (!self::$serializer) {
710 3
            self::$serializer = new Serializer();
711 3
        }
712
713 3
        return self::$serializer;
714
    }
715
716
    /**
717
     * Serialize or deserialize the agent use scheme.
718
     *
719
     * @param array $scheme
720
     *
721
     * @return array
722
     */
723 3
    protected static function serializeOrDeserializeScheme(array $scheme)
724
    {
725 3
        foreach ($scheme as $name => &$options) {
726 3
            if (is_array($options)) {
727 3
                self::serializeOrDeserializeClosureAndReplace($options, 'sendSms');
728 3
                self::serializeOrDeserializeClosureAndReplace($options, 'voiceVerify');
729 3
            }
730 3
        }
731
732 3
        return $scheme;
733
    }
734
735
    /**
736
     * Serialize the hooks` handlers of balancing task
737
     *
738
     * @return array
739
     */
740 3
    protected static function serializeHandlers()
741
    {
742 3
        $task = self::getTask();
743 3
        $hooks = $task->handlers;
744 3
        foreach ($hooks as &$handlers) {
745 3
            foreach (array_keys($handlers) as $key) {
746 3
                self::serializeOrDeserializeClosureAndReplace($handlers, $key);
747 3
            }
748 3
        }
749
750 3
        return $hooks;
751
    }
752
753
    /**
754
     * Reinstall hooks` handlers for balancing task.
755
     *
756
     * @param array $handlers
757
     */
758 3
    protected static function reinstallHandlers(array $handlers)
759
    {
760 3
        $serializer = self::getSerializer();
761 3
        foreach ($handlers as $hookName => $serializedHandlers) {
762 3
            foreach ($serializedHandlers as $index => $handler) {
763 3
                if (is_string($handler)) {
764 3
                    $handler = $serializer->unserialize($handler);
765 3
                }
766 3
                self::$hookName($handler, $index === 0);
767 3
            }
768 3
        }
769 3
    }
770
771
    /**
772
     * Serialize/deserialize the specified closure and replace the origin value.
773
     *
774
     * @param array      $options
775
     * @param int|string $key
776
     */
777 3
    protected static function serializeOrDeserializeClosureAndReplace(array &$options, $key)
778
    {
779 3
        if (!isset($options[$key])) {
780 3
            return;
781
        }
782 3
        $serializer = self::getSerializer();
783 3
        if (is_callable($options[$key])) {
784 3
            $options[$key] = (string) $serializer->serialize($options[$key]);
785 3
        } elseif (is_string($options[$key])) {
786 3
            $options[$key] = $serializer->unserialize($options[$key]);
787 3
        }
788 3
    }
789
}
790