Yaml   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 100
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 2 Features 0
Metric Value
wmc 8
lcom 1
cbo 4
dl 0
loc 100
ccs 13
cts 13
cp 1
rs 10
c 4
b 2
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A parse() 0 19 2
A getSupportedFileExtensions() 0 4 1
A loadFile() 0 11 2
A exportFormat() 0 10 2
A __toString() 0 4 1
1
<?php
2
3
/**
4
 * Konfig.
5
 *
6
 * Yet another simple configuration loader library.
7
 *
8
 * PHP version 5
9
 *
10
 * @category Library
11
 * @package  Konfig
12
 * @author   Xeriab Nabil (aka KodeBurner) <[email protected]>
13
 * @license  https://raw.github.com/xeriab/konfig/master/LICENSE MIT
14
 * @link     https://xeriab.github.io/projects/konfig
15
 */
16
17
namespace Exen\Konfig\FileParser;
18
19
use Exception;
20
use Exen\Konfig\Exception\ParseException;
21
use Exen\Konfig\Utils;
22
use Symfony\Component\Yaml\Yaml as YamlParser;
23
24
/**
25
 * Konfig's YAML parser class.
26
 *
27
 * @category FileParser
28
 * @package  Konfig
29
 * @author   Xeriab Nabil (aka KodeBurner) <[email protected]>
30
 * @license  https://raw.github.com/xeriab/konfig/master/LICENSE MIT
31
 * @link     https://xeriab.github.io/projects/konfig
32
 *
33
 * @implements Exen\Konfig\FileParser\AbstractFileParser
34
 */
35
class Yaml extends AbstractFileParser
36
{
37
    /**
38
     * Loads a YAML/YML file as an array.
39
     *
40
     * @param string $path File path
41
     *
42
     * @throws ParseException If there is an error parsing YAML/YML file
43
     *
44
     * @return array|object|stdClass The parsed data
45
     *
46
     * @since 0.1.0
47
     */
48 6
    public function parse($path)
49
    {
50 6
        $data = null;
51
52
        try {
53 6
            $data = $this->loadFile($path);
54 4
        } catch (Exception $ex) {
55 3
            throw new ParseException(
56
                [
57 3
                    'message' => 'Error parsing YAML file',
58 3
                    'file' => realpath($path),
59 3
                    'line' => $ex->getParsedLine(),
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class Exception as the method getParsedLine() does only exist in the following sub-classes of Exception: Exen\Konfig\Exception\DumpException, Exen\Konfig\Exception\RuntimeException, Symfony\Component\Yaml\Exception\ParseException, Yosymfony\Toml\Exception\ParseException. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
60 3
                    'exception' => $ex,
61
                ]
62 1
            );
63
        }
64
65 3
        return $data;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $data; (string|array|Exen\Konfig\FileParser\stdClass) is incompatible with the return type declared by the interface Exen\Konfig\FileParser::parse of type array.

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...
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     *
71
     * @return array Supported extensions
72
     *
73
     * @since 0.1.0
74
     */
75 3
    public function getSupportedFileExtensions()
76
    {
77 3
        return ['yaml', 'yml'];
78
    }
79
80
    /**
81
     * Loads in the given file and parses it.
82
     *
83
     * @param string $file File to load
84
     *
85
     * @return string|array|stdClass The parsed file data
86
     *
87
     * @since              0.2.4
88
     * @codeCoverageIgnore
89
     */
90
    protected function loadFile($file = null)
91
    {
92
        $this->file = $file;
93
        $contents = $this->parseVars(Utils::getContent($file));
94
95
        if (extension_loaded('yaml')) {
96
            return yaml_parse($contents);
97
        }
98
99
        return YamlParser::parse($contents);
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \Symfony\Componen...Yaml::parse($contents); (string|array|stdClass) is incompatible with the return type declared by the abstract method Exen\Konfig\FileParser\A...actFileParser::loadFile of type array.

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...
100
    }
101
102
    /**
103
     * Returns the formatted configuration file contents.
104
     *
105
     * @param array $contents configuration array
106
     *
107
     * @return string formatted configuration file contents
108
     *
109
     * @since              0.2.4
110
     * @codeCoverageIgnore
111
     */
112
    protected function exportFormat($contents = null)
113
    {
114
        $this->prepVars($contents);
0 ignored issues
show
Bug introduced by
It seems like $contents defined by parameter $contents on line 112 can also be of type null; however, Exen\Konfig\FileParser\A...tFileParser::prepVars() does only seem to accept array, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
115
116
        if (extension_loaded('yaml')) {
117
            return yaml_emit($contents);
118
        }
119
120
        return YamlParser::dump($contents);
121
    }
122
123
    /**
124
     * __toString.
125
     *
126
     * @return             string
127
     * @since              0.1.2
128
     * @codeCoverageIgnore
129
     */
130
    public function __toString()
131
    {
132
        return 'Exen\Konfig\FileParser\Yaml' . PHP_EOL;
133
    }
134
}
135
136
// END OF ./src/FileParser/Yaml.php FILE
137