maybeUn() public static method

Unserialize value only if it is serialized.
public static maybeUn ( string $data ) : mixed
$data string A variable that may or may not be serialized
return mixed
Example #1
0
 /**
  * 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;
     }
 }
Example #2
0
 public function testMaybeUn()
 {
     $obj = new \stdClass();
     $obj->prop1 = 'Hello';
     $obj->prop2 = 'World';
     isNull(Ser::maybeUn(serialize(null)));
     isFalse(Ser::maybeUn(serialize(false)));
     is('This is a string', Ser::maybeUn('This is a string'));
     is(5.81, Ser::maybeUn(5.81));
     is(array(), Ser::maybeUn('a:0:{}'));
     is($obj, Ser::maybeUn('O:8:"stdClass":2:{s:5:"prop1";s:5:"Hello";s:5:"prop2";s:5:"World";}'));
     is(array('test', 'blah', 'hello' => 'world', 'array' => $obj), Ser::maybeUn('a:4:{i:0;s:4:"test";i:1;s:4:"blah";s:5:"hello";s:5:"world";s:5:"array";O:8:"stdClass":2:{s:5:"prop1";s:5:"Hello";s:5:"prop2";s:5:"World";}}'));
     // Test a broken serialization.
     $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?";}';
     $unserializedData = Ser::maybeUn($brokenSerialization);
     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.');
     // Test unfixable serialization.
     $unfixableSerialization = 'a:2:{i:0;s:6:"Normal";}';
     is($unfixableSerialization, Ser::maybeUn($unfixableSerialization), 'Somehow the [previously?] impossible happened and utilphp thinks it has unserialized an unfixable serialization.');
 }