Completed
Push — master ( 6336a8...2eca18 )
by Jacob
07:36
created

PageController::set_body_data()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
rs 10
c 0
b 0
f 0
cc 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', 'Header');
4
5
abstract class PageController
6
{
7
8
	private static $TRACKING_CODE = 'UA-11745070-1';
9
	
10
	protected static $DEPRECATED_BLOGS = array(
11
		10 => 63,
12
		55 => 67,
13
	);
14
15
	private $headers;
16
	private $css_array = array();
17
	private $font_css_array = array();
18
	private $js_array = array();
19
20
	private $data_array = array();
21
	private $body_view_array = array();
22
23
	protected function set_head_data() {}
24
	protected function set_body_data() {}
25
	protected function set_data() {}
26
27
	public function __construct()
28
	{
29
		$this->set_header_method('sendHTML');
30
		
31
		$this->set_head('google_verification', 'sgAISiuoWfK54KXnOfm2oU4vQdad8eyNCQX7LkZ1OxM');
32
		$this->set_head('bing_verification', 'AF1A4CEA30A7589590E9294C4B512607');
33
		
34
		$this->set_body('domain_container', $this->get_domain_container());
35
		$this->set_body('footer', array(
36
			'link' => Loader::getRootUrl('site'),
37
			'anchor' => 'jacobemerick.com',
38
			'date' => date('Y')));
39
	}
40
41
	protected function get_domain_container()
42
	{
43
		$domain_container = new stdclass();
44
		
45
		$domain_container->blog = Loader::getRootUrl('blog');
46
		$domain_container->home = Loader::getRootUrl('home');
47
		$domain_container->lifestream = Loader::getRootUrl('lifestream');
48
		$domain_container->map = Loader::getRootUrl('map');
49
		$domain_container->portfolio = Loader::getRootUrl('portfolio');
50
		$domain_container->waterfalls = Loader::getRootUrl('waterfalls');
51
		
52
		return $domain_container;
53
	}
54
55
    protected function get_recent_activity()
56
    {
57
        global $container;
58
        $activityRepository = new Jacobemerick\Web\Domain\Stream\Activity\MysqlActivityRepository($container['db_connection_locator']);
59
        $post_result = $activityRepository->getActivities(5);
60
61
        $post_array = array();
62
        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...
63
            array_push($post_array, $this->expand_post($row));
64
        }
65
66
        return $post_array;
67
    }
68
69
    protected function expand_post($raw_post, $format = 'short')
70
    {
71
        $post = [
72
            'type' => $raw_post['type'],
73
            'title' => ($format == 'short') ? $raw_post['message'] : $raw_post['message_long'],
74
            'date' => $this->get_parsed_date($raw_post['datetime']),
75
        ];
76
77
        if ($format != 'short') {
78
            $post['url'] = Loader::getRootUrl('lifestream') . "{$raw_post['type']}/{$raw_post['id']}/";
79
80
            $metadata = json_decode($raw_post['metadata'], true);
81
            $post = array_merge($post, $metadata);
82
        }
83
84
        return (object) $post;
85
    }
86
87
	public function activate()
88
	{
89
		$this->set_head_data();
90
		$this->set_body_data();
91
		$this->set_data();
92
		
93
		$this->load_assets();
94
		
95
		$headers = $this->headers;
96
		Header::$headers();
97
		Loader::load('view', '/Head', $this->data_array['head']);
98
		foreach($this->body_view_array as $view)
99
		{
100
			if(substr($view, 0, 1) == '/')
101
				Loader::load('view', $view, $this->data_array['body']);
102
			else
103
				Loader::load('view', URLDecode::getSite() . '/' . $view, $this->data_array['body']);
104
		}
105
        
106
        if (URLDecode::getSite() == 'waterfalls') {
107
            Loader::load('view', '/WaterfallFoot');
108
        } else {
109
            Loader::load('view', '/Foot', array('tracking_code' => self::$TRACKING_CODE));
110
        }
111
		
112
		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 98. 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...
113
			exit;
114
	}
115
116
	protected function set_header_method($method)
117
	{
118
		$this->headers = $method;
119
	}
120
121
	protected function set_title($value)
122
	{
123
		$this->set_head('title', $value);
124
	}
125
126
	protected function set_author($value)
127
	{
128
		$this->set_head('author', $value);
129
	}
130
131
	protected function set_description($value)
132
	{
133
		$this->set_head('description', $value);
134
	}
135
136
	protected function set_keywords($array)
137
	{
138
		$this->set_head('keywords', implode(', ', $array));
139
	}
140
	
141
	protected function set_canonical($url)
142
	{
143
		$this->set_head('canonical', $url);
144
	}
145
146
	protected function set_head($set, $value)
147
	{
148
		$this->data_array['head'][$set] = $value;
149
	}
