Completed
Push — erdiko2 ( 303fc0...d974fb )
by John
13s
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
/**
4
 * @Deprecated
5
 *
6
 * The Helper Class handle the following deprecations
7
 *
8
 * Config file as JSON, different folder structure
9
 * ToroHook Class which is deprecated too
10
 * Email also is deprecated, we have a new Email package
11
 * Cache use the Helper class to load configs
12
 * Routes use config files
13
 */
14
15
/**
16
 * Erdiko Helper
17
 *
18
 * Some global helpers
19
 *
20
 * @package     erdiko/core
21
 * @copyright   2012-2017 Arroyo Labs, Inc. http://www.arroyolabs.com
22
 * @author      John Arroyo <[email protected]>
23
 */
24
namespace erdiko;
25
26
27
class Helper
28
{
29
    /**
30
     * Log Object
31
     */
32
    protected static $_logObject=null; // @todo get rid of this
33
34
    /**
35
     * Serve your site
36
     * Loads routes based off of context and serves up the current request
37
     *
38
     * @param string $context optional context defaults to getenv('ERDIKO_CONTEXT')
39
     */
40
    public static function serve($context = null)
41
    {
42
        if(empty($context))
43
            $context = getenv('ERDIKO_CONTEXT');
44
        
45
        $routes = static::getRoutes($context);
46
        Toro::serve($routes);
47
    }
48
49
    /**
50
     * Load a view from the current theme with the given data
51
     *
52
     * @param string $viewName
53
     * @param array $data
54
     */
55
    public static function getView($viewName, $data = null, $templateRootFolder = null)
56
    {
57
        $view = new \erdiko\core\View($viewName, $data);
58
59
        if ($templateRootFolder !== null) {
60
            $view->setTemplateRootFolder($templateRootFolder);
61
        }
62
        return  $view->toHtml();
63
    }
64
    
65
    /**
66
     * Read JSON config file and return array
67
     *
68
     * @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...
69
     * @return array $config
70
     */
71 View Code Duplication
    public static function getConfigFile($filename)
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...
72
    {
73
        $filename = addslashes($filename);
74
        if (is_file($filename)) {
75
            $data = str_replace("\\", "\\\\", file_get_contents($filename));
76
            $json = json_decode($data, true);
77
78
            if (empty($json)) {
79
                throw new \Exception("Config file has a json parse error, $filename");
80
            }
81
82
        } else {
83
            throw new \Exception("Config file not found, $filename");
84
        }
85
        
86
        return $json;
87
    }
88
    
89
    /**
90
     * Get configuration
91
     */
92 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...
93
    {
94
        if($context == null)
95
            $context = getenv('ERDIKO_CONTEXT');
96
97
        $filename = ERDIKO_APP."/config/{$context}/{$name}.json";
98
        return static::getConfigFile($filename);
99
    }
100
    
101
    /**
102
     * Get the compiled application routes from the config files
103
     *
104
     * @todo cache the loaded/compiled routes
105
     */
106 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...
107
    {
108
        if($context == null)
109
            $context = getenv('ERDIKO_CONTEXT');
110
        $file = ERDIKO_APP."/config/{$context}/routes.json";
111
        $applicationConfig = static::getConfigFile($file);
112
        
113
        return $applicationConfig['routes'];
114
    }
115
    
116
    /**
117
     * Send email
118
     * @todo add ways to swap out ways of sending
119
     */
120
    public static function sendEmail($toEmail, $subject, $body, $fromEmail)
121
    {
122
        $headers = "From: $fromEmail\r\n" .
123
            "Reply-To: $fromEmail\r\n" .
124
            "X-Mailer: PHP/" . phpversion();
125
        
126
        return mail($toEmail, $subject, $body, $headers);
127
    }
128
    
129
    /**
130
     * log message to log file
131
     * If you enter null for level it will default to 'debug'
132
     *
133
     * @usage \Erdiko::log('debug',"Message here...", array())
134
     *
135
     * @param string $level
136
     * @param string $message
137
     * @param array $context
138
     * @return bool $success
139
     * @todo refactor how logging is used, eventually remove from helper
140
     */
141
    public static function log($level, $message, array $context = array())
142
    {
143
        if(static::$_logObject==null)
144
        {
145
            $erdikoContext = getenv('ERDIKO_CONTEXT');
146
            $config = static::getConfig("application", $erdikoContext);
147
            $logFiles = $config["logs"]["files"][0];
148
            $logDir = $config["logs"]["path"];
149
150
            static::$_logObject = new \erdiko\core\Logger($logFiles, $logDir);
151
        }
152
153
        if(empty($level))
154
            $level = \Psr\Log\LogLevel::DEBUG; // Default to debug for convenience
155
156
        return static::$_logObject->log($level, $message, $context);
157
    }
158
159
    /**
160
     * log debug 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 debug($message, array $context = array())
168
    {
169
        return self::log(\Psr\Log\LogLevel::DEBUG, $message, $context);
170
    }
171
172
    /**
173
     * log error message to log file
174
     *
175
     * @param string $message
176
     * @param array $context
177
     * @return bool $success
178
     * @todo refactor how logging is used, eventually remove from helper
179
     */
180
    public static function error($message, array $context = array())
181
    {
182
        return self::log(\Psr\Log\LogLevel::ERROR, $message, $context);
183
    }
184
    
185
    /**
186
     * Get the configured cache instance using name
187
     *
188
     * @return cache $cache returns the instance of the cache type
189
     */
190
    public static function getCache($cacheType = "default")
191
    {
192
        $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...
193
        $config = static::getConfig("application");
194
        
195
        if (isset($config["cache"][$cacheType])) {
196
            $cacheConfig = $config["cache"][$cacheType];
197
            $class = "erdiko\core\cache\\".$cacheConfig["type"];
198
            return new $class;
199
        } else {
200
            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\Helper::getCache of type erdiko\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...
201
        }
202
    }
203
}
204