Completed
Pull Request — master (#39)
by
unknown
02:33
created

OpauthIdentity::getAuthSource()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 3
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/**
4
 * OpauthIdentity
5
 * The SS equivalent of "index.php" and "callback.php" in the Opauth package.
6
 * @author Will Morgan <@willmorgan>
7
 * @author Dan Hensby <@dhensby>
8
 * @copyright Copyright (c) 2013, Better Brief LLP
9
 */
10
class OpauthIdentity extends DataObject {
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...
11
12
	private static
13
		$db = array(
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $db.

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...
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $db 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...
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
14
			'UID' => 'Varchar(255)',
15
			'Provider' => 'Varchar(45)',
16
		),
17
		$has_one = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $has_one 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...
18
			'Member' => 'Member',
19
		),
20
		$summary_fields = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $summary_fields 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
			'Member.Email' => 'MemberEmail',
22
			'Provider' => 'Provider',
23
			'UID' => 'UID',
24
		);
25
26
	protected
27
		/**
28
		 * @var array source from Opauth
29
		 */
30
		$authSource,
0 ignored issues
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
Coding Style introduced by
The visibility should be declared for property $authSource.

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...
31
		/**
32
		 * @var array The parsed member record, if any
33
		 */
34
		$parsedRecord;
35
36
	private
37
		/**
38
		 * @var boolean shim for onBeforeCreate
39
		 */
40
		$_isCreating = false;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $_isCreating.

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...
41
42
	/**
43
	 * factory
44
	 * Returns or creates a fresh OpauthIdentity.
45
	 * @param array $oaResponse The response object from Opauth.
46
	 * @return OpauthIdentity instance based on $oaResponse.
47
	 */
48
	public static function factory(array $oaResponse) {
49
50
		if(empty($oaResponse['auth'])) {
51
			throw new InvalidArgumentException('The auth key is required to continue.');
52
		}
53
		if(empty($oaResponse['auth']['provider'])) {
54
			throw new InvalidArgumentException('Unable to determine provider.');
55
		}
56
57
		$auth = $oaResponse['auth'];
58
59
		$do = OpauthIdentity::get()->filter(
60
			array(
61
				'Provider' => $auth['provider'],
62
				'UID' => $auth['uid'],
63
			)
64
		)->first();
65
66
		if(!$do || !$do->exists()) {
67
			$do = new OpauthIdentity();
68
			$do->Provider = $auth['provider'];
0 ignored issues
show
Documentation introduced by
The property Provider does not exist on object<OpauthIdentity>. 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...
69
			$do->UID = $auth['uid'];
0 ignored issues
show
Documentation introduced by
The property UID does not exist on object<OpauthIdentity>. 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...
70
		}
71
72
		$do->setAuthSource($auth);
73
		return $do;
74
	}
75
76
	/**
77
	 * Add an extension point for creation and member linking
78
	 */
79
	public function onBeforeWrite() {
80
		parent::onBeforeWrite();
81
		if(!$this->isInDb()) {
82
			$this->_isCreating = true;
83
			$this->extend('onBeforeCreate');
84
		}
85
		if($this->isChanged('MemberID')) {
86
			$this->extend('onMemberLinked');
87
		}
88
	}
89
90
	/**
91
	 * Add an extension point for afterCreate
92
	 */
93
	public function onAfterWrite() {
94
		parent::onAfterWrite();
95
		if($this->_isCreating === true) {
96
			$this->_isCreating = false;
97
			$this->extend('onAfterCreate');
98
		}
99
	}
100
101
	/**
102
	 * Finds a member based on this identity. Searches existing records before
103
	 * creating a new Member object.
104
	 * Note that this method does not write anything, merely sets everything up.
105
	 * @param array $usrSettings A map of settings because there are so many.
106
	 * @return Member
107
	 */
