From ebac18ebef0073fb8e6b230f11f3a9f691dabcc1 Mon Sep 17 00:00:00 2001 From: Nabeel Shahzad Date: Sun, 2 Sep 2018 15:07:54 -0400 Subject: [PATCH] Make sure created ICAO in factory is unique otherwise tests fail --- app/Database/factories/AirportFactory.php | 32 ++++++++++++++++++----- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/app/Database/factories/AirportFactory.php b/app/Database/factories/AirportFactory.php index 1909a8f5..ad49dbb0 100644 --- a/app/Database/factories/AirportFactory.php +++ b/app/Database/factories/AirportFactory.php @@ -2,18 +2,36 @@ use Faker\Generator as Faker; +/** + * Create an ICAO for use in the factory. + */ +if (!function_exists('createFactoryICAO')) { + function createFactoryICAO(): string + { + $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + $max = strlen($characters) - 1; + $string = ''; + for ($i = 0; $i < 4; $i++) { + try { + $string .= $characters[random_int(0, $max)]; + } catch (Exception $e) { + } + } + + return $string; + } +} + /* * Add any number of airports. Don't really care if they're real or not */ $factory->define(App\Models\Airport::class, function (Faker $faker) { + $used = []; return [ - 'id' => function () { - $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; - $string = ''; - $max = strlen($characters) - 1; - for ($i = 0; $i < 4; $i++) { - $string .= $characters[random_int(0, $max)]; - } + 'id' => function () use ($used) { + do { + $string = createFactoryICAO(); + } while (in_array($string, $used, true)); return $string; },