1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 
<?php
/* --------------------------------------------------------------
   CustomerConfigurationProvider.inc.php 2018-06-15
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2018 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

/**
 * Class CustomerConfigurationProvider
 */
class CustomerConfigurationProvider
{
    /**
     * @var \CI_DB_query_builder
     */
    private $db;
    
    /**
     * @var \LanguageTextManager
     */
    private $languageTextManager;
    
    /**
     * @var array
     */
    private static $minLength = [
        'firstName'   => 'ENTRY_FIRST_NAME_MIN_LENGTH',
        'lastName'    => 'ENTRY_LAST_NAME_MIN_LENGTH',
        'dateOfBirth' => 'ENTRY_DOB_MIN_LENGTH',
        'dob'         => 'ENTRY_DOB_MIN_LENGTH',
        'email'       => 'ENTRY_EMAIL_ADDRESS_MIN_LENGTH',
        'street'      => 'ENTRY_STREET_ADDRESS_MIN_LENGTH',
        'houseNumber' => 'ENTRY_HOUSENUMBER_MIN_LENGTH',
        'company'     => 'ENTRY_COMPANY_MIN_LENGTH',
        'postcode'    => 'ENTRY_POSTCODE_MIN_LENGTH',
        'city'        => 'ENTRY_CITY_MIN_LENGTH',
        'countryZone' => 'ENTRY_STATE_MIN_LENGTH',
        'suburb'      => 'ENTRY_STATE_MIN_LENGTH',
        'state'       => 'ENTRY_STATE_MIN_LENGTH',
        'telephone'   => 'ENTRY_TELEPHONE_MIN_LENGTH',
        'password'    => 'ENTRY_PASSWORD_MIN_LENGTH'
    ];
    
    
    /**
     * @var array
     */
    private static $display = [
        'gender'      => 'ACCOUNT_GENDER',
        'dob'         => 'ACCOUNT_DOB',
        'dateOfBirth' => 'ACCOUNT_DOB',
        'company'     => 'ACCOUNT_COMPANY',
        'state'       => 'ACCOUNT_STATE',
        'telephone'   => 'ACCOUNT_TELEPHONE',
        'fax'         => 'ACCOUNT_FAX',
        'suburb'      => 'ACCOUNT_SUBURB',
        'countryZone' => 'ACCOUNT_STATE'
    ];
    
    
    /**
     * @var array
     */
    private static $errorMessages = [
        'gender'               => 'ENTRY_GENDER_ERROR',
        'firstName'            => 'ENTRY_FIRST_NAME_ERROR',
        'lastName'             => 'ENTRY_LAST_NAME_ERROR',
        'dob'                  => 'ENTRY_DATE_OF_BIRTH_ERROR',
        'dateOfBirth'          => 'ENTRY_DATE_OF_BIRTH_ERROR',
        'company'              => 'ENTRY_COMPANY_ERROR',
        'vatNumber'            => 'ENTRY_VAT_ERROR',
        'email'                => 'ENTRY_EMAIL_ADDRESS_ERROR',
        'emailAddressCheck'    => 'ENTRY_EMAIL_ADDRESS_CHECK_ERROR',
        'emailConfirmation'    => 'ENTRY_EMAIL_ADDRESS_CONFIRM_DIFFERENT_ERROR',
        'emailExists'          => 'ENTRY_EMAIL_ADDRESS_ERROR_EXISTS',
        'street'               => 'ENTRY_STREET_ADDRESS_ERROR',
        'houseNumber'          => 'ENTRY_HOUSENUMBER_ERROR',
        'postcode'             => 'ENTRY_POST_CODE_ERROR',
        'city'                 => 'ENTRY_CITY_ERROR',
        'country'              => 'ENTRY_COUNTRY_ERROR',
        'countryZone'          => 'ENTRY_STATE_ERROR',
        'countryZoneSelection' => 'ENTRY_STATE_ERROR_SELECT',
        'telephone'            => 'ENTRY_TELEPHONE_NUMBER_ERROR',
        'password'             => 'ENTRY_PASSWORD_ERROR',
        'passwordMismatch'     => 'ENTRY_PASSWORD_ERROR_NOT_MATCHING',
        'privacy'              => 'ENTRY_PRIVACY_ERROR',
        'invalidInput'         => 'ENTRY_MAX_LENGTH_ERROR'
    ];
    
    /**
     * @var array
     */
    private static $configuration = [
        'acceptPrivacy'          => [
            'table' => 'gm_configuration',
            'keys'  => [
                'GM_SHOW_PRIVACY_REGISTRATION',
                'PRIVACY_CHECKBOX_REGISTRATION'
            ]
        ],
        'optionalNames'          => [
            'table' => 'configuration',
            'keys'  => [
                'ACCOUNT_NAMES_OPTIONAL'
            ]
        ],
        'splitStreetInformation' => [
            'table' => 'configuration',
            'keys'  => [
                'ACCOUNT_SPLIT_STREET_INFORMATION'
            ]
        ],
        'moveOnlyIfNoGuest' => [
            'table' => 'configuration',
            'keys'  => [
                'MOVE_ONLY_IF_NO_GUEST'
            ]
        ],
        'genderMandatory' => [
            'table' => 'configuration',
            'keys'  => [
                'GENDER_MANDATORY'
            ]
        ]
    ];
    
    
    private static $defaultStatusId = [
        'customer' => 'DEFAULT_CUSTOMERS_STATUS_ID',
        'guest'    => 'DEFAULT_CUSTOMERS_STATUS_ID_GUEST'
    ];
    
    /**
     * @var array
     */
    private static $configurationTable = [
        'table' => 'configuration',
        'key'   => 'configuration_key',
        'value' => 'configuration_value'
    ];
    
    /**
     * @var array
     */
    private static $gmConfigurationTable = [
        'table' => 'gm_configuration',
        'key'   => 'gm_key',
        'value' => 'gm_value',
    ];
    
    
    /**
     * CustomerConfigurationProvider constructor.
     *
     * @param \CI_DB_query_builder $db                  Database access, required to fetch configurations.
     * @param \LanguageTextManager $languageTextManager Text manager to fetch error messages.
     */
    public function __construct(CI_DB_query_builder $db, LanguageTextManager $languageTextManager)
    {
        $this->db                  = $db;
        $this->languageTextManager = $languageTextManager;
    }
    
    
    /**
     * Minimum length of provided configuration field.
     * Allowed fields are 'firstName', 'lastName', 'dateOfBirth', 'dob', 'email', 'street', 'houseNumber', 'company',
     * 'postcode', 'city', 'countryZone', 'suburb', 'state', 'telephone', 'password'.
     *
     * @param \StringType $configField Determines for which configuration field the minimum length should be provided.
     *
     * @return int Minimum length of provided configuration field.
     */
    public function minLength(StringType $configField)
    {
        $this->checkIfFieldExists($configField, static::$minLength);
        
        $result   = $this->db->select(static::$configurationTable['value'])
                             ->from(static::$configurationTable['table'])
                             ->where(static::$configurationTable['key'], static::$minLength[$configField->asString()])
                             ->get()
                             ->row_array();
        $rowValue = array_key_exists(static::$configurationTable['value'],
                                     $result) ? $result[static::$configurationTable['value']] : 0;
        
        return (int)$rowValue;
    }
    
    
    /**
     * Should the provided configuration field be displayed?
     * Allowed fields are 'gender', 'dob', 'dateOfBirth', 'company', 'state', 'telephone', 'fax', 'suburb'.
     *
     * @param \StringType $configField Determines for which configuration field the display check should be performed.
     *
     * @return bool True if provided configuration field should be displayed and false otherwise.
     */
    public function display(StringType $configField)
    {
        $this->checkIfFieldExists($configField, static::$display);
        
        $result   = $this->db->select(static::$configurationTable['value'])
                             ->from(static::$configurationTable['table'])
                             ->where(static::$configurationTable['key'], static::$display[$configField->asString()])
                             ->get()
                             ->row_array();
        $rowValue = array_key_exists(static::$configurationTable['value'],
                                     $result) ? $result[static::$configurationTable['value']] : 'false';
        
        return $rowValue === 'true';
    }
    
    
    /**
     * Error message for provided configuration field.
     * Allowed fields are 'gender', 'firstName', 'lastName', 'dateOfBirth', 'company', 'vatNumber', 'email',
     * 'emailAddressCheck', 'emailConfirmation', 'emailExists', 'street', 'houseNumber', 'postcode', 'city', 'country',
     * 'countryZone', 'countryZoneSelection', 'telephone', 'password', 'passwordMismatch', 'privacy', 'invalidInput'.
     *
     * @param \StringType $configField Determines for which configuration field the error message should be provided.
     *
     * @return string Error message of provided configuration field.
     */
    public function errorMessage(StringType $configField)
    {
        $message = $this->languageTextManager->get_text(static::$errorMessages[$configField->asString()], 'general');
        
        try
        {
            $minLength = $this->minLength($configField);
            
            return sprintf($message, $minLength);
        }
        catch(InvalidArgumentException $exception)
        {
            return $message;
        }
    }
    
    
    /**
     * Checks if given configuration is enabled.
     * Allowed fields are 'acceptPrivacy', 'optionalNames', 'splitStreetInformation'.
     *
     * @param \StringType $configField Determines for which configuration field should be checked.
     *
     * @return bool True if configuration is enabled and false otherwise.
     */
    public function configuration(StringType $configField)
    {
        $this->checkIfFieldExists($configField, static::$configuration);
        
        $configField = static::$configuration[$configField->asString()];
        $table       = $configField['table'];
        $configKey   = $table
                       === static::$configurationTable['table'] ? static::$configurationTable['key'] : static::$gmConfigurationTable['key'];
        $configValue = $table
                       === static::$configurationTable['table'] ? static::$configurationTable['value'] : static::$gmConfigurationTable['value'];
        $expectation = $table === static::$configurationTable['table'] ? 'true' : '1';
        
        $result = true;
        foreach($configField['keys'] as $key)
        {
            $queryResult = $this->db->select($configValue)->from($table)->where($configKey, $key)->get()->row_array();
            $result      &= array_key_exists($configValue, $queryResult) ? $queryResult[$configValue]
                                                                           === $expectation : false;
        }
        
        return (bool)$result;
    }
    
    
    /**
     * Provides the default status id for customers and guests.
     * Allowed fields are 'customer' and 'guest'.
     *
     * @param \StringType $configField Either 'guest' or 'customer'.
     *
     * @return int Default status id of given config field.
     */
    public function defaultStatusId(StringType $configField)
    {
        $this->checkIfFieldExists($configField, static::$defaultStatusId);
        
        $result = $this->db->select(static::$configurationTable['value'])
                           ->from(static::$configurationTable['table'])
                           ->where(static::$configurationTable['key'],
                                   static::$defaultStatusId[$configField->asString()])
                           ->get()
                           ->row_array();
        
        return array_key_exists(static::$configurationTable['value'],
                                $result) ? (int)$result[static::$configurationTable['value']] : 0;
    }
    
    
    /**
     * Checks if given configuration field exists.
     *
     * @param \StringType $configField Expected configuration field.
     * @param array       $fields      Allowed configuration fields.
     *
     * @throws \InvalidArgumentException If provided config field do not exist.
     * @return $this|\CustomerConfigurationProvider Same instance for chained method calls.
     */
    protected function checkIfFieldExists(StringType $configField, array $fields)
    {
        if(!array_key_exists($configField->asString(), $fields))
        {
            throw new \InvalidArgumentException('Provided configuration field "' . $configField->asString()
                                                . '" does not exist for display. Allowed fields are "' . implode('", "',
                                                                                                                 array_keys($fields))
                                                . '".');
        }
        
        return $this;
    }
}