Completed
Pull Request — development (#2540)
by
unknown
06:26
created

PushNotification::sendNotification()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 25
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 8.439
c 0
b 0
f 0
cc 6
eloc 17
nc 4
nop 3
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 2 and the first side effect is on line 176.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
	class PushNotification extends Base {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
3
		var $tableSettings = 'push_notification_settings';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $tableSettings.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
4
		
5
		private static function getClassesInFile($file){
6
			$classes = array();
7
			$tokens = token_get_all(file_get_contents($file));
8
			$count = count($tokens);
9
			for ($i = 2; $i < $count; $i++) {
10
				if ($tokens[$i - 2][0] == T_CLASS && $tokens[$i - 1][0] == T_WHITESPACE && $tokens[$i][0] == T_STRING) {
11
					$class_name = $tokens[$i][1];
12
					$classes[] = $class_name;
13
				}
14
			}
15
			return $classes;
16
		}
17
		
18
		private static $classes = null;
19
		public function getClasses(){
20
			if (self::$classes === null){
21
				$directory = new DirectoryIterator(__DIR__.'/push_notification');
22
				foreach ($directory as $fileInfo) {
23
					if (($fileInfo->getExtension() != 'php') || $fileInfo->isDot()) {
24
						continue;
25
					}
26
					foreach (self::getClassesInFile($fileInfo->getRealPath()) as $class){
27
						if (!class_exists($class)){
28
							include $fileInfo->getRealPath();
29
						}
30
						$cr = new ReflectionClass($class);
31
						if ($cr->isSubclassOf('IPushNotification')){
32
							self::$classes[$class] = array($fileInfo->getFilename(), $cr->getMethod('getName')->invoke(null), $cr->getMethod('getParameters')->invoke(null));
33
						}
34
					}
35
				}
36
			}
37
			return self::$classes;
38
		}
39
		
40
		public function getClassesForSmarty(){
41
			$c = $this->getClasses();
42
			return array_map(function($a, $b){
43
				return array(
44
					'class' => $b,
45
					'file' => $a[0],
46
					'name' => $a[1],
47
					'parameters' => $a[2],
48
				);
49
			}, $c, array_keys($c));
50
		}
51
		
52
		/**
53
		 * @param string|array $notificator
54
		 * @param array $data
55
		 * @return IPushNotification|bool
56
		 */
57
		public function getNotificatorInstance($notificator, $data){
58
			$class = null;
59
			$file = null;
60
			
61
			if (is_array($notificator)){
62
				if (count($notificator) == 2){
63
					list($class, $file) = $notificator;
64
				} else {
65
					$class = reset($notificator);
66
				}
67
			} else {
68
				$class = $notificator;
69
			}
70
			
71
			if (!class_exists($class)){
72
				if ($file === null){
73
					foreach (self::getClasses() as $_class => $_info){
74
						if ($_class == $class){
75
							$file = $_info[0];
0 ignored issues
show
Unused Code introduced by
$file 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...
76
							break;
77
						}
78
					}
79
				} else {
80
					include __DIR__.'/push_notification/'.$file;
81
				}
82
				if (!class_exists($class)){
83
					return false;
84
				}
85
			}
86
			$cr = new ReflectionClass($class);
87
			$constructor = $cr->getConstructor();
88
			$constructorParameters = array();
89
			foreach (array_map(function($a){ return $a->getName();}, $constructor->getParameters()) as $param){
90
				$constructorParameters[] = array_key_exists($param, $data)?$data[$param]:null;
91
			}
92
			$instance = $cr->newInstanceArgs($constructorParameters);
93
			return $instance;
94
		}
95
		
96
		/**
97
		 * Update accounts push notification settings
98
		 * @param account_id int Account ID
99
		 * @param data array Data array
100
		 * @return bool
101
		 **/
102
		public function updateSettings($account_id, $data) {
103
			$this->debug->append("STA " . __METHOD__, 4);
0 ignored issues
show
Bug introduced by
The property debug does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
104
			
105
			$stmt = $this->mysqli->prepare("INSERT INTO $this->tableSettings (value, account_id) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = VALUES(value)");
0 ignored issues
show
Bug introduced by
The property mysqli does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
106
			if (!($stmt && $stmt->bind_param('si', json_encode($data), $account_id) && $stmt->execute())) {
107
				$this->setErrorMessage($this->getErrorMsg('E0047', __CLASS__));
108
				return $this->sqlError();
109
			}
110
			$this->log->log("info", "User $account_id updated notification settings");
0 ignored issues
show
Bug introduced by
The property log does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
111
			return true;
112
		}
113
		
114
		/**
115
		 * Fetch notification settings for user account
116
		 * @param id int Account ID
117
		 * @return array Notification settings
118
		 **/
119
		public function getNotificationSettings($account_id) {
120
			$this->debug->append("STA " . __METHOD__, 4);
121
			$stmt = $this->mysqli->prepare("SELECT value FROM $this->tableSettings WHERE account_id = ?");
122
			if ($stmt && $stmt->bind_param('i', $account_id) && $stmt->execute() && $result = $stmt->get_result()) {
123
				if ($result->num_rows) {
124
					/* @var $result mysqli_result */
125
					$aData = json_decode(current($result->fetch_row()), true);
126
					return $aData;
127
				} else {
128
					return array(
129
						'class' => false,
130
						'params' => null,
131
						'file' => null,
132
					);
133
				}
134
			}
135
			return $this->sqlError('E0045');
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->sqlError('E0045'); (boolean) is incompatible with the return type documented by PushNotification::getNotificationSettings of type array.

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...
136
		}
137
		
138
		private static $instance = null;
139
		/**
140
		 * @param PushNotification $instance
141
		 */
142
		public static function Instance($instance = null){
143
			if (func_num_args() == 0){
144
				return self::$instance;
145
			}
146
			return self::$instance = $instance;
147
		}
148
		
149
		public function sendNotification($account_id, $template, $aData){
150
			$settings = $this->getNotificationSettings($account_id);
151
			if ($settings['class']){
152
				$instance = $this->getNotificatorInstance(array($settings['class'], $settings['file']), $settings['params']);
153
				if ($instance){
154
					$this->smarty->assign('WEBSITENAME', $this->setting->getValue('website_name'));
0 ignored issues
show
Bug introduced by
The property setting does not seem to exist. Did you mean tableSettings?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
155
					$this->smarty->assign('SUBJECT', $aData['subject']);
156
					$this->smarty->assign('DATA', $aData);
157
						
158
					$message = false;
159
					foreach (array('/mail/push_notifications/', '/mail/notifications/') as $dir){
160
							$this->smarty->clearCache($templateFile = TEMPLATE_DIR.$dir.$template.'.tpl');
161
						try {
162
							$message = $this->smarty->fetch($templateFile);
163
						} catch (SmartyException $e){
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
Bug introduced by
The class SmartyException 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...
164
							
165
						}
166
					}
167
					if ($message){
168
						$instance->notify($message, 'info', $aData['subject']);
169
					}
170
				}
171
			}
172
			return true;
173
		}
174
	}
175
	
176
	$pushnotification = PushNotification::Instance(new PushNotification());
177
	$pushnotification->setDebug($debug);
178
	$pushnotification->setLog($log);
179
	$pushnotification->setMysql($mysqli);
180
	$pushnotification->setSmarty($smarty);
181
	$pushnotification->setConfig($config);
182
	$pushnotification->setSetting($setting);
183
	$pushnotification->setErrorCodes($aErrorCodes);
184