Last active
April 17, 2020 08:10
-
-
Save Chemaclass/14e86ab2f39947ed09bddc7aaa6153e6 to your computer and use it in GitHub Desktop.
This is the code that I used to verify locally my answer for a concret stackoverflow question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php declare(strict_types=1); | |
| # https://stackoverflow.com/a/58767497/3454593 | |
| // Usage example: | |
| $postWithImage = new PostWithImage( | |
| $chaptersUrlApi = 'https://httpbin.org/get', | |
| $imagesUrlApi = 'https://httpbin.org/get?{$key}={$value}' | |
| ); | |
| foreach ($postWithImage->generate(20) as $post) { | |
| var_dump($post); | |
| } | |
| // The code: | |
| final class PostWithImage | |
| { | |
| /** @var string */ | |
| private $chaptersUrlApi; | |
| /** @var string */ | |
| private $imagesUrlApi; | |
| public function __construct(string $chaptersUrlApi, string $imagesUrlApi) | |
| { | |
| $this->chaptersUrlApi = $chaptersUrlApi; | |
| $this->imagesUrlApi = $imagesUrlApi; | |
| } | |
| public function generate(int $total): Generator | |
| { | |
| $headers = $this->getHeaders(); | |
| foreach ($headers as $key => $value) { | |
| $images = $this->getImagesPerChapter($key, $value); | |
| foreach ($images as $image) { | |
| yield $this->makePostWithImage($image->current()['origin']); | |
| } | |
| } | |
| } | |
| private function getHeaders(): array | |
| { | |
| return $this->makeRequest($this->chaptersUrlApi)->current()['headers']; | |
| } | |
| private function getImagesPerChapter(string $key, string $value): Generator | |
| { | |
| yield $this->makeRequest(sprintf($this->imagesUrlApi, $key, $value)); | |
| } | |
| private function makeRequest(string $url): Generator | |
| { | |
| $curl = curl_init(); | |
| curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); | |
| curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); | |
| curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); | |
| curl_setopt($curl, CURLOPT_URL, $url); | |
| $result = curl_exec($curl); | |
| curl_close($curl); | |
| yield json_decode($result, true); | |
| } | |
| private function makePostWithImage(string $image): array | |
| { | |
| return [ | |
| 'post_content' => sprintf('<img src="%s">', $image), | |
| 'post_title' => 'Chapeter 2 !!', | |
| 'post_status' => 'publish', | |
| ]; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment