Completed
Push — master ( 610508...f1f896 )
by lan tian
8s
created

Sms::initTask()   C

Complexity

Conditions 7
Paths 3

Size

Total Lines 29
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 7.0035

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 29
ccs 23
cts 24
cp 0.9583
rs 6.7272
cc 7
eloc 19
nc 3
nop 0
crap 7.0035
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] for serialize closure objects.
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 6
    public static function bootstrap()
132
    {
133 6
        if (!self::taskInitialized()) {
134 3
            self::configuration();
135 3
            self::initTask();
136 3
        }
137 6
    }
138
139
    /**
140
     * Whether task initialized.
141
     *
142
     * Note: 判断drivers是否为空不能用'empty',因为在TaskBalance库的中Task类的drivers属性是受保护的(不可访问),
143
     * 虽然通过魔术方法可以获取到其值,但在其目前版本(v0.4.2)其内部却并没有使用'__isset'魔术方法对'empty'或'isset'函数进行逻辑补救.
144
     *
145
     * @return bool
146
     */
147 12
    protected static function taskInitialized()
148
    {
149 12
        $task = self::getTask();
150
151 12
        return (bool) count($task->drivers);
152
    }
153
154
    /**
155
     * Get or generate a balancing task instance for send SMS/voice verify.
156
     *
157
     * @return Task
158
     */
159 21
    public static function getTask()
160
    {
161 21
        if (!Balancer::hasTask(self::TASK_NAME)) {
162 9
            Balancer::task(self::TASK_NAME);
163 9
        }
164
165 21
        return Balancer::getTask(self::TASK_NAME);
166
    }
167
168
    /**
169
     * Configuration.
170
     */
171 6
    protected static function configuration()
172
    {
173 6
        $config = [];
174 6
        if (!count(self::scheme())) {
175 3
            self::initScheme($config);
176 3
        }
177 6
        $diff = array_diff_key(self::scheme(), self::$agentsConfig);
178 6
        self::initAgentsConfig(array_keys($diff), $config);
179 6
        self::validateConfig();
180 6
    }
181
182
    /**
183
     * Try to read the dispatch scheme of agent from config file.
184
     *
185
     * @param array $config
186
     */
187 3
    protected static function initScheme(array &$config)
188
    {
189 3
        $config = empty($config) ? include __DIR__ . '/../config/phpsms.php' : $config;
190 3
        $scheme = isset($config['scheme']) ? $config['scheme'] : [];
191 3
        self::scheme($scheme);
192 3
    }
193
194
    /**
195
     * Try to initialize the specified agents` configuration information.
196
     *
197
     * @param array $agents
198
     * @param array $config
199
     */
200 6
    protected static function initAgentsConfig(array $agents, array &$config)
201
    {
202 6
        if (empty($agents)) {
203 3
            return;
204
        }
205 3
        $config = empty($config) ? include __DIR__ . '/../config/phpsms.php' : $config;
206 3
        $agentsConfig = isset($config['agents']) ? $config['agents'] : [];
207 3
        foreach ($agents as $name) {
208 3
            $agentConfig = isset($agentsConfig[$name]) ? $agentsConfig[$name] : [];
209 3
            self::config($name, $agentConfig);
210 3
        }
211 3
    }
212
213
    /**
214
     * validate configuration.
215
     *
216
     * @throws PhpSmsException
217
     */
218 6
    protected static function validateConfig()
219
    {
220 6
        if (!count(self::scheme())) {
221
            throw new PhpSmsException('Please configure at least one agent');
222
        }
223 6
    }
224
225
    /**
226
     * Initialize the task.
227
     */
228 18
    protected static function initTask()
229
    {
230 3
        foreach (self::scheme() as $name => $scheme) {
231
            //解析代理器数组模式的调度配置
232 3
            if (is_array($scheme)) {
233 3
                $data = self::parseScheme($scheme);
234 3
                $scheme = $data['scheme'];
235 3
            }
236
            //创建任务驱动器
237
            self::getTask()->driver("$name $scheme")->work(function ($driver) {
238 18
                $agent = self::getAgent($driver->name);
239 18
                $smsData = $driver->getTaskData();
240 18
                extract($smsData);
241 18
                $template = isset($templates[$driver->name]) ? $templates[$driver->name] : 0;
242 18
                if ($type === self::TYPE_VOICE) {
243
                    $agent->voiceVerify($to, $voiceCode, $template, $templateData);
244 18
                } elseif ($type === self::TYPE_SMS) {
245 18
                    $agent->sendSms($to, $content, $template, $templateData);
246 18
                }
247 18
                $result = $agent->result();
248 18
                if ($result['success']) {
249 18
                    $driver->success();
250 18
                }
251 18
                unset($result['success']);
252
253 18
                return $result;
254 3
            });
255 3
        }
256 3
    }
