Passed
Push — master ( 7b39eb...30c9e1 )
by Dmitry
14:30 queued 12:48
created

generateUniqueNumericValue()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
nc 1
nop 3
dl 0
loc 5
c 1
b 0
f 0
cc 2
rs 10
1
<?php
2
3
function generateUniqueNumericValue($existingValues, $min, $max) {
4
    do {
5
        $uniqueValue = mt_rand($min, $max);
6
    } while (in_array($uniqueValue, $existingValues));
7
    return $uniqueValue;
8
}
9
10
// Configurable product count
11
$productCount = 10000; // Set the number of products to generate
12
13
// Path to input and output files
14
$inputFile = 'exported_product.csv';
15
$outputFile = 'extended_products_' . $productCount . '.csv';
16
17
// Read the input CSV
18
if (!file_exists($inputFile)) {
19
    die("File not found: $inputFile");
20
}
21
22
$data = array_map(function ($line) {
23
    return str_getcsv($line, ';'); // Use ";" as the delimiter
24
}, file($inputFile));
25
26
$header = array_shift($data); // Extract the headers
27
28
// Ensure there is at least one row of data
29
if (empty($data)) {
30
    die("No data found for processing in the file.");
31
}
32
33
// Use the first row as a template for duplication
34
$templateRow = $data[0];
35
36
// Determine the indexes for the unique fields
37
$gtinIndex = array_search('GTINs', $header);
38
$nameEnIndex = array_search('name-en_US', $header);
39
40
if ($gtinIndex === false || $nameEnIndex === false) {
41
    die("Required columns not found: 'GTINs', 'name-en_US'");
42
}
43
44
// Create arrays to track unique values
45
$existingGtins = [$templateRow[$gtinIndex]];
46
$existingEnNames = [$templateRow[$nameEnIndex]];
47
48
// Increase the number of records to the configured amount
49
$data = []; // Clear the data array for populating
50
for ($i = 0; $i < $productCount; $i++) {
51
    $newRow = $templateRow;
52
53
    // Generate unique 'GTINs' (numeric values, 13 characters long)
54
    $newRow[$gtinIndex] = generateUniqueNumericValue($existingGtins, 1000000000000, 9999999999999);
55
    $existingGtins[] = $newRow[$gtinIndex];
56
57
    // Generate unique 'name-en_US'
58
    $newRow[$nameEnIndex] = 'V7 Noise Isolating Stereo Earbuds ' . $i;
59
60
    $data[] = $newRow;
61
}
62
63
// Save the result to a new CSV file with ";" as the delimiter
64
$outputHandle = fopen($outputFile, 'w');
65
if ($outputHandle === false) {
66
    die("Failed to open file for writing: $outputFile");
67
}
68
69
// Write headers
70
fputcsv($outputHandle, $header, ';');
71
72
// Write data
73
foreach ($data as $row) {
74
    fputcsv($outputHandle, $row, ';');
75
}
76
77
fclose($outputHandle);
78
79
echo "File successfully created: $outputFile\n";
80