DBConnect::loadDotenv()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 5
rs 9.4286
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
/**
3
 * @package A simple ORM that performs basic CRUD operations
4
 * @author Surajudeen AKANDE <[email protected]>
5
 * @license MIT <https://opensource.org/licenses/MIT>
6
 * @link http://www.github.com/andela-sakande
7
 * */
8
9
namespace Sirolad\DB;
10
11
use PDO;
12
use Dotenv\Dotenv;
13
14
/**
15
 * This class manages the database connection for PotatoORM
16
 * It loads environmental variables from .env file
17
 * It has been proven to connect with MySQL and PgSQL databases.
18
 * */
19
class DBConnect
20
{
21
    /**
22
     * @var string
23
     * */
24
    protected $host;
25
    /**
26
     * @var string
27
     * */
28
    protected $user;
29
    /**
30
     * @var string
31
     * */
32
    protected $pass;
33
    /**
34
     * @var integer
35
     * */
36
    protected $dbport;
37
    /**
38
     * @var string
39
     * */
40
    protected $dbtype;
41
    /**
42
     * @var string
43
     * */
44
    protected $dbname;
45
46
    /**
47
     * This method makes connection to the database on getting the necessary parameters.
48
     * @return connection to database
49
     * */
50
    public function getConnection()
51
    {
52
        $this->loader();
53
        try {
54
            if ($this->dbtype === 'pgsql') {
55
                $conn = new PDO($this->dbtype . ':host=' . $this->host . ';port=' . $this->dbport . ';dbname=' . $this->dbname . ';user=' . $this->user . ';password=' . $this->pass);
56
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
57
                $conn->setAttribute(PDO::ATTR_PERSISTENT, false);
58
            } elseif ($this->dbtype === 'mysql') {
59
                $conn = new PDO($this->dbtype . ':host=' . $this->host . ';dbname=' . $this->dbname . ';charset=utf8mb4', $this->user, $this->pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
60
                                PDO::ATTR_PERSISTENT => false]);
61
            }
62
        } catch (PDOException $e) {
0 ignored issues
show
Bug introduced by
The class Sirolad\DB\PDOException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
63
            return $e->getMessage();
64
        }
65
66
        return $conn;
0 ignored issues
show
Bug introduced by
The variable $conn does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug Best Practice introduced by
The return type of return $conn; (PDO) is incompatible with the return type documented by Sirolad\DB\DBConnect::getConnection of type Sirolad\DB\connection.

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...
67
    }
68
69
    /**
70
     * Loads up the database configuration options from the .env file
71
     */
72
    public function loader()
73
    {
74
        $this->loadDotenv();
75
        $this->host = getenv('DB_HOST');
76
        $this->user = getenv('DB_USERNAME');
77
        $this->pass = getenv('DB_PASSWORD');
78
        $this->dbport = getenv('DB_PORT');
0 ignored issues
show
Documentation Bug introduced by
The property $dbport was declared of type integer, but getenv('DB_PORT') is of type string. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
79
        $this->dbname = getenv('DB_DATABASE');
80
        $this->dbtype = getenv('DB_ENGINE');
81
    }
82
83
    /**
84
     * Makes connection to the env file in the root folder
85
     * @return void
86
     */
87
    public function loadDotenv()
88
    {
89
        $dotEnv = new Dotenv(__DIR__.'/../..');
90
        $dotEnv->load();
91
    }
92
}
93