OperSMS

 avatar
unknown
php
2 years ago
6.6 kB
4
Indexable
<?php

namespace App\Services\Sms;

use Exception;

class OperSmsService
{
    /**
     * @throws Exception
     */
    public static function send($phone, $message)
    {
        try {
            $callbackUrl = config('application.sms.opersms.url');
            $login = config('application.sms.opersms.login');
            $password = config('application.sms.opersms.password');

            if (is_array($message) && !is_array($phone)) {
                throw new Exception("Argument Text received as array but argument Number received as string. If you send arrays then both arguments must be arrays");
            }

            if (is_array($phone) && !is_array($message)) {
                throw new Exception("Argument Number received as array but argument Text received as string. If you send arrays then both arguments must be arrays");
            }

            if (is_array($message) && is_array($phone)) {
                if (count($phone) != count($message)) {
                    throw new Exception("Count of array values Text and Number can not be different");
                }
            }

            if (is_string($phone)) {
                $phone = preg_replace('/\D/', '', trim($phone));
            }

            if (is_array($phone)) {
                $tempNumbArray = [];
                foreach ($phone as $validateNumb) {
                    if (is_string($validateNumb)) {
                        $validateNumb = preg_replace('/\D/', '', trim($validateNumb));
                        $tempNumbArray[] = $validateNumb;
                    }
                }

                if (count($phone) !== count($tempNumbArray)) {
                    throw new Exception("An array of phone numbers includes subarrays. The function expects a list of phone numbers");
                }

                unset($phone);

                $phone = $tempNumbArray;

            }

            $tempMessages = [];
            if (is_array($message)) {
                # перебираем каждый элемент
                foreach ($message as $ValidateText) {
                    # проверяем на то , является ли он строкой
                    if (is_string($ValidateText)) {
                        $tempMessages[] = $ValidateText;
                    }
                }

                if (count($message) !== count($tempMessages)) {
                    throw new Exception("An array of sms texts includes subarrays. The function expects a list of sms texts");
                }
            }

            if (is_string($phone)) {
                if (strlen($phone) > 12) {
                    throw new Exception("Phone number must be no more than 12 characters");
                }

                if (strlen($phone) < 12) {
                    throw new Exception("Phone number must be at least 12 characters");
                }
            }

            if (is_array($phone)) {
                foreach ($phone as $NumbExcept) {
                    if (strlen($NumbExcept) > 12) {
                        throw new Exception("One of phone numbers is more than 12 characters");
                    }

                    if (strlen($NumbExcept) < 12) {
                        throw new Exception("One of the phone numbers is less than 12 characters");
                    }
                }
            }

            if (is_string($phone)) {
                preg_match("/[0-9]{12}/", $phone, $matches);
                if (empty($matches[0])) {
                    throw new Exception("Phone number does not consist of numbers or its length is not equal to 12 characters");
                }
            }

            if (is_array($phone)) {
                foreach ($phone as $NumbExceptReg) {
                    preg_match("/[0-9]{12}/", $NumbExceptReg, $matches);

                    if (empty($matches[0])) {
                        throw new Exception("One of the phone numbers does not consist of numbers or its length is not equal to 12 characters");
                    }
                }
            }

            $sendData = [];
            if (is_string($phone) && is_string($message)) {
                $sendData[] = ['phone' => "$phone", 'text' => $message];
            }

            if (is_array($phone) && is_array($message)) {
                $iterationCount = 0;

                foreach (array_combine($phone, $message) as $number => $mess) {
                    $sendData[$iterationCount] = [
                        'phone' => "$number",
                        'text' => $mess
                    ];
                    $iterationCount++;
                }

                unset($iterationCount);
            }

            $smsParts = array_chunk($sendData, 50, true);

            $result = [];
            foreach ($smsParts as $part) {
                $curl = curl_init($callbackUrl);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($curl, CURLOPT_TIMEOUT, 30);
                curl_setopt($curl, CURLOPT_POSTFIELDS, "login=" . $login . "&password=" . $password . "&data=" . json_encode($part));
                /*curl_setopt($curl, CURLOPT_POSTFIELDS, [
                    "login"    => $login,
                    "password" => $password,
                    "data"     => json_encode($part)
                ]);*/
                $response = curl_exec($curl);
                $responseEr = curl_error($curl);


                //@file_put_contents(__DIR__ . '/logs.log', print_r([$response, $responseEr], true), FILE_APPEND);

                curl_close($curl);

                $result[] = json_decode($response, true);
            }

            return $result;
        } catch (Exception $exception) {
            return [
                'errors' => [
                    'message' => $exception->getMessage(),
                    'line' => $exception->getLine(),
                    'code' => $exception->getCode(),
                    'file' => $exception->getFile(),
                    'trace' => $exception->getTrace(),
                    'traceString' => $exception->getTraceAsString()
                ]
            ];
        }
    }

    /**
     * Генерируем случайных 6-значных чисел
     */
    public static function generateRand($length = 6): string
    {
        $chars = '1234567890';
        $numChars = strlen($chars);
        $string = '';
        for ($i = 0; $i < $length; $i++) {
            $string .= substr($chars, rand(1, $numChars) - 1, 1);
        }
        return $string;
    }
}
Editor is loading...