3 * @see https://github.com/zendframework/zend-serializer for the canonical source repository
4 * @copyright Copyright (c) 2005-2018 Zend Technologies USA Inc. (https://www.zend.com)
5 * @license https://github.com/zendframework/zend-serializer/blob/master/LICENSE.md New BSD License
8 namespace Zend\Serializer\Adapter
;
11 use Zend\Serializer\Exception
;
12 use Zend\Stdlib\ErrorHandler
;
14 class PhpSerialize
extends AbstractAdapter
17 * Serialized boolean false value
21 private static $serializedFalse = null;
24 * @var PhpSerializeOptions
31 * @param array|Traversable|PhpSerializeOptions|null $options
33 public function __construct($options = null)
35 // needed to check if a returned false is based on a serialize false
36 // or based on failure (igbinary can overwrite [un]serialize functions)
37 if (static::$serializedFalse === null) {
38 static::$serializedFalse = serialize(false);
41 parent
::__construct($options);
47 * @param array|Traversable|PhpSerializeOptions $options
48 * @return PhpSerialize
50 public function setOptions($options)
52 if (! $options instanceof PhpSerializeOptions
) {
53 $options = new PhpSerializeOptions($options);
56 $this->options
= $options;
63 * @return PhpSerializeOptions
65 public function getOptions()
67 if ($this->options
=== null) {
68 $this->options
= new PhpSerializeOptions();
71 return $this->options
;
75 * Serialize using serialize()
79 * @throws Exception\RuntimeException On serialize error
81 public function serialize($value)
83 ErrorHandler
::start();
84 $ret = serialize($value);
85 $err = ErrorHandler
::stop();
87 throw new Exception\
RuntimeException('Serialization failed', 0, $err);
96 * @todo Allow integration with unserialize_callback_func
97 * @param string $serialized
99 * @throws Exception\RuntimeException on unserialize error
101 public function unserialize($serialized)
103 if (! is_string($serialized) ||
! preg_match('/^((s|i|d|b|a|O|C):|N;)/', $serialized)) {
104 $value = $serialized;
105 if (is_object($value)) {
106 $value = get_class($value);
107 } elseif (! is_string($value)) {
108 $value = gettype($value);
111 throw new Exception\
RuntimeException(sprintf(
112 'Serialized data must be a string containing serialized PHP code; received: %s',
117 // If we have a serialized boolean false value, just return false;
118 // prevents the unserialize handler from creating an error.
119 if ($serialized === static::$serializedFalse) {
123 ErrorHandler
::start(E_NOTICE
);
125 // The second parameter to unserialize() is only available on PHP 7.0 or higher
126 $ret = PHP_MAJOR_VERSION
>= 7
127 ?
unserialize($serialized, ['allowed_classes' => $this->getOptions()->getUnserializeClassWhitelist()])
128 : unserialize($serialized);
130 $err = ErrorHandler
::stop();
131 if ($ret === false) {
132 throw new Exception\
RuntimeException('Unserialization failed', 0, $err);