<?php
/**
 * Pi Engine (http://piengine.org)
 *
 * @link            http://code.piengine.org for the Pi Engine source repository
 * @copyright       Copyright (c) Pi Engine http://piengine.org
 * @license         http://piengine.org/license.txt BSD 3-Clause License
 * @package         Registry
 */

namespace Pi\Application\Registry;

use Pi;

/**
 * Config cache
 *
 * @author Taiwen Jiang <taiwenjiang@tsinghua.org.cn>
 */
class Config extends AbstractRegistry
{
    /**
     * {@inheritDoc}
     */
    protected function loadDynamic($options = [])
    {
        $module = '';
        if (!empty($options['module'])) {
            if (!Pi::service('module')->isActive($options['module'])) {
                return false;
            }
            $module = $options['module'];
        }
        $category = null;
        if (!empty($options['category'])) {
            $category = $options['category'];
        }

        $modelConfig = Pi::model('config');
        $where       = ['module' => $module];
        if (isset($category)) {
            $where['category'] = $category;
        }
        $select  = $modelConfig->select()->columns(['name', 'value', 'filter'])->where($where);
        $rowset  = $modelConfig->selectWith($select);
        $configs = [];
        foreach ($rowset as $row) {
            $configs[$row->name] = $row->value;
        }

        return $configs;
    }

    /**
     * {@inheritDoc}
     * @param string $module
     * @param string $category
     */
    public function read($module = '', $category = '')
    {
        $module  = $module ?: 'system';
        $options = compact('module', 'category');

        return $this->loadData($options);
    }

    /**
     * {@inheritDoc}
     * @param string      $module
     * @param string|null $category
     */
    public function create($module = '', $category = '')
    {
        $this->clear($module);
        $this->read($module, $category);

        return true;
    }

    /**
     * {@inheritDoc}
     */
    public function clear($namespace = '')
    {
        $namespace = $namespace ?: 'system';
        parent::clear($namespace);

        return $this;
    }
}
