Skip to content

Instantly share code, notes, and snippets.

@bz0
Created March 28, 2024 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bz0/7a47a356b16e1e985da2754c1795b570 to your computer and use it in GitHub Desktop.
Save bz0/7a47a356b16e1e985da2754c1795b570 to your computer and use it in GitHub Desktop.
<?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