Code Coverage for /src/SciPhp/NumPhp/FileTrait.php

 
Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
FileTrait
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
6
100.00% covered (success)
100.00%
1 / 1
 loadtxt
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
6
1 <?php
2
3 declare(strict_types=1);
4
5 namespace SciPhp\NumPhp;
6
7 use SciPhp\NdArray;
8 use Webmozart\Assert\Assert;
9
10 /**
11  * File methods
12  */
13 trait FileTrait
14 {
15     /**
16      * Load data from a text file.
17      *
18      * @param string $file
19      *
20      * @param array $options
21      *  default is
22      *  [
23      *    'headers'   => false,
24      *    'delimiter' => ';'
25      *  ]
26      *
27      * @link http://sciphp.org/numphp.loadtxt Documentation
28      *
29      * @api
30      */
31     final public static function loadtxt(string $file, array $options = []): NdArray
32     {
33         Assert::string($file);
34         Assert::file($file = realpath($file));
35
36         $m = [];
37         $options = array_merge(
38             ['headers' => false, 'delimiter' => ';'],
39             $options
40         );
41
42         $handle = fopen($file, 'r');
43         if ($handle !== false) {
44             $row = 0;
45             $num = 0;
46
47             while (($data = fgetcsv($handle, 2048, $options['delimiter'])) !== false) {
48                 if ($row === 0) {
49                     $num = count($data);
50                 }
51
52                 Assert::eq($num, count($data));
53
54                 if ($options['headers'] && $row === 0) {
55                     // skip headers
56                     $options['headers'] = false;
57                 } else {
58                     $m[] = $data;
59                 }
60
61                 $row++;
62             }
63
64             fclose($handle);
65         }
66
67         return static::ar($m);
68     }
69 }