public function testExecute() { // string $stringObject = 'wwwcoinwww'; $stringObjectRet = Replacer::execute($stringObject, 'coin', 'steak'); $this->assertEquals($stringObjectRet, true); $this->assertEquals($stringObject, 'wwwsteakwww'); // serialize string $serializeObject = 'a:2:{s:7:"company";s:7:"hikouki";s:7:"website";s:26:"https://github.com/hikouki";}'; $serializeObjectRet = Replacer::execute($serializeObject, 'github.com', 'qiita.com'); $this->assertEquals($serializeObjectRet, true); $this->assertEquals($serializeObject, Ser::maybe(['company' => 'hikouki', 'website' => 'https://qiita.com/hikouki'])); }
/** * Execute * @return boolean */ public static function execute(&$object, $target, $replace) { $plainObject = Ser::maybeUn($object); if (is_array($plainObject)) { $replaced = false; foreach ($plainObject as &$value) { if (static::execute($value, $target, $replace) && !$replaced) { $replaced = true; } } $object = Ser::maybe($plainObject); return $replaced; } else { if (strpos($object, $target) !== false) { $object = str_replace($target, $replace, $object); return true; } return false; } }
public function testFix() { $expectedData = array('Normal', 'High-value Char: ' . chr(231) . 'a-va?'); $brokenSerialization = 'a:2:{i:0;s:6:"Normal";i:1;s:23:"High-value Char: ▒a-va?";}'; $expectedError = array('errno' => 8, 'errstr' => 'unserialize(): Error at offset 55 of 60 bytes'); $reportedError = array(); set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext) use(&$reportedError) { $reportedError = compact('errno', 'errstr'); }); unserialize($brokenSerialization); is($expectedError['errno'], $reportedError['errno']); // Because HHVM's unserialize() error message does not contain enough info to properly test. if (!defined('HHVM_VERSION')) { is($expectedError['errstr'], $reportedError['errstr']); } restore_error_handler(); $fixedSerialization = Ser::fix($brokenSerialization); $unserializedData = unserialize($fixedSerialization); is($expectedData[0], $unserializedData[0], 'Did not properly fix the broken serialized data.'); is(substr($expectedData[1], 0, 10), substr($unserializedData[1], 0, 10), 'Did not properly fix the broken serialized data.'); }