/** * Convert packable object to an array. * * @param PackableInterface $object * @return array */ public static function pack(PackableInterface $object) { $reflect = new \ReflectionClass(get_class($object)); $data = array(); foreach ($object as $key => $value) { // we don't want to send null variables if ($value === null) { continue; } // run the packer over packable objects if ($value instanceof PackableInterface) { $value = self::pack($value); } // find packing strategy $strategy = sprintf('%s_PACKER_STRATEGY', $key); $strategy = $reflect->hasConstant($strategy) ? $reflect->getConstant($strategy) : self::SINGLE_KEY_STRATEGY; // execute $strategy::pack($data, $key, $value); } // default actions foreach ($data as $key => $value) { // make sure all objects have been packed if ($value instanceof PackableInterface) { $value = self::pack($value); } // compress any remaining data structures if (is_array($value)) { Compress::pack($data, $key, $value); } } return $data; }
public function testPack() { $data = array(); $contents = array('LIKE' => 'orange', 'LOVE' => 'apple', 'HATE' => 'banana'); Compress::pack($data, 'FRUIT', $contents); $this->assertArrayHasKey('FRUIT', $data); $this->assertTrue($data['FRUIT'] === "LIKE|orange" . chr(31) . "LOVE|apple" . chr(31) . "HATE|banana", 'Compressed string is not valid.'); $this->assertCount(1, $data); }