protected function generateUniquePaymentIdentifier($gateway = null)
    {
        $gateway = $gateway ?: $this->Gateway;
        $length = GatewayInfo::getConfigSetting($gateway, 'payment_identifier_length') ?:
            static::config()->get('payment_identifier_length');

        /** @var RandomGenerator $generator */
        $generator = Injector::inst()->get(RandomGenerator::class);

        do {
            $id = substr($generator->randomToken(), 0, $length);

            if (empty($id)) {
                throw new \RuntimeException('Random generator produced empty token');
            }
        } while (self::get()->filter('Identifier', $id)->exists());

        return $id;
    }