Passed
Push — master ( 75715f...53a757 )
by Andy
05:10
created

CsvFileObject::getLineEnding()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
namespace Palmtree\Csv;
4
5
class CsvFileObject extends \SplFileObject
6
{
7
    protected $bytesWritten = 0;
8
    protected $lineEnding = "\r\n";
9
10
    public function fputcsv($fields, $delimiter = null, $enclosure = null, $escape = null)
0 ignored issues
show
Unused Code introduced by
The parameter $escape is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
11
    {
12
        $bytes = parent::fwrite($this->getCsvString($fields, $delimiter, $enclosure));
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (fwrite() instead of fputcsv()). Are you sure this is correct? If so, you might want to change this to $this->fwrite().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
13
14
        if ($bytes === false) {
15
            return false;
1 ignored issue
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type of the parent method SplFileObject::fputcsv of type integer.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
16
        }
17
18
        $this->bytesWritten += $bytes;
19
20
        return $bytes;
21
    }
22
23
    public function __destruct()
24
    {
25
        $this->trimFinalLineEnding();
26
    }
27
28
    /**
29
     * Returns a string representation of a row to be written
30
     * as a line in a CSV file.
31
     *
32
     * @param array $row
33
     *
34
     * @param       $delimiter
35
     * @param       $enclosure
36
     *
37
     * @return string
38
     */
39
    protected function getCsvString($row, $delimiter, $enclosure)
40
    {
41
        $csvControl = $this->getCsvControl();
42
43
        $delimiter = $delimiter ? : $csvControl[0];
44
        $enclosure = $enclosure ? : $csvControl[1];
45
46
        $result = $enclosure;
47
        $result .= implode($enclosure . $delimiter . $enclosure, self::escapeEnclosure($row, $enclosure));
48
        $result .= $enclosure;
49
50
        $result .= $this->getLineEnding();
51
52
        return $result;
53
    }
54
55
    /**
56
     * @return int
57
     */
58
    public function getBytesWritten()
59
    {
60
        return (int)$this->bytesWritten;
61
    }
62
63
    /**
64
     * @return string
65
     */
66
    public function getLineEnding()
67
    {
68
        return $this->lineEnding;
69
    }
70
71
    /**
72
     * Trims the line ending delimiter from the end of the CSV file.
73
     * RFC-4180 states CSV files should not contain a trailing new line.
74
     */
75
    public function trimFinalLineEnding()
76
    {
77
        if ($this->getBytesWritten() > 0) {
78
            // Only trim the file if it ends with the line ending delimiter.
79
            $length = mb_strlen($this->getLineEnding());
80
81
            $this->fseek(-$length, SEEK_END);
82
            $chunk = $this->fread($length);
1 ignored issue
show
Bug introduced by
The method fread() does not seem to exist on object<Palmtree\Csv\CsvFileObject>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
83
84
            if ($chunk === $this->getLineEnding()) {
85
                $this->ftruncate($this->getBytesWritten() - $length);
86
            }
87
        }
88
    }
89
90
    /**
91
     * Escapes the enclosure character recursively.
92
     * RFC-4180 states the enclosure character (usually double quotes) should be
93
     * escaped by itself, so " becomes "".
94
     *
95
     * @param mixed $data Array or string of data to escape.
96
     *
97
     * @return mixed Escaped data
98
     */
99
    protected static function escapeEnclosure($data, $enclosure)
100
    {
101
        if (is_array($data)) {
102
            foreach ($data as $key => $value) {
103
                $data[$key] = self::escapeEnclosure($value, $enclosure);
104
            }
105
        } else {
106
            $data = str_replace($enclosure, str_repeat($enclosure, 2), $data);
107
        }
108
109
        return $data;
110
    }
111
}
112