257
258
    /**
259
     * Parsing the dispatch scheme.
260
     * 解析代理器的数组模式的调度配置
261
     *
262
     * @param array $options
263
     *
264
     * @return array
265
     */
266 9
    protected static function parseScheme(array $options)
267
    {
268 9
        $agentClass = Util::pullFromArrayByKey($options, 'agentClass');
269 9
        $sendSms = Util::pullFromArrayByKey($options, 'sendSms');
270 9
        $voiceVerify = Util::pullFromArrayByKey($options, 'voiceVerify');
271 9
        $backup = Util::pullFromArrayByKey($options, 'backup') ? 'backup' : '';
272 9
        $scheme = implode(' ', array_values($options)) . " $backup";
273
274 9
        return compact('agentClass', 'sendSms', 'voiceVerify', 'scheme');
275
    }
276
277
    /**
278
     * Get a sms agent instance by agent name,
279
     * if null, will try to create a new agent instance.
280
     *
281
     * @param string $name
282
     *
283
     * @throws PhpSmsException
284
     *
285
     * @return mixed
286
     */
287 27
    public static function getAgent($name)
288
    {
289 27
        if (!self::hasAgent($name)) {
290 9
            $scheme = self::scheme($name);
291 9
            $data = self::parseScheme(is_array($scheme) ? $scheme : [$scheme]);
292 9
            $data = array_merge(self::config($name), $data);
293 9
            $className = $data['agentClass'] ?: ('Toplan\\PhpSms\\' . $name . 'Agent');
294 9
            if (is_callable($data['sendSms']) || is_callable($data['voiceVerify'])) {
295 3
                self::$agents[$name] = new ParasiticAgent($data);
296 9
            } elseif (class_exists($className)) {
297 6
                self::$agents[$name] = new $className($data);
298 6
            } else {
299
                throw new PhpSmsException("Dont support [$name] agent.");
300
            }
301 9
        }
302
303 27
        return self::$agents[$name];
304
    }
305
306
    /**
307
     * Whether to has specified agent.
308
     *
309
     * @param string $name
310
     *
311
     * @return bool
312
     */
313 36
    public static function hasAgent($name)
314
    {
315 36
        return isset(self::$agents[$name]);
316
    }
317
318
    /**
319
     * Set or get the dispatch scheme of agent by name.
320
     *
321
     * @param mixed $name
322
     * @param mixed $scheme
323
     *
324
     * @return mixed
325
     */
326 18
    public static function scheme($name = null, $scheme = null)
327
    {
328
        return Util::operateArray(self::$scheme, $name, $scheme, null, function ($key, $value) {
329 6
            if (is_string($key)) {
330 3
                self::modifyScheme($key, is_array($value) ? $value : "$value");
331 6
            } elseif (is_int($key)) {
332 6
                self::modifyScheme($value, '');
333 6
            }
334 18
        });
335
    }
336
337
    /**
338
     * Modify the dispatch scheme of agent by name.
339
     *
340
     * @param $key
341
     * @param $value
342
     *
343
     * @throws PhpSmsException
344
     */
345 6
    protected static function modifyScheme($key, $value)
346
    {
347 6
        if (self::taskInitialized()) {
348
            throw new PhpSmsException("Modify the dispatch scheme failed for [$key] agent, because the task system has already started.");
349
        }
350 6
        self::validateAgentName($key);
351 6
        self::$scheme[$key] = $value;
352 6
    }
353
354
    /**
355
     * Set or get configuration information by agent name.
356
     *
357
     * @param mixed $name
358
     * @param mixed $config
359
     * @param bool  $override
360
     *
361
     * @throws PhpSmsException
362
     *
363
     * @return array
364
     */
365 18
    public static function config($name = null, $config = null, $override = false)
