public function testSerialization() { $testData = [['firstname' => 'Bobby', 'surname' => 'Silver'], ['firstname' => 'Jake', 'surname' => 'Starkiller'], ['firstname' => 'Dirk', 'surname' => 'Diggler']]; $humanCollection = new HumanCollection(); foreach ($testData as $node) { $humanCollection->add(new Human($node['firstname'], $node['surname'])); } $this->assertEquals($humanCollection->serialize(), json_encode($testData)); }
public function writeToFile(HumanCollection $collection, string $filename) { // Can't just append to a JSON file, wouldn't be valid, I have to parse and save all of it. if (file_exists($filename)) { $serializedData = json_decode(file_get_contents($filename), true); foreach ($serializedData as $person) { $collection->add(new Human($person['firstname'], $person['surname'])); } } $serializedData = $collection->serialize(); $result = file_put_contents($filename, $serializedData); if (false === $result) { throw new Exception('Could not WRITE to file!'); } }