<?php
/**
 * Copyright 2007 Maintainable Software, LLC
 * Copyright 2008-2017 Horde LLC (http://www.horde.org/)
 *
 * See the enclosed file LICENSE for license information (BSD). If you
 * did not receive this file, see http://www.horde.org/licenses/bsd.
 *
 * @author     Mike Naberezny <mike@maintainable.com>
 * @author     Derek DeVries <derek@maintainable.com>
 * @author     Chuck Hagenbuch <chuck@horde.org>
 * @category   Horde
 * @license    http://www.horde.org/licenses/bsd
 * @package    Db
 * @subpackage Adapter
 */

/**
 *
 *
 * @author     Mike Naberezny <mike@maintainable.com>
 * @author     Derek DeVries <derek@maintainable.com>
 * @author     Chuck Hagenbuch <chuck@horde.org>
 * @category   Horde
 * @copyright  2007 Maintainable Software, LLC
 * @copyright  2008-2017 Horde LLC
 * @license    http://www.horde.org/licenses/bsd
 * @package    Db
 * @subpackage Adapter
 */
class Horde_Db_Adapter_Mysql_Column extends Horde_Db_Adapter_Base_Column
{
    /**
     * @var array
     */
    protected $_hasEmptyStringDefault = array('binary', 'string', 'text');

    /**
     * @var string
     */
    protected $_originalDefault = null;

    /**
     * Construct
     * @param   string  $name
     * @param   string  $default
     * @param   string  $sqlType
     * @param   boolean $null
     */
    public function __construct($name, $default, $sqlType=null, $null=true)
    {
        $this->_originalDefault = $default;
        parent::__construct($name, $default, $sqlType, $null);

        if ($this->_isMissingDefaultForgedAsEmptyString()) {
            $this->_default = null;
        }
    }

    /**
     */
    protected function _setSimplifiedType()
    {
        if (strpos(Horde_String::lower($this->_sqlType), 'tinyint(1)') !== false) {
            $this->_type = 'boolean';
            return;
        } elseif (preg_match('/enum/i', $this->_sqlType)) {
            $this->_type = 'string';
            return;
        }
        parent::_setSimplifiedType();
    }

    /**
     * MySQL misreports NOT NULL column default when none is given.
     * We can't detect this for columns which may have a legitimate ''
     * default (string, text, binary) but we can for others (integer,
     * datetime, boolean, and the rest).
     *
     * Test whether the column has default '', is not null, and is not
     * a type allowing default ''.
     *
     * @return  boolean
     */
    protected function _isMissingDefaultForgedAsEmptyString()
    {
        return !$this->_null && $this->_originalDefault == '' &&
            !in_array($this->_type, $this->_hasEmptyStringDefault);
    }

}