366
    {
367 18
        if (is_array($name) && is_bool($config)) {
368 6
            $override = $config;
369 6
        }
370
371
        return Util::operateArray(self::$agentsConfig, $name, $config, [], function ($key, $value) {
372 9
            if (is_array($value)) {
373 9
                self::modifyConfig($key, $value);
374 9
            }
375 18
        }, $override, function (array $origin) {
376 6
            $nameList = array_keys($origin);
377 6
            foreach ($nameList as $name) {
378 6
                if (self::hasAgent("$name")) {
379 3
                    self::getAgent("$name")->config([], true);
380 3
                }
381 6
            }
382 18
        });
383
    }
384
385
    /**
386
     * Modify the configuration information of agent by name.
387
     *
388
     * @param string $key
389
     * @param array  $value
390
     *
391
     * @throws PhpSmsException
392
     */
393 9
    protected static function modifyConfig($key, array $value)
394
    {
395 9
        self::validateAgentName($key);
396 9
        self::$agentsConfig[$key] = $value;
397 9
        if (self::hasAgent($key)) {
398 3
            self::getAgent($key)->config($value);
399 3
        }
400 9
    }
401
402
    /**
403
     * Validate the agent name.
404
     * Agent name must be a string, but not be a number string
405
     *
406
     * @param string $name
407
     *
408
     * @throws PhpSmsException
409
     */
410 12
    protected static function validateAgentName($name)
411
    {
412 12
        if (!$name || !is_string($name) || preg_match('/^[0-9]+$/', $name)) {
413
            throw new PhpSmsException("The agent name [$name] is illegal. Agent name must be a string, but not be a number string.");
414
        }
415 12
    }
416
417
    /**
418
     * Tear down agent use scheme and prepare to create and start a new balancing task,
419
     * so before do it must destroy old task instance.
420
     */
421 6
    public static function cleanScheme()
422
    {
423 6
        Balancer::destroy(self::TASK_NAME);
424 6
        self::$scheme = [];
425 6
    }
426
427
    /**
428
     * Tear down all the configuration information of agent.
429
     */
430 6
    public static function cleanConfig()
431
    {
432 6
        self::config([], true);
433 6
    }
434
435
    /**
436
     * Create a sms instance send SMS,
437
     * your can also set SMS templates or content at the same time.
438
     *
439
     * @param mixed $agentName
440
     * @param mixed $tempId
441
     *
442
     * @return Sms
443
     */
444
    public static function make($agentName = null, $tempId = null)
445
    {
446
        $sms = new self();
447
        $sms->smsData['type'] = self::TYPE_SMS;
448
        if (is_array($agentName)) {
449
            $sms->template($agentName);
450
        } elseif ($agentName && is_string($agentName)) {
451
            if ($tempId === null) {
452
                $sms->content($agentName);
453
            } elseif (is_string($tempId) || is_int($tempId)) {
454
                $sms->template($agentName, "$tempId");
455
            }
456
        }
457
458
        return $sms;
459
    }
460
461
    /**
462
     * Create a sms instance send voice verify,
463
     * your can also set verify code at the same time.
464
     *
465
     * @param int|string|null $code
466
     *
467
     * @return Sms
468
     */
469 3
    public static function voice($code = null)
470
    {
471 3
        $sms = new self();
472 3
        $sms->smsData['type'] = self::TYPE_VOICE;
473 3
        $sms->smsData['voiceCode'] = $code;
474
475 3
        return $sms;
476
    }
477
478
    /**
479
     * Set whether to use the queue system, and define how to use it.
480
     *
481
     * @param mixed $enable
482
     * @param mixed $handler
483
     *
484
     * @return bool
485
     */
486 3
    public static function queue($enable = null, $handler = null)
487
    {
488 3
        if ($enable === null && $handler === null) {
489 3
            return self::$enableQueue;
490
        }
491 3
        if (is_callable($enable)) {
492 3
            $handler = $enable;
493 3
            $enable = true;
494 3
        }
495 3
        self::$enableQueue = (bool) $enable;
496 3
        if (is_callable($handler)) {
497 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...
498 3
        }
499
500 3
        return self::$enableQueue;
501
    }
502
503
    /**
504
     * Set the recipient`s mobile number.
505
     *
506
     * @param string $mobile
507
     *
508
     * @return $this
509
     */
510 6
    public function to($mobile)
511
    {
512 6
        $this->smsData['to'] = trim((string) $mobile);
513
514 6
        return $this;
515
    }
516
517
    /**
518
     * Set the content for content SMS.
519
     *
520
     * @param string $content
521
     *
522
     * @return $this
523
     */
524 3
    public function content($content)