150
151
	protected function set_body($set, $value)
152
	{
153
		$this->data_array['body'][$set] = $value;
154
	}
155
156
	protected function add_css($file, $version = 1)
157
	{
158
		$this->css_array[] = [$file, $version];
159
	}
160
161
	protected function add_js($file)
162
	{
163
		$this->js_array[] = $file;
164
	}
165
166
	private function load_assets()
167
	{
168
    $css_array = array_map(function ($stylesheet) {
169
      $path = "/css/{$stylesheet[0]}.css";
170
      if ($stylesheet[1] > 1) {
171
        $path .= "?v={$stylesheet[1]}";
172
      }
173
      return $path;
174
    }, $this->css_array);
175
    $js_array = array_map(function ($script) {
176
      if (substr($script, 0, 4) == 'http') {
177
        return $script;
178
      }
179
      return "/js/{$script}.min.js";
180
    }, $this->js_array);
181
		
182
		$this->set_head('css_link_array', $css_array);
183
		$this->set_head('js_link_array', $js_array);
184
	}
185
186
	protected function set_body_view($view)
187
	{
188
		$this->body_view_array[] = $view;
189
	}
190
191
	protected function eject()
192
	{
193
		if(get_class($this) !== 'Error404Controller')
194
			Loader::loadNew('controller', '/Error404Controller')->activate();
195
	}
196
197
	protected function unavailable()
198
	{
199
		if(get_class($this) !== 'Error503Controller')
200
			Loader::loadNew('controller', '/Error503Controller')->activate();
201
	}
202
203
	protected function redirect($uri, $method = 301)
204
	{
205
		switch($method)
206
		{
207 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...
208
				if(get_class($this) !== 'Error301Controller')
209
					Loader::loadNew('controller', '/Error301Controller', array($uri))->activate();
210
				break;
211 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...
212
				if(get_class($this) !== 'Error303Controller')
213
					Loader::loadNew('controller', '/Error303Controller', array($uri))->activate();
214
				break;
215
		}
216
	}
217
218
	final protected function get_parsed_date($date)
219
	{
220
		$parsed_date = new stdclass();
221
		
222
		$parsed_date->stamp = date('c', strtotime($date));
223
		$parsed_date->friendly = date('F j, Y', strtotime($date));
224
		$parsed_date->elapsed = Content::instance('ElapsedTime', $date)->activate();
225
		
226
		return $parsed_date;
227
	}
228
229
	private $comment_errors;
230
	protected function handle_comment_submit($site_id, $path, $redirect_url, $page_title)
231
	{
232
		if(Request::hasPost() && Request::getPost('submit') == 'Submit Comment')
233
		{
234
			$parameters = array($site_id, $path, $redirect_url, $page_title);
235
			$this->comment_errors = Loader::loadNew('module', 'form/CommentSubmitModule', $parameters)->activate();
236
		}
237
		
238
		return;
239
	}
240
241
    protected function get_comment_array($site, $path)
242
    {
243
        global $container;
244
        $repository = new Jacobemerick\Web\Domain\Comment\Comment\ServiceCommentRepository($container['comment_service_api']);
245
        $start = microtime(true);
246
        try {
247
            $comment_response = $repository->getComments(
248
                $site,
249
                $path,
250
                1,
251
                null,
252
                'date'
253
            );
254
        } catch (Exception $e) {
255
            $container['logger']->warning("CommentService | Path | {$e->getMessage()}");
256
            return;
257
        }
258
259
        $elapsed = microtime(true) - $start;
260
        global $container;
261
        $container['logger']->info("CommentService | Path | {$elapsed}");
262
263
        $array = array();
264
        foreach((array) $comment_response as $comment)
265
        {
266
            $body = Content::instance('CleanComment', $comment['body'])->activate();
267
            $body = strip_tags($body);
268
269
            $comment_obj = new stdclass();
270
            $comment_obj->id = $comment['id'];
271
            $comment_obj->name = $comment['commenter']['name'];
272
            $comment_obj->url = $comment['commenter']['website'];
273
            $comment_obj->trusted = true;
274
            $comment_obj->date = $comment['date']->format('M j, \'y');
275
            $comment_obj->body = $body;
276
277
            if ($comment['reply_to']) {
278
                $array[$comment['reply_to']]->replies[$comment['id']] = $comment_obj;
279
                continue;
280
            }
281
282
            $comment_obj->replies = [];
283
            $array[$comment['id']] = $comment_obj;
284
        }
285
286
        // todo figure out commenter obj
287
        // todo figure out how to handle errors or whatever
288
        // todo why is this even doing all this
289
        return [
290
            'comments' => $array,
291
            'commenter' => [],
292
            'errors' => $this->comment_errors,
293
            'comment_count' => count($comment_response),
294
        ];
295
    }
296
}
297