unserialize
might not work if have magento 2.2.x. Magento 2.0.x and Magento 2.1.x use default PHP serialize functionality. Starting from Magento 2.2.x it uses the JSON format by default.
What you can do is create a helper like this to get serialized value from DB that will work in any magento version
<?php
namespace Nwdthemes\ArraySerialized\Helper;
use Magento\Framework\App\ObjectManager;
/**
* ArraySerialized helper
*/
class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* Get config value
* @param $configPath
* @param null $store
* @return mixed
*/
public function getConfigValue($configPath, $store = null)
{
return $this->scopeConfig->getValue(
$configPath,
\Magento\Store\Model\ScopeInterface::SCOPE_STORE,
$store
);
}
/**
* Get serialized config value
* temporarily solution to get unserialized config value
* should be deprecated in 2.3.x
*
* @param $configPath
* @param null $store
* @return mixed
*/
public function getSerializedConfigValue($configPath, $store = null)
{
$value = $this->getConfigValue($configPath, $store);
if (empty($value)) return false;
if ($this->isSerialized($value)) {
$unserializer = ObjectManager::getInstance()->get(\Magento\Framework\Unserialize\Unserialize::class);
} else {
$unserializer = ObjectManager::getInstance()->get(\Magento\Framework\Serialize\Serializer\Json::class);
}
return $unserializer->unserialize($value);
}
/**
* Check if value is a serialized string
*
* @param string $value
* @return boolean
*/
private function isSerialized($value)
{
return (boolean) preg_match('/^((s|i|d|b|a|O|C):|N;)/', $value);
}
}
public function getConfigValue()
used to load any value from config table.
public function getSerializedConfigValue()
is modified to automatically unserialize config data. It detect if we have serialized string or json string and use proper method to unserialize data. This code works in both 2.0.x – 2.1.x and 2.2.x versions.
Starting from 2.2.4 it should be enough to use just getConfigValue()
.