protected function _applyPasswordPolicies(Validator $validator)
    {
        $rules = [];
        if (plugin('User')->settings('password_min_length')) {
            $len = intval(plugin('User')->settings('password_min_length'));
            $rules['length'] = [
                'rule' => function ($value, $context) use ($len) {
                    return mb_strlen($this->_getRawPassword($context)) >= $len;
                },
                'message' => __d('user', 'Password must be at least {0} characters long.', $len),
            ];
        }

        if (plugin('User')->settings('password_uppercase')) {
            $rules['uppercase'] = [
                'rule' => function ($value, $context) {
                    return (bool)preg_match('/[\p{Lu}]/u', $this->_getRawPassword($context));
                },
                'message' => __d('user', 'Password must contain at least one uppercase character (A-Z).'),
            ];
        }

        if (plugin('User')->settings('password_lowercase')) {
            $rules['lowercase'] = [
                'rule' => function ($value, $context) {
                    return (bool)preg_match('/[\p{Ll}]/u', $this->_getRawPassword($context));
                },
                'message' => __d('user', 'Password must contain at least one lowercase character (a-z).'),
            ];
        }

        if (plugin('User')->settings('password_number')) {
            $rules['number'] = [
                'rule' => function ($value, $context) {
                    return (bool)preg_match('/[\p{N}]/u', $this->_getRawPassword($context));
                },
                'message' => __d('user', 'Password must contain at least one numeric character (1-9).'),
            ];
        }

        if (plugin('User')->settings('password_non_alphanumeric')) {
            $rules['non_alphanumeric'] = [
                'rule' => function ($value, $context) {
                    return (bool)preg_match('/[^\p{L}\p{N}]/u', $this->_getRawPassword($context));
                },
                'message' => __d('user', 'Password must contain at least one non-alphanumeric character (e.g. #%?).'),
            ];
        }

        $validator->add('password', $rules);

        return $validator;
    }