Completed
Pull Request — master (#4)
by Jacob
05:15
created

PageController::set_body_data()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 1
Code Lines 1

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 1
rs 10
cc 1
eloc 1
nc 1
nop 0
1
<?
0 ignored issues
show
Security Best Practice introduced by
It is not recommend to use PHP's short opening tag <?, better use <?php, or <?= in case of outputting.

Short opening tags are disabled in PHP’s default configuration. In such a case, all content of this file is output verbatim to the browser without being parsed, or executed.

As a precaution to avoid these problems better use the long opening tag <?php.

Loading history...
2
3
Loader::load('utility', array(
4
  'Header',
5
  'URLDecode'
6
));
7
8
abstract class PageController
9
{
10
11
	private static $TRACKING_CODE = 'UA-11745070-1';
12
	
13
	protected static $DEPRECATED_BLOGS = array(
14
		10 => 63,
15
		55 => 67,
16
	);
17
18
	private $headers;
19
	private $css_array = array();
20
	private $font_css_array = array();
0 ignored issues
show
Unused Code introduced by
The property $font_css_array is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
21
	private $js_array = array();
22
23
	private $data_array = array();
24
	private $body_view_array = array();
25
26
	protected function set_head_data() {}
27
	protected function set_body_data() {}
28
	protected function set_data() {}
29
30
	public function __construct()
31
	{
32
		$this->set_header_method('sendHTML');
33
		
34
		$this->set_head('google_verification', 'sgAISiuoWfK54KXnOfm2oU4vQdad8eyNCQX7LkZ1OxM');
35
		$this->set_head('bing_verification', 'AF1A4CEA30A7589590E9294C4B512607');
36
		
37
		$this->set_body('domain_container', $this->get_domain_container());
38
		$this->set_body('footer', array(
39
			'link' => Loader::getRootUrl('site'),
40
			'anchor' => 'jacobemerick.com',
41
			'date' => date('Y')));
42
43
// todo this belongs in db handler		
44
//		Loader::loadInstance('utility', 'Database');
45
//		if(Database::isConnected() === false)
46
//			$this->unavailable();
47
	}
48
49
	protected function get_domain_container()
50
	{
51
		$domain_container = new stdclass();
52
		
53
		$domain_container->blog = Loader::getRootUrl('blog');
54
		$domain_container->home = Loader::getRootUrl('home');
55
		$domain_container->lifestream = Loader::getRootUrl('lifestream');
56
		$domain_container->map = Loader::getRootUrl('map');
57
		$domain_container->portfolio = Loader::getRootUrl('portfolio');
58
		$domain_container->waterfalls = Loader::getRootUrl('waterfalls');
59
		
60
		return $domain_container;
61
	}
62
63
    protected function get_recent_activity()
64
    {
65
        global $container;
66
        $activityRepository = new Jacobemerick\Web\Domain\Stream\Activity\MysqlActivityRepository($container['db_connection_locator']);
67
        $post_result = $activityRepository->getActivities(5);
68
69
        $post_array = array();
70
        foreach($post_result as $row) {
0 ignored issues
show
Bug introduced by
The expression $post_result of type array|false is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
71
            array_push($post_array, $this->expand_post($row));
72
        }
73
74
        return $post_array;
75
    }
76
77
    protected function expand_post($raw_post, $format = 'short')
78
    {
79
        $post = [
80
            'type' => $raw_post['type'],
81
            'title' => ($format == 'short') ? $raw_post['message'] : $raw_post['message_long'],
82
            'date' => $this->get_parsed_date($raw_post['datetime']),
83
        ];
84
85
        if ($format != 'short') {
86
            $post['url'] = Loader::getRootUrl('lifestream') . "{$raw_post['type']}/{$raw_post['id']}/";
87
88
            $metadata = json_decode($raw_post['metadata'], true);
89
            $post = array_merge($post, $metadata);
90
        }
91
92
        return (object) $post;
93
    }
94
95
	public function activate()
96
	{
97
		$this->set_head_data();
98
		$this->set_body_data();
99
		$this->set_data();
100
		
101
		$this->load_assets();
102
		
103
		$headers = $this->headers;
104
		Header::$headers();
105
		Loader::load('view', '/Head', $this->data_array['head']);
106
		foreach($this->body_view_array as $view)
107
		{
108
			if(substr($view, 0, 1) == '/')
109
				Loader::load('view', $view, $this->data_array['body']);
110
			else
111
				Loader::load('view', URLDecode::getSite() . '/' . $view, $this->data_array['body']);
112
		}
113
        
114
        if (URLDecode::getSite() == 'waterfalls') {
115
            Loader::load('view', '/WaterfallFoot');
116
        } else {
117
            Loader::load('view', '/Foot', array('tracking_code' => self::$TRACKING_CODE));
118
        }
119
		
120
		if($view == '/404' || $view == '/503')
0 ignored issues
show
Bug introduced by
The variable $view seems to be defined by a foreach iteration on line 106. Are you sure the iterator is never empty, otherwise this variable is not defined?

It seems like you are relying on a variable being defined by an iteration:

foreach ($a as $b) {
}

// $b is defined here only if $a has elements, for example if $a is array()
// then $b would not be defined here. To avoid that, we recommend to set a
// default value for $b.


// Better
$b = 0; // or whatever default makes sense in your context
foreach ($a as $b) {
}

// $b is now guaranteed to be defined here.
Loading history...
121
			exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method activate() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
122
	}
123
124
	protected function set_header_method($method)
125
	{
126
		$this->headers = $method;
127
	}
128
129
	protected function set_title($value)
130
	{
131
		$this->set_head('title', $value);
132
	}
133
134
	protected function set_author($value)
135
	{
136
		$this->set_head('author', $value);
137
	}
138
139
	protected function set_description($value)
140
	{
141
		$this->set_head('description', $value);
142
	}
143
144
	protected function set_keywords($array)
145
	{
146
		$this->set_head('keywords', implode(', ', $array));
147
	}
148
	
149
	protected function set_canonical($url)
150
	{
151
		$this->set_head('canonical', $url);
152
	}
153
154
	protected function set_head($set, $value)
155
	{
156
		$this->data_array['head'][$set] = $value;
157
	}
158
159
	protected function set_body($set, $value)
160
	{
161
		$this->data_array['body'][$set] = $value;
162
	}
163
164
	protected function add_css($file, $version = 1)
165
	{
166
		$this->css_array[] = [$file, $version];
167
	}
168
169
	protected function add_js($file)
170
	{
171
		$this->js_array[] = $file;
172
	}
173
174
	private function load_assets()
175
	{
176
    $css_array = array_map(function ($stylesheet) {
177
      $path = "/css/{$stylesheet[0]}.css";
178
      if ($stylesheet[1] > 1) {
179
        $path .= "?v={$stylesheet[1]}";
180
      }
181
      return $path;
182
    }, $this->css_array);
183
    $js_array = array_map(function ($script) {
184
      if (substr($script, 0, 4) == 'http') {
185
        return $script;
186
      }
187
      return "/js/{$script}.min.js";
188
    }, $this->js_array);
189
		
190
		$this->set_head('css_link_array', $css_array);
191
		$this->set_head('js_link_array', $js_array);
192
	}
193
194
	protected function set_body_view($view)
195
	{
196
		$this->body_view_array[] = $view;
197
	}
198
199
	protected function eject()
200
	{
201
		if(get_class($this) !== 'Error404Controller')
202
			Loader::loadNew('controller', '/Error404Controller')->activate();
203
	}
204
205
	protected function unavailable()
206
	{
207
		if(get_class($this) !== 'Error503Controller')
208
			Loader::loadNew('controller', '/Error503Controller')->activate();
209
	}
210
211
	protected function redirect($uri, $method = 301)
212
	{
213
		switch($method)
214
		{
215 View Code Duplication
			case 301 :
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
216
				if(get_class($this) !== 'Error301Controller')
217
					Loader::loadNew('controller', '/Error301Controller', array($uri))->activate();
218
				break;
219 View Code Duplication
			case 303 :
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
220
				if(get_class($this) !== 'Error303Controller')
221
					Loader::loadNew('controller', '/Error303Controller', array($uri))->activate();
222
				break;
223
		}
224
	}
225
226
	final protected function get_parsed_date($date)
227
	{
228
		$parsed_date = new stdclass();
229
		
230
		$parsed_date->stamp = date('c', strtotime($date));
231
		$parsed_date->friendly = date('F j, Y', strtotime($date));
232
		$parsed_date->elapsed = Content::instance('ElapsedTime', $date)->activate();
233
		
234
		return $parsed_date;
235
	}
236
237
	private $comment_errors;
238
	protected function handle_comment_submit($site_id, $path, $redirect_url, $page_title)
239
	{
240
		if(Request::hasPost() && Request::getPost('submit') == 'Submit Comment')
241
		{
242
			$parameters = array($site_id, $path, $redirect_url, $page_title);
243
			$this->comment_errors = Loader::loadNew('module', 'form/CommentSubmitModule', $parameters)->activate();
244
		}
245
		
246
		return;
247
	}
248
249
	protected function get_comment_array($site, $path)
250
	{
251
		Loader::load('collector', 'comment/CommentCollector');
252
		
253
		$commenter = $this->get_commenter();
254
		
255
		$comment_array = array();
256
		$comment_result = CommentCollector::getCommentsForURL($site, $path, $commenter->id);
257
		
258
		foreach($comment_result as $comment)
0 ignored issues
show
Bug introduced by
The expression $comment_result of type array|false is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
259
		{
260
			$comment_object = new stdclass();
261
			$comment_object->id = $comment->id;
262
			$comment_object->body = $comment->body_format;
263
			$comment_object->date = date("M j, 'y", strtotime($comment->date));
264
			$comment_object->name = $comment->name;
265
			$comment_object->url = $comment->url;
266
			$comment_object->trusted = $comment->trusted;
267
			
268
			if($comment->reply == 0 && Request::getPost('type') == $comment->id)
269
				$comment_object->errors = $this->comment_errors;
270
			else
271
				$comment_object->errors = array();
272
			
273
			if($comment->reply == 0)
274
			{
275
				$comment_object->replies = array();
276
				$comment_array[$comment->id] = $comment_object;
277
			}
278
			else
279
				$comment_array[$comment->reply]->replies[$comment->id] = $comment_object;
280
		}
281
		
282
		$comment_count = CommentCollector::getCommentCountForURL($site, $path);
283
		
284
		return array(
285
			'comments' => $comment_array,
286
			'commenter' => $commenter,
287
			'errors' => $this->comment_errors,
288
			'comment_count' => $comment_count);
289
	}
290
291
	private function get_commenter()
292
	{
293
		Loader::load('collector', 'comment/CommentCollector');
294
		Loader::load('utility', 'Cookie');
295
		
296
		$commenter = new stdclass();
297
		
298
		$commenter->id = 0;
299
		$commenter->name = '';
300
		$commenter->email = '';
301
		$commenter->website = '';
302
		
303
		$commenter_cookie = Cookie::instance('Commenter');
304
		if(!$commenter_cookie->exists())
305
			return $commenter;
306
		
307
		$commenter_cookie_value = $commenter_cookie->getValue();
308
		$commenter_cookie_value = json_decode($commenter_cookie_value);
309
		
310
		if($commenter_cookie_value === NULL)
311
			return $commenter;
312
		
313
		if(!isset($commenter_cookie_value->name) || !isset($commenter_cookie_value->email))
314
			return $commenter;
315
		
316
		$commenter_object = CommentCollector::getCommenterByFields($commenter_cookie_value->name, $commenter_cookie_value->email, (isset($commenter_cookie_value->website) ? $commenter_cookie_value->website : ''));
317
		
318
		if($commenter_object === NULL)
319
			return $commenter;
320
		
321
		$commenter->id = $commenter_object->id;
322
		$commenter->name = $commenter_object->name;
323
		$commenter->email = $commenter_object->email;
324
		$commenter->website = $commenter_object->url;
325
		
326
		return $commenter;
327
	}
328
329
}
330