Last active
October 4, 2020 09:38
-
-
Save Muqsit/82f3a74872cc611a83cf3040b6e6960e to your computer and use it in GitHub Desktop.
OnlinePlayerIterator.php
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 | |
declare(strict_types=1); | |
final class Player{ | |
/** @var int */ | |
public $id; | |
/** @var bool */ | |
public $connected = true; | |
public function __construct(int $id){ | |
$this->id = $id; | |
} | |
public function isConnected() : bool{ | |
return $this->connected; | |
} | |
} | |
final class OnlinePlayerIterator implements Iterator{ | |
/** | |
* @var Iterator | |
* @phpstan-var Iterator<Player> | |
*/ | |
private $iterator; | |
/** | |
* @param Iterator $iterator | |
* | |
* @phpstan-param Iterator<Player> | |
*/ | |
public function __construct(Iterator $iterator){ | |
$this->iterator = $iterator; | |
} | |
public function current() : Player{ | |
return $this->iterator->current(); | |
} | |
public function rewind() : void{ | |
$this->iterator->rewind(); | |
} | |
public function next() : void{ | |
$this->iterator->next(); | |
} | |
public function key(){ | |
$this->iterator->key(); | |
} | |
public function valid() : bool{ | |
while($this->iterator->valid()){ | |
if($this->current()->isConnected()){ | |
return true; | |
} | |
$this->next(); | |
} | |
return false; | |
} | |
} | |
$players = []; | |
for($i = 0; $i < 10; $i++){ | |
$players[] = new Player($i); | |
} | |
foreach(array_rand($players, 3) as $remove){ | |
echo "Setting #", $players[$remove]->id, " offline", PHP_EOL; | |
$players[$remove]->connected = false; | |
} | |
foreach(new OnlinePlayerIterator(new ArrayIterator($players)) as $player){ | |
echo "Traversed #", $player->id, PHP_EOL; | |
assert($player->isConnected()); | |
} |
Author
Muqsit
commented
Oct 4, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment