From 82727ac2a11474b2d5367cbef603d0b8385dba1b Mon Sep 17 00:00:00 2001 From: dinamiko Date: Mon, 24 Jan 2022 12:38:16 +0100 Subject: [PATCH] Generate unique id based on the length of the prefix --- .../src/Repository/CustomerRepository.php | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/modules/ppcp-api-client/src/Repository/CustomerRepository.php b/modules/ppcp-api-client/src/Repository/CustomerRepository.php index eb6e0cf6a..01b85c777 100644 --- a/modules/ppcp-api-client/src/Repository/CustomerRepository.php +++ b/modules/ppcp-api-client/src/Repository/CustomerRepository.php @@ -13,6 +13,7 @@ namespace WooCommerce\PayPalCommerce\ApiClient\Repository; * Class CustomerRepository */ class CustomerRepository { + const CLIENT_ID_MAX_LENGTH = 22; /** * The prefix. @@ -37,13 +38,14 @@ class CustomerRepository { * @return string */ public function customer_id_for_user( int $user_id ): string { + $unique_id = $this->generate_unique_id(); if ( 0 === $user_id ) { $guest_customer_id = WC()->session->get( 'ppcp_guest_customer_id' ); if ( is_string( $guest_customer_id ) && $guest_customer_id ) { return $guest_customer_id; } - $unique_id = $this->prefix . uniqid(); + $unique_id = $this->generate_unique_id(); WC()->session->set( 'ppcp_guest_customer_id', $unique_id ); return $unique_id; @@ -56,4 +58,17 @@ class CustomerRepository { return $this->prefix . (string) $user_id; } + + /** + * Generates a unique id based on the length of the prefix. + * + * @return string + */ + protected function generate_unique_id(): string { + $offset = self::CLIENT_ID_MAX_LENGTH - strlen( $this->prefix ); + + return strlen( uniqid() ) > $offset + ? $this->prefix . substr( uniqid(), $offset ) + : $this->prefix . uniqid(); + } }