Skip to main content
edited title
Link
Mast
  • 13.8k
  • 12
  • 57
  • 127

How should I go about on refactoring this code? Scrape multiple twitch IRC chats

edited title
Link
hamon
  • 55
  • 6

What design pattern How should I use? How to organizego about on refactoring this bettercode?

Source Link
hamon
  • 55
  • 6

What design pattern should I use? How to organize this better?

I've always struggled to create and sustainable, organizated, clean code. I tried to use a Factory method and it's working better now that I created another class.

I know I should write documentation, but that's not the advice I'm looking for yet. Because I don't think documentation will help with organizating my code.

This code is scraping multiple twitch IRC chats and using my Laravel API to count the subscribers of multiple streamers. The code works but I have the feeling it's getting harder to implement features, change the code and even read it.

Is there any design pattern should I use for this? How can I make it better?

Request:

class Request
{
    private $requestUrl;
    private $requestFields;
    private $requestResult;
    private $requestStreamer;
    private $requestStatus;
    private $requestType;
    private $ch;

    public function __construct($streamer = null, $status = null, $url = null, $customFields = null)
    {
        $this->requestStreamer = $streamer;
        $this->requestStatus = $status;
        $this->requestFields = $customFields;
        $this->requestUrl = $url;
        $this->start();
    }
    public function setFields($fields = null)
    {
        if ($fields != null)
            $this->requestFields = $fields;

    }
    public function start()
    {
        if ($this->requestUrl == 'online') {
            $this->requestUrl = 'http://localhost:8000/api/streamers/changeOnline';
            $this->setFields(['streamer' => $this->requestStreamer, 'is_online' => $this->requestStatus]);
            $this->request();
            return;
        }
        if ($this->requestUrl == 'status') {
            $this->requestUrl = 'http://localhost:8000/api/streamers/changeStatus';
            $this->setFields(['streamer' => $this->requestStreamer, 'run' => $this->requestStatus]);
            $this->request();
            return;
        }
        if ($this->requestUrl == 'sub') {
            $this->requestUrl = 'http://localhost:8000/api/create/sub';
            $this->setFields();
            $this->request();
            dump($this->requestFields);
            return;
        }
        if ($this->requestUrl == 'checkTwitchOnline') {
            $this->requestUrl =  'https://api.twitch.tv/helix/streams/?user_login=' . $this->requestStreamer;
            $this->requestType = 'get';
            $this->setFields(array('Authorization: Bearer gokyy7wxa9apriyjr2evaccv6h71qn', 'Client-ID: gosbl0lt05vzj18la6v11lexhvpwlb'));
            $this->request();

            return $this->decode();
        }
        if ($this->requestUrl == 'getStreamers') {
            $this->requestUrl =  'http://localhost:8000/api/streamers/getAll';
            $this->requestType = 'get';
            $this->request();
            return $this->decode();
        }
        if ($this->requestUrl == null) {
            $this->requestUrl = 'http://localhost:8000/api/streamers/changeStatus';
            $this->setFields(['streamer' => $this->requestStreamer, 'run' => $this->requestStatus]);
            $this->request();

            $this->requestUrl = 'http://localhost:8000/api/streamers/changeOnline';
            $this->setFields(['streamer' => $this->requestStreamer, 'is_online' => $this->requestStatus]);
            $this->request();

            return;
        }
        return;
    }

    public function setRequestType()
    {
        curl_setopt($this->ch, CURLOPT_URL, $this->requestUrl);

        if ($this->requestType == 'get') {
            curl_setopt($this->ch, CURLOPT_HTTPGET, true);
            $this->setHeader();
        } else {
            curl_setopt($this->ch, CURLOPT_POST, true);
            $this->setHeader();
        }
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
    }
    public function setHeader()
    {
        if (!empty($this->requestFields)) {
            $fields_string = http_build_query($this->requestFields);

            if ($this->requestType == 'get') {
                curl_setopt($this->ch, CURLOPT_HTTPHEADER, $this->requestFields);
            } else {
                curl_setopt($this->ch, CURLOPT_POSTFIELDS, $fields_string);
            }
        }
    }
    public function request()
    {
        $this->ch = curl_init();
        $this->setRequestType();
        $this->requestResult = curl_exec($this->ch);

        return $this->result();
    }
    public function decode()
    {
        return json_decode($this->requestResult, true);
    }
    public function result()
    {
        //dump($this->requestResult);
        return $this->requestResult;
    }
}
class RequestFactory
{
    public static function create($streamer = null, $status = null, $url = null, $customFields = null)
    {
        return new Request($streamer, $status, $url, $customFields);
    }
}
$changeStatus = RequestFactory::create(null, null, 'getStreamers');

Main file:


use GhostZero\Tmi\Client;
use GhostZero\Tmi\ClientOptions;
use GhostZero\Tmi\Events\Twitczh\SubEvent;
use GhostZero\Tmi\Events\Twitch\AnonSubGiftEvent;
use GhostZero\Tmi\Events\Twitch\AnonSubMysteryGiftEvent;
use GhostZero\Tmi\Events\Twitch\ResubEvent;
use GhostZero\Tmi\Events\Twitch\SubGiftEvent;
use GhostZero\Tmi\Events\Twitch\SubMysteryGiftEvent;

include('requestFactory.php');
$streamers = RequestFactory::create(null, null, 'getStreamers');
$streamers = $streamers->decode();

for ($i = 0; $i <= count($streamers) - 1; ++$i) {
    $pid = pcntl_fork();
    if ($pid == -1) {
        die('could not fork');
    } else if ($pid) {
        // we are the parent
        // pcntl_wait($status); //Protect against Zombie children
    } else {
        $GLOBALS['streamer'] = ($streamers[$i]['streamer']);
        cli_set_process_title($GLOBALS['streamer'] . 'run.php');

        $request = RequestFactory::create($GLOBALS['streamer'], '1', 'status');
        $request = RequestFactory::create($GLOBALS['streamer'], null, 'checkTwitchOnline');
        $data = $request->decode();
        
        if (empty($data['data'])) {
            $request = RequestFactory::create($GLOBALS['streamer'], '0');
            die();
        }

        $request = RequestFactory::create($GLOBALS['streamer'], '1', 'online');

        $client = new Client(new ClientOptions([
            'options' => ['debug' => false],
            'connection' => [
                'secure' => true,
                'reconnect' => true,
                'rejoin' => true,
            ],
            'channels' => [$GLOBALS['streamer']]
        ]));

        /**
         * @param SubGiftEvent $event
         */
        function giftedRequest($event, $type): void
        {

            $fields = ['recipient' => $event->recipient, 'plan' => $event->plan->plan, 'type' => $type, 'gifter' => $event->user, 'streamer' => $GLOBALS['streamer']];
            RequestFactory::create($GLOBALS['streamer'], null,'sub',$fields);
        }

        /**
         * @param SubEvent $event
         */
        function subbedRequest($event, $type): void
        {
            $fields = ['recipient' => $event->user, 'plan' => $event->plan->plan, 'type' => $type, 'gifter' => NULL, 'streamer' => $GLOBALS['streamer']];
            RequestFactory::create($GLOBALS['streamer'], null,'sub',$fields);
        }

        $client->on(SubEvent::class, function (SubEvent $event) {
            subbedRequest($event, 'SubEvent');
        });
        $client->on(AnonSubGiftEvent::class, function (AnonSubGiftEvent $event) {
            print_r($event);
        });

        $client->on(AnonSubMysteryGiftEvent::class, function (AnonSubMysteryGiftEvent $event) {
            print_r($event);
        });
        $client->on(ResubEvent::class, function (ResubEvent $event) {
            subbedRequest($event, 'ResubEvent');
        });
        $client->on(SubGiftEvent::class, function (SubGiftEvent $event) {
            giftedRequest($event, 'SubGiftEvent');
        });
        $client->on(SubMysteryGiftEvent::class, function (SubMysteryGiftEvent $event) {
            subbedRequest($event, 'SubMysteryGiftEvent');
        });
        $client->connect();
    }
}

This is my first question here, let me know how can I make it better.