108
	public function findOrCreateMember($usrSettings = array()) {
109
110
		$defaults = array(
111
			/**
112
			 * Link this identity to any newly discovered member.
113
			 */
114
			'linkOnMatch' => true,
115
			/**
116
			 * True, false, or an array of fields to overwrite if we merge data.
117
			 * Exception to this rule is overwriteEmail, which takes precedence.
118
			 */
119
			'overwriteExistingFields' => false,
120
			/**
121
			 * Overwrite the email field if it's different. Effectively changes
122
			 * the Member login details, so it's set to false for now.
123
			 */
124
			'overwriteEmail' => false,
125
		);
126
127
		$settings = array_merge($defaults, $usrSettings);
128
129
		if($this->isInDB()) {
130
			$member = $this->Member();
0 ignored issues
show
Bug introduced by
The method Member() does not exist on OpauthIdentity. Did you maybe mean findOrCreateMember()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
131
			if($member->exists()) {
132
				return $member;
133
			}
134
		}
135
136
		$record = $this->getMemberRecordFromAuth();
137
138
		if(empty($record['Email'])) {
139
			$member = new Member();
140
		}
141
		else {
142
			$member = Member::get()->filter('Email', $record['Email'])->first();
143
144
			if(!$member) {
145
				$member = new Member();
146
			}
147
		}
148
149
		if($settings['linkOnMatch'] && $member->isInDB()) {
150
			$this->MemberID = $member->ID;
0 ignored issues
show
Documentation introduced by
The property MemberID does not exist on object<OpauthIdentity>. 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...
151
		}
152
153
		// If this is a new member, give it everything we have.
154
		if(!$member->isInDB()) {
155
			$member->update($record);
156
		}
157
		// If not, we update it carefully using the settings described above.
158
		else {
159
			$overwrite = $settings['overwriteExistingFields'];
160
			$overwriteEmail = $settings['overwriteEmail'];
161
			$fieldsToWrite = array();
162
163
			// If overwrite is true, take everything (subtract Email later)
164
			if($overwrite === true) {
165
				$fieldsToWrite = $record;
166
			}
167
			else if(is_array($overwrite)) {
168
				$fieldsToWrite = array_intersect_key($record, ArrayLib::valuekey($overwrite));
169
			}
170
			// If false then fieldsToWrite remains empty, let's coast it out.
171
172
			// Subtract email if setting is not precisely true:
173
			if($overwriteEmail !== true && isset($fieldsToWrite['Email'])) {
174
				unset($fieldsToWrite['Email']);
175
			}
176
177
			// Boom, we're so done.
178
			$member->update($fieldsToWrite);
179
		}
180
181
		return $member;
182
	}
183
184
	/**
185
	 * @param array $auth
186
	 */
187
	public function setAuthSource($auth) {
188
		$this->authSource = $auth;
189
		unset($this->parsedRecord);
190
		return $this;
191
	}
192
193
	/**
194
	 * @return array
195
	 */
196
	public function getAuthSource() {
197
		return $this->authSource;
198
	}
199
200
	/**
201
	 * @return array The mapping arrangement from auth response to Member.
202
	 */
203
	public function getMemberMapper() {
204
		$mapper = Config::inst()->get(__CLASS__, 'member_mapper');
205
		if(!isset($mapper[$this->Provider])) {
0 ignored issues
show
Documentation introduced by
The property Provider does not exist on object<OpauthIdentity>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
206
			return array();
207
		}
208
		return $mapper[$this->Provider];
0 ignored issues
show
Documentation introduced by
The property Provider does not exist on object<OpauthIdentity>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read 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.");
        }
    }

}

If the property has read access only, you can use the @property-read 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...
209
	}
210
211
	/**
212
	 * Use dot notation and/or a parser to retrieve information from a provider.
213
	 * Examples of simple dot notation:
214
	 * - 'FirstName' => 'info.first_name'
215
	 * - 'Surname' => 'info.surname'
216
	 * Examples of a parser, for example when only a "name" param is present:
217
	 * - 'FirstName' => array('OpauthResponseHelper', 'get_first_name')
218
	 * - 'Surname' => array('OpauthResponseHelper', 'get_last_name')
219
	 * @see OpauthResponseHelper
220
	 * @return array The data record to add to a member
221
	 */
222
	public function getMemberRecordFromAuth() {
223
		if(empty($this->parsedRecord)) {
224
			$record = array();
225
			foreach($this->getMemberMapper() as $memberField => $sourcePath) {
226
				if(is_array($sourcePath)) {
227
					$record[$memberField] = call_user_func($sourcePath, $this->authSource);
228
				}
229
				else if(is_string($sourcePath)) {
230
					$record[$memberField] = OpauthResponseHelper::parse_source_path($sourcePath, $this->authSource);
231
				}
232
			}
233
			$this->parsedRecord = $record;
234
		}
235
		return $this->parsedRecord;
236
	}
237
238
}
239