Created
March 28, 2024 03:22
-
-
Save bz0/7a47a356b16e1e985da2754c1795b570 to your computer and use it in GitHub Desktop.
This file contains 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 | |
final class TweetCollection implements \IteratorAggregate, \Countable | |
{ | |
public function __construct(array $attributes = []) | |
{ | |
} | |
/** | |
* @param Tweet $tweet | |
*/ | |
public function add(Tweet $tweet): void | |
{ | |
$this->attributes[] = $tweet; | |
} | |
/** | |
* @return int | |
*/ | |
public function count(): int | |
{ | |
return count($this->attributes); | |
} | |
/** | |
* @return Tweet[]|ArrayIterator | |
*/ | |
public function getIterator() | |
{ | |
return new \ArrayIterator($this->attributes); | |
} | |
} | |
class Tweet implements \JsonSerializable | |
{ | |
private $text = null; | |
private $media_ids = null; | |
public function __construct($text='', $media_ids=[]) | |
{ | |
$this->text = $text; | |
$this->media_ids = $media_ids; | |
} | |
public function jsonSerialize() { | |
$result = []; | |
$result['text'] = $this->text; | |
// 画像あれば入れる | |
if (count($this->media_ids) > 0) { | |
$result['media_ids'] = $this->media_ids; | |
} | |
return $result; | |
} | |
} | |
$twlist = new TweetCollection(); | |
$twlist->add(new Tweet('aaaa', ['111', '222'])); | |
$twlist->add(new Tweet('bb', ['3', '5'])); | |
foreach($twlist as $tw){ | |
var_dump(json_encode($tw)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment