| 1 |
<?php |
| 2 |
/** |
| 3 |
* Read CSV file |
| 4 |
* |
| 5 |
* @package Timetics |
| 6 |
*/ |
| 7 |
namespace Timetics\Base; |
| 8 |
|
| 9 |
/** |
| 10 |
* CSV Reader Class |
| 11 |
*/ |
| 12 |
class CsvReader implements FileReaderInterface { |
| 13 |
/** |
| 14 |
* Store file |
| 15 |
* |
| 16 |
* @var string |
| 17 |
*/ |
| 18 |
private static $file; |
| 19 |
|
| 20 |
/** |
| 21 |
* Get data that will be read from csv file |
| 22 |
* |
| 23 |
* @param file $file |
| 24 |
* |
| 25 |
* @return array |
| 26 |
*/ |
| 27 |
public static function get_data( $file ) { |
| 28 |
self::$file = $file; |
| 29 |
|
| 30 |
return self::read_file(); |
| 31 |
} |
| 32 |
|
| 33 |
/** |
| 34 |
* Get from file |
| 35 |
* |
| 36 |
* @return array |
| 37 |
*/ |
| 38 |
private static function read_file() { |
| 39 |
$file = self::$file; |
| 40 |
$csv_data = []; |
| 41 |
|
| 42 |
// Initialize WP_Filesystem |
| 43 |
global $wp_filesystem; |
| 44 |
if ( empty( $wp_filesystem ) ) { |
| 45 |
require_once ABSPATH . 'wp-admin/includes/file.php'; |
| 46 |
WP_Filesystem(); |
| 47 |
} |
| 48 |
|
| 49 |
// Read file contents using WP_Filesystem |
| 50 |
$contents = $wp_filesystem->get_contents( $file ); |
| 51 |
if ( false === $contents ) { |
| 52 |
return $csv_data; |
| 53 |
} |
| 54 |
|
| 55 |
// Split content into lines |
| 56 |
$lines = explode( "\n", $contents ); |
| 57 |
if ( empty( $lines ) ) { |
| 58 |
return $csv_data; |
| 59 |
} |
| 60 |
|
| 61 |
// Parse header row |
| 62 |
$headers = str_getcsv( array_shift( $lines ) ); |
| 63 |
if ( ! $headers ) { |
| 64 |
return $csv_data; |
| 65 |
} |
| 66 |
|
| 67 |
$header_count = count( $headers ); |
| 68 |
|
| 69 |
foreach ( $lines as $line ) { |
| 70 |
// Skip empty lines |
| 71 |
if ( empty( trim( $line ) ) ) { |
| 72 |
continue; |
| 73 |
} |
| 74 |
|
| 75 |
$data = str_getcsv( $line ); |
| 76 |
if ( false === $data ) { |
| 77 |
continue; |
| 78 |
} |
| 79 |
|
| 80 |
$row = []; |
| 81 |
for ( $i = 0; $i < $header_count; $i++ ) { |
| 82 |
$row[$headers[$i]] = isset( $data[$i] ) ? $data[$i] : ''; |
| 83 |
} |
| 84 |
|
| 85 |
$csv_data[] = $row; |
| 86 |
} |
| 87 |
|
| 88 |
return $csv_data; |
| 89 |
} |
| 90 |
} |
| 91 |
|