Completed
Pull Request — master (#13)
by
unknown
02:29
created

SmsManager::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
namespace Tzsk\Sms;
3
4
class SmsManager
5
{
6
    /**
7
     * Sms Configuration.
8
     *
9
     * @var null|object
10
     */
11
    protected $config = null;
12
13
    /**
14
     * Sms Driver Settings.
15
     *
16
     * @var null|object
17
     */
18
    protected $settings = null;
19
20
    /**
21
     * Sms Driver Name.
22
     *
23
     * @var null|string
24
     */
25
    protected $driver = null;
26
27
    /**
28
     * SmsManager constructor.
29
     */
30
    public function __construct()
31
    {
32
        $this->config = config('sms');
33
        $this->withDriver($this->config['default']);
34
    }
35
36
    /**
37
     * Change the driver on the fly.
38
     *
39
     * @param $driver
40
     * @return $this
41
     */
42
    public function withDriver($driver)
43
    {
44
        $this->driver = $driver;
45
        $this->settings = $this->config['drivers'][$this->driver];
46
47
        return $this;
48
    }
49
50
    /**
51
     * Send message.
52
     *
53
     * @param $message
54
     * @param $callback
55
     * @return mixed
56
     * @throws \Exception
57
     */
58
    public function send($message, $callback)
59
    {
60
        $this->validateParams();
61
62
        $class = $this->config['map'][$this->driver];
63
        $object = new $class($this->settings);
64
        $object->message($message);
65
        call_user_func($callback, $object);
66
67
        return $object->send();
68
    }
69
70
    /**
71
     * Validate Parameters before sending.
72
     *
73
     * @throws \Exception
74
     */
75
    protected function validateParams()
76
    {
77
        if (empty($this->driver)) {
78
            throw new \Exception("Driver not selected or default driver does not exist.");
79
        }
80
        if (empty($this->config['drivers'][$this->driver]) or empty($this->config['map'][$this->driver])) {
81
            throw new \Exception("Driver not found in config file. Try updating the package.");
82
        }
83
84
        if (!class_exists($this->config['map'][$this->driver])) {
85
            throw new \Exception("Driver source not found. Please update the package.");
86
        }
87
    }
88
}
89