Completed
Push — master ( 36f8ff...81ebd3 )
by John
02:24
created

Helper::sendEmail()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 1
eloc 5
nc 1
nop 4
1
<?php
2
/**
3
 * Erdiko Helper
4
 *
5
 * Some global helpers
6
 *
7
 * @package     erdiko/core
8
 * @copyright   2012-2017 Arroyo Labs, Inc. http://www.arroyolabs.com
9
 * @author      John Arroyo <[email protected]>
10
 */
11
namespace erdiko\core;
12
13
14
class Helper
15
{
16
    /**
17
     * Log Object
18
     */
19
    protected static $_logObject=null; // @todo get rid of this
20
21
    /**
22
     * Serve your site
23
     * Loads routes based off of context and serves up the current request
24
     *
25
     * @param string $context optional context defaults to getenv('ERDIKO_CONTEXT')
26
     */
27
    public static function serve($context = null)
28
    {
29
        if(empty($context))
30
            $context = getenv('ERDIKO_CONTEXT');
31
        
32
        $routes = static::getRoutes($context);
33
        Toro::serve($routes);
34
    }
35
36
    /**
37
     * Load a view from the current theme with the given data
38
     *
39
     * @param string $viewName
40
     * @param array $data
41
     */
42 View Code Duplication
    public static function getView($viewName, $data = null, $templateRootFolder = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
43
    {
44
        $view = new \erdiko\core\View($viewName, $data);
45
46
        if ($templateRootFolder !== null) {
47
            $view->setTemplateRootFolder($templateRootFolder);
48
        }
49
        return  $view->toHtml();
50
    }
51
    
52
    /**
53
     * Read JSON config file and return array
54
     *
55
     * @param string $file
0 ignored issues
show
Bug introduced by
There is no parameter named $file. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
56
     * @return array $config
57
     */
58
    public static function getConfigFile($filename)
59
    {
60
        $filename = addslashes($filename);
61
        if (is_file($filename)) {
62
            $data = str_replace("\\", "\\\\", file_get_contents($filename));
63
            $json = json_decode($data, true);
64
65
            if (empty($json)) {
66
                throw new \Exception("Config file has a json parse error, $filename");
67
            }
68
69
        } else {
70
            throw new \Exception("Config file not found, $filename");
71
        }
72
        
73
        return $json;
74
    }
75
    
76
    /**
77
     * Get configuration
78
     */
79 View Code Duplication
    public static function getConfig($name = 'application', $context = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
80
    {
81
        if($context == null)
82
            $context = getenv('ERDIKO_CONTEXT');
83
84
        $filename = ERDIKO_APP."/config/{$context}/{$name}.json";
85
        return static::getConfigFile($filename);
86
    }
87
    
88
    /**
89
     * Get the compiled application routes from the config files
90
     *
91
     * @todo cache the loaded/compiled routes
92
     */
93 View Code Duplication
    public static function getRoutes($context = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
94
    {
95
        if($context == null)
96
            $context = getenv('ERDIKO_CONTEXT');
97
        $file = ERDIKO_APP."/config/{$context}/routes.json";
98
        $applicationConfig = static::getConfigFile($file);
99
        
100
        return $applicationConfig['routes'];
101
    }
102
    
103
    /**
104
     * Send email
105
     * @todo add ways to swap out ways of sending
106
     */
107
    public static function sendEmail($toEmail, $subject, $body, $fromEmail)
108
    {
109
        $headers = "From: $fromEmail\r\n" .
110
            "Reply-To: $fromEmail\r\n" .
111
            "X-Mailer: PHP/" . phpversion();
112
        
113
        return mail($toEmail, $subject, $body, $headers);
114
    }
115
    
116
    /**
117
     * log message to log file
118
     * If you enter null for level it will default to 'debug'
119
     *
120
     * @usage \Erdiko::log('debug',"Message here...", array())
121
     *
122
     * @param string $level
123
     * @param string $message
124
     * @param array $context
125
     * @return bool $success
126
     * @todo refactor how logging is used, eventually remove from helper
127
     */
128
    public static function log($level, $message, array $context = array())
129
    {
130
        if(static::$_logObject==null)
131
        {
132
            $erdikoContext = getenv('ERDIKO_CONTEXT');
133
            $config = static::getConfig("application", $erdikoContext);
134
            $logFiles = $config["logs"]["files"][0];
135
            $logDir = $config["logs"]["path"];
136
137
            static::$_logObject = new \erdiko\core\Logger($logFiles, $logDir);
138
        }
139
140
        if(empty($level))
141
            $level = \Psr\Log\LogLevel::DEBUG; // Default to debug for convenience
142
143
        return static::$_logObject->log($level, $message, $context);
144
    }
145
146
    /**
147
     * log debug message to log file
148
     *
149
     * @param string $message
150
     * @param array $context
151
     * @return bool $success
152
     * @todo refactor how logging is used, eventually remove from helper
153
     */
154
    public static function debug($message, array $context = array())
155
    {
156
        return self::log(\Psr\Log\LogLevel::DEBUG, $message, $context);
157
    }
158
159
    /**
160
     * log error message to log file
161
     *
162
     * @param string $message
163
     * @param array $context
164
     * @return bool $success
165
     * @todo refactor how logging is used, eventually remove from helper
166
     */
167
    public static function error($message, array $context = array())
168
    {
169
        return self::log(\Psr\Log\LogLevel::ERROR, $message, $context);
170
    }
171
    
172
    /**
173
     * Get the configured cache instance using name
174
     *
175
     * @return cache $cache returns the instance of the cache type
176
     */
177
    public static function getCache($cacheType = "default")
178
    {
179
        $context = getenv('ERDIKO_CONTEXT');
0 ignored issues
show
Unused Code introduced by
$context is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
180
        $config = static::getConfig("application");
181
        
182
        if (isset($config["cache"][$cacheType])) {
183
            $cacheConfig = $config["cache"][$cacheType];
184
            $class = "erdiko\core\cache\\".$cacheConfig["type"];
185
            return new $class;
186
        } else {
187
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by erdiko\core\Helper::getCache of type erdiko\core\Cache.

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...
188
        }
189
    }
190
}
191