SaveController.class.php 2.76 KB
<?php
/**
 * Created by PhpStorm.
 * User: liyifei2012it
 * Date: 16/9/13
 * Time: 17:15
 */

namespace Apicp\Controller\Attribute;

use Common\Model\AttrModel;
use Common\Service\AttrService;

class SaveController extends AbstractController
{

    /**
     * 保存属性接口(新增、编辑保存)
     * @author liyifei
     * @time 2016-09-18 16:41:19
     */
    public function Index_post()
    {

        // 接收参数
        list($attrId, $params) = $this->getRequestParams();

        $attrServ = new AttrService();

        $isAddHandle = $attrId == -1;
        if ($isAddHandle) {
            $result = $attrServ->addAttr($params);
        } else {
            $result = $attrServ->updateAttrById($attrId, $params);
        }

        if (!$result) {
            E('_ERR_ATTR_EDIT_FAIL');
        }

        return false;
    }

    /**
     * 获取请求参数
     * @return array
     */
    private function getRequestParams()
    {
        $attrId = I('post.attr_id', -1, 'Intval');
        $type = I('post.type', -1, 'Intval');
        $isOpenCp = I('post.is_open_cp', -1, 'Intval');
        $isOpen = I('post.is_open', -1, 'Intval');
        $isShow = I('post.is_show', -1, 'Intval');
        $isRequiredCp = I('post.is_required_cp', -1, 'Intval');
        $isRequired = I('post.is_required', -1, 'Intval');
        $option = I('post.option', '');
        $attrName = I('post.attr_name', '', 'trim');
        $isAllowUserModify = I('post.is_allow_user_modify', -1, 'Intval');
        $isAllowUserModifyEdit = I('post.is_allow_user_modify_edit', -1, 'Intval');

        $params = [];

        if (!empty($attrName)) {
            $params['attr_name'] = $attrName;
        }

        if ($type != -1) {
            $params['type'] = $type;
        }

        if ($isOpenCp != -1) {
            $params['is_open_cp'] = $isOpenCp;
        }

        if ($isOpen != -1) {
            $params['is_open'] = $isOpen;
        }

        if ($isShow != -1) {
            $params['is_show'] = $isShow;
        }

        if ($isRequiredCp != -1) {
            $params['is_required_cp'] = $isRequiredCp;
        }

        if ($isRequired != -1) {
            $params['is_required'] = $isRequired;
        }

        if ($isAllowUserModify != -1) {
            $params['is_allow_user_modify'] = $isAllowUserModify;
        }

        if ($isAllowUserModifyEdit != -1) {
            $params['is_allow_user_modify_edit'] = $isAllowUserModifyEdit;
        }

        // 类型是单选或多选
        $isRadioOrMultiSelect = in_array($type, [AttrModel::ATTR_TYPE_RADIO, AttrModel::ATTR_TYPE_CHECKBOX]);
        // option不为空
        $hadOption = $isRadioOrMultiSelect && !empty($option);

        $params['option'] = $hadOption ? serialize($option) : '';

        return array($attrId, $params);
    }
}