525
    {
526 3
        $this->smsData['content'] = trim((string) $content);
527
528 3
        return $this;
529
    }
530
531
    /**
532
     * Set the template id for template SMS.
533
     *
534
     * @param mixed $name
535
     * @param mixed $tempId
536
     *
537
     * @return $this
538
     */
539 3
    public function template($name, $tempId = null)
540
    {
541 3
        Util::operateArray($this->smsData['templates'], $name, $tempId);
542
543 3
        return $this;
544
    }
545
546
    /**
547
     * Set the template data for template SMS.
548
     *
549
     * @param array $data
550
     *
551
     * @return $this
552
     */
553 3
    public function data(array $data)
554
    {
555 3
        $this->smsData['templateData'] = $data;
556
557 3
        return $this;
558
    }
559
560
    /**
561
     * Set the first agent by name.
562
     *
563
     * @param string $name
564
     *
565
     * @return $this
566
     */
567 3
    public function agent($name)
568
    {
569 3
        $this->firstAgent = (string) $name;
570
571 3
        return $this;
572
    }
573
574
    /**
575
     * Start send SMS/voice verify.
576
     *
577
     * If give a true parameter, this system will immediately start request to send SMS/voice verify whatever whether to use the queue.
578
     * if you are already pushed sms instance to the queue, you can recall the method `send()` in queue system without `true` parameter,
579
     * so this mechanism in order to make you convenient use the method `send()` in queue system.
580
     *
581
     * @param bool $immediately
582
     *
583
     * @return mixed
584
     */
585 18
    public function send($immediately = false)
586
    {
587 18
        if (!self::$enableQueue || $this->pushedToQueue) {
588 18
            $immediately = true;
589 18
        }
590 18
        if ($immediately) {
591 18
            $result = Balancer::run(self::TASK_NAME, [
592 18
                'data'   => $this->getData(),
593 18
                'driver' => $this->firstAgent,
594 18
            ]);
595 18
        } else {
596 3
            $result = $this->push();
597
        }
598
599 18
        return $result;
600
    }
601
602
    /**
603
     * Push to the queue by a custom method.
604
     *
605
     * @throws \Exception | PhpSmsException
606
     *
607
     * @return mixed
608
     */
609 3
    public function push()
610
    {
611 3
        if (is_callable(self::$howToUseQueue)) {
612
            try {
613 3
                $this->pushedToQueue = true;
614
615 3
                return call_user_func_array(self::$howToUseQueue, [$this, $this->getData()]);
616
            } catch (\Exception $e) {
617
                $this->pushedToQueue = false;
618
                throw $e;
619
            }
620
        } else {
621
            throw new PhpSmsException('Please define how to use queue by this static method: queue(...)');
622
        }
623
    }
624
625
    /**
626
     * Get all the data of SMS/voice verify.
627
     *
628
     * @param null|string $name
629
     *
630
     * @return mixed
631
     */
632 36
    public function getData($name = null)
633
    {
634 36
        if (is_string($name) && isset($this->smsData["$name"])) {
635 3
            return $this->smsData[$name];
636
        }
637
638 36
        return $this->smsData;
639
    }
640
641
    /**
642
     * Overload static method.
643
     *
644
     * @param string $name
645
     * @param array  $args
646
     *
647
     * @throws PhpSmsException
648
     */
649 9
    public static function __callStatic($name, $args)
650
    {
651 9
        $name = $name === 'beforeSend' ? 'beforeRun' : $name;
652 9
        $name = $name === 'afterSend' ? 'afterRun' : $name;
653 9
        $name = $name === 'beforeAgentSend' ? 'beforeDriverRun' : $name;
654 9
        $name = $name === 'afterAgentSend' ? 'afterDriverRun' : $name;
655 9
        if (in_array($name, self::$availableHooks)) {
656 9
            $handler = $args[0];
657 9
            $override = isset($args[1]) ? (bool) $args[1] : false;
658 9
            if (is_callable($handler)) {
659 9
                $task = self::getTask();
660 9
                $task->hook($name, $handler, $override);
661 9
            } else {
662
                throw new PhpSmsException("Please give method $name() a callable parameter");
663
            }
664 9
        } else {
665
            throw new PhpSmsException("Dont find method $name()");
666
        }
667 9
    }
668
669
    /**
670
     * Overload method.
671
     *
672
     * @param string $name
673
     * @param array  $args
674
     *
675
     * @throws PhpSmsException
676
     * @throws \Exception
677
     */
