Completed
Pull Request — development (#2540)
by
unknown
02:48
created

PushNotification::getNotificatorInstance()   D

Complexity

Conditions 10
Paths 63

Size

Total Lines 38
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 38
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 27
nc 63
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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 4 and the first side effect is on line 2.

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

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
106
			return true;
107
		}
108
		
109
		/**
110
		 * Fetch notification settings for user account
111
		 * @param id int Account ID
112
		 * @return array Notification settings
113
		 **/
114
		public function getNotificationSettings($account_id) {
115
			if ($settings = UserSettings::construct($account_id)->PushNotifications){
0 ignored issues
show
Documentation introduced by
The property PushNotifications does not exist on object<UserSettings>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
116
				return $settings;
117
			}
118
			return array(
119
				'class' => false,
120
				'params' => null,
121
				'file' => null,
122
			);
123
		}
124
		
125
		private static $instance = null;
126
		/**
127
		 * @param PushNotification $instance
128
		 */
129
		public static function Instance($instance = null){
130
			if (func_num_args() == 0){
131
				return self::$instance;
132
			}
133
			return self::$instance = $instance;
134
		}
135
		
136
		public function sendNotification($account_id, $template, $aData){
137
			$settings = $this->getNotificationSettings($account_id);
138
			if ($settings['class']){
139
				$instance = $this->getNotificatorInstance(array($settings['class'], $settings['file']), $settings['params']);
140
				if ($instance){
141
					$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...
142
					$this->smarty->assign('SUBJECT', $aData['subject']);
143
					$this->smarty->assign('DATA', $aData);
144
						
145
					$message = false;
146
					foreach (array('/mail/push_notifications/', '/mail/notifications/') as $dir){
147
							$this->smarty->clearCache($templateFile = TEMPLATE_DIR.$dir.$template.'.tpl');
148
						try {
149
							$message = $this->smarty->fetch($templateFile);
150
						} 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...
151
							
152
						}
153
					}
154
					if ($message){
155
						$instance->notify($message, 'info', $aData['subject']);
156
					}
157
				}
158
			}
159
			return true;
160
		}
161
	}
162
	
163
	$pushnotification = PushNotification::Instance(new PushNotification());
164
	$pushnotification->setDebug($debug);
165
	$pushnotification->setLog($log);
166
	$pushnotification->setMysql($mysqli);
167
	$pushnotification->setSmarty($smarty);
168
	$pushnotification->setConfig($config);
169
	$pushnotification->setSetting($setting);
170
	$pushnotification->setErrorCodes($aErrorCodes);
171