<?php
namespace Moto\System\Widgets; use Twig_Environment; use Moto; use Zend\Stdlib\ArrayUtils; class Storage { public static function saveByWidget($widget, $content = null, $meta = null) { if (!($widget instanceof Moto\System\Widgets\AbstractWidget)) { throw new \InvalidArgumentException('Widget must be a instanceof "Moto\System\Widgets\AbstractWidget"'); } if ($content === null) { $content = $widget->exportData(); } if (!is_array($meta)) { $meta = array(); } $meta['name'] = $widget->getName(); return static::saveById($widget->getWidgetId(), $content, $meta); } public static function saveById($id, $content = null, $meta = null) { $filePath = static::_generatePathById($id); $filePath = Moto\System::getAbsolutePath($filePath); if (file_exists($filePath)) { unlink($filePath); } if (!is_array($meta)) { $meta = array(); } $meta['id'] = $id; $meta['created_at'] = time(); $meta['md5'] = md5(json_encode($content)); Moto\Util::filePutContents($filePath, '<?php return ' . var_export(array( 'meta' => $meta, 'content' => $content, ), true) . ';'); return true; } public static function loadById($id) { $filePath = static::_generatePathById($id); $absoluteFilePath = Moto\System::getAbsolutePath($filePath); if (file_exists($absoluteFilePath)) { $data = include $absoluteFilePath; } else { if (Moto\System::isDevelopmentStage()) { Moto\System\Log::warning(__CLASS__ . '::' . __FUNCTION__ . ' : File [ ' . $filePath . ' ] not exists [ id = ' . $id . ' ]'); } return false; } return $data; } public static function isExists($id) { $filePath = static::_generatePathById($id); $absoluteFilePath = Moto\System::getAbsolutePath($filePath); return file_exists($absoluteFilePath); } public static function getById($id, $key = null) { $filePath = static::_generatePathById($id); $absoluteFilePath = Moto\System::getAbsolutePath($filePath); if (file_exists($absoluteFilePath)) { $content = include $absoluteFilePath; } else { if (Moto\System::isDevelopmentStage()) { Moto\System\Log::warning(__CLASS__ . '::' . __FUNCTION__ . ' : File [ ' . $filePath . ' ] not exists [ id = ' . $id . ' ]'); } return false; } return Moto\Util::getValue($content, 'content' . (is_string($key) && $key !== '' ? '.' . $key : '') ); } public static function deleteById($id) { $filePath = static::_generatePathById($id); $absoluteFilePath = Moto\System::getAbsolutePath($filePath); if (file_exists($absoluteFilePath)) { return @unlink($absoluteFilePath); } return false; } protected static function _generatePathById($id) { $hash = md5((string) $id); $path = substr($hash, 0, 2) . '/' . $hash; return '@widgetsStorageDir/' . $path . '.php'; } } 