678 3
    public function __call($name, $args)
679
    {
680
        try {
681 3
            $this->__callStatic($name, $args);
682 3
        } catch (\Exception $e) {
683
            throw $e;
684
        }
685 3
    }
686
687
    /**
688
     * Serialize magic method.
689
     *
690
     * @return array
691
     */
692 3
    public function __sleep()
693
    {
694
        try {
695 3
            $this->_status_before_enqueue_['scheme'] = self::serializeOrDeserializeScheme(self::scheme());
696 3
            $this->_status_before_enqueue_['agentsConfig'] = self::config();
697 3
            $this->_status_before_enqueue_['handlers'] = self::serializeHandlers();
698 3
        } catch (\Exception $e) {
699
            //swallow exception
700
        }
701
702 3
        return ['smsData', 'firstAgent', 'pushedToQueue', '_status_before_enqueue_'];
703
    }
704
705
    /**
706
     * Deserialize magic method.
707
     */
708 3
    public function __wakeup()
709
    {
710 3
        if (empty($this->_status_before_enqueue_)) {
711
            return;
712
        }
713 3
        $status = $this->_status_before_enqueue_;
714 3
        self::$scheme = self::serializeOrDeserializeScheme($status['scheme']);
715 3
        self::$agentsConfig = $status['agentsConfig'];
716 3
        Balancer::destroy(self::TASK_NAME);
717 3
        self::bootstrap();
718 3
        self::reinstallHandlers($status['handlers']);
719 3
    }
720
721
    /**
722
     * Get a closure serializer.
723
     *
724
     * @return Serializer
725
     */
726 3
    protected static function getSerializer()
727
    {
728 3
        if (!self::$serializer) {
729 3
            self::$serializer = new Serializer();
730 3
        }
731
732 3
        return self::$serializer;
733
    }
734
735
    /**
736
     * Serialize or deserialize the agent use scheme.
737
     *
738
     * @param array $scheme
739
     *
740
     * @return array
741
     */
742 3
    protected static function serializeOrDeserializeScheme(array $scheme)
743
    {
744 3
        foreach ($scheme as $name => &$options) {
745 3
            if (is_array($options)) {
746 3
                self::serializeOrDeserializeClosureAndReplace($options, 'sendSms');
747 3
                self::serializeOrDeserializeClosureAndReplace($options, 'voiceVerify');
748 3
            }
749 3
        }
750
751 3
        return $scheme;
752
    }
753
754
    /**
755
     * Serialize the hooks` handlers of balancing task
756
     *
757
     * @return array
758
     */
759 3
    protected static function serializeHandlers()
760
    {
761 3
        $task = self::getTask();
762 3
        $hooks = (array) $task->handlers;
763 3
        foreach ($hooks as &$handlers) {
764 3
            foreach (array_keys($handlers) as $key) {
765 3
                self::serializeOrDeserializeClosureAndReplace($handlers, $key);
766 3
            }
767 3
        }
768
769 3
        return $hooks;
770
    }
771
772
    /**
773
     * Reinstall hooks` handlers for balancing task.
774
     *
775
     * @param array $handlers
776
     */
777 3
    protected static function reinstallHandlers(array $handlers)
778
    {
779 3
        $serializer = self::getSerializer();
780 3
        foreach ($handlers as $hookName => $serializedHandlers) {
781 3
            foreach ($serializedHandlers as $index => $handler) {
782 3
                if (is_string($handler)) {
783 3
                    $handler = $serializer->unserialize($handler);
784 3
                }
785 3
                self::$hookName($handler, $index === 0);
786 3
            }
787 3
        }
788 3
    }
789
790
    /**
791
     * Serialize/deserialize the specified closure and replace the origin value.
792
     *
793
     * @param array      $options
794
     * @param int|string $key
795
     */
796 3
    protected static function serializeOrDeserializeClosureAndReplace(array &$options, $key)
797
    {
798 3
        if (!isset($options[$key])) {
799 3
            return;
800
        }
801 3
        $serializer = self::getSerializer();
802 3
        if (is_callable($options[$key])) {
803 3
            $options[$key] = (string) $serializer->serialize($options[$key]);
804 3
        } elseif (is_string($options[$key])) {
805 3
            $options[$key] = $serializer->unserialize($options[$key]);
806 3
        }
807 3
    }
808
}
809