Циклический просмотр нескольких страниц запроса JSON (Guzzle, Laravel, PHP) - PullRequest
0 голосов
/ 18 февраля 2020

Здесь новый разработчик, поэтому я прошу прощения, если это простой вопрос или что-то в этом роде, но я не смог найти именно то, что я ищу (вполне может быть, что я тоже не правильно задаю вопрос) У меня есть список страниц, возвращаемый из API, и я не уверен, что лог c будет иметь возможность циклически просматривать эти страницы. Вот код, который у меня пока есть, который отлично работает для первой страницы. Lol.

    public function handle()
    {
        //This is the artisan command that runs on a timer and gets all the ticket and update fields that are needed and saves them to the database.
        $tickets = $this->pullTicketSummary();
        collect($tickets['data'])
            ->each(function ($currTicket) {

                $ticketRow = Tickets::query()->firstOrCreate(['ticket_id' => $currTicket['id']]);
                $ticketRow->status_id = $currTicket['status']['id'];
                $ticketRow->category_id = $currTicket['category']['id'];
                $ticketRow->user_id = $currTicket['assigned_to']['id'];
                $ticketRow->jira_issue_id = $currTicket['jira_issue_id'];
                $ticketRow->save();

                collect($currTicket['updates'])->each(function ($update) use ($currTicket){
                    $updateRow = Update::query()->firstOrCreate(['update_id' => $update['update_id']]);
                    $updateRow->ticket_id = $currTicket['id'];
                    $updateRow->assignee_change = $update['assignee_change'];
                });
            });
        Log::info('All tickets and updates were pulled successfully');
    }

    protected function pullTicketSummary()
    {       //Function makes the guzzle request and returns the response from the happyfox api
            $client = new Client();
            $request = $client->get('https://happyfox.com/api/1.1/json/tickets/?size=50&page=1',
                ['auth' => ['N/A']);
            $response = json_decode($request->getBody()->getContents(), true);
            return $response;

    }

С учетом того, что я новичок, если на этот вопрос уже отвечали до того, что я пропустил, просто застрелите меня по ссылке или, если вам известна какая-либо документация, которая поможет мне самостоятельно найти ответ, это было бы здорово! спасибо!

1 Ответ

0 голосов
/ 18 февраля 2020

Обновите свою функцию, чтобы использовать номер страницы:

protected function pullTicketSummary($page)
{       //Function makes the guzzle request and returns the response from the happyfox api
        $client = new Client();
        $request = $client->get('https://happyfox.com/api/1.1/json/tickets/?size=50&page='.$page,
            ['auth' => ['N/A']);
        $response = json_decode($request->getBody()->getContents(), true);
        return $response;

}

//new function only to save the data from tickets variable. Necessary to reuse.
public function saveTicketsOrSomething($tickets)
{
    collect($tickets['data'])
        ->each(function ($currTicket) {

            $ticketRow = Tickets::query()->firstOrCreate(['ticket_id' => $currTicket['id']]);
            $ticketRow->status_id = $currTicket['status']['id'];
            $ticketRow->category_id = $currTicket['category']['id'];
            $ticketRow->user_id = $currTicket['assigned_to']['id'];
            $ticketRow->jira_issue_id = $currTicket['jira_issue_id'];
            $ticketRow->save();

            collect($currTicket['updates'])->each(function ($update) use ($currTicket){
                $updateRow = Update::query()->firstOrCreate(['update_id' => $update['update_id']]);
                $updateRow->ticket_id = $currTicket['id'];
                $updateRow->assignee_change = $update['assignee_change'];
            });
        });
}

Затем выполняйте итерацию до тех пор, пока не закончите sh все страницы:

    $tickets = $this->pullTicketSummary(1); //first time
    $numPages = $tickets['numPages']; //update here to get the actual value of number of pages
    $this->saveTicketsOrSomething($tickets);

    for ($i = 2; $i < $numPages; $i++) { //start on 2, cause we already have fetched page 1
        $tickets = $this->pullTicketSummary($i); //other pages
        $this->saveTicketsOrSomething($tickets);
    }
    Log::info('All tickets and updates were pulled successfully');
...