Skip to content

Commit

Permalink
Merge pull request #45 from watzenare/develop
Browse files Browse the repository at this point in the history
Refactoring and bug prevention
  • Loading branch information
watzenare committed Dec 16, 2015
2 parents 71f0850 + 574d565 commit d64490e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
4 changes: 4 additions & 0 deletions PushApi/Controllers/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,10 @@ public function removeUserDevice($id, $idDevice)
*/
public function removeUserDeviceByType($id, $type)
{
if (!in_array($type, Device::$validStringTypes)) {
throw new PushApiException(PushApiException::INVALID_RANGE, "Invalid type value");
}

$this->send(Device::deleteDevicesByType($id, $type));
}

Expand Down
29 changes: 21 additions & 8 deletions PushApi/Models/Device.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,26 @@ class Device extends Eloquent implements IModel
const TYPE_ANDROID = 2;
const TYPE_IOS = 3;

const STRING_TYPE_EMAIL = 'email';
const STRING_TYPE_ANDROID = 'android';
const STRING_TYPE_IOS = 'ios';

public static $validStringTypes = [
self::STRING_TYPE_EMAIL,
self::STRING_TYPE_ANDROID,
self::STRING_TYPE_IOS,
];

public static $typeToString = [
self::TYPE_EMAIL => 'email',
self::TYPE_ANDROID => 'android',
self::TYPE_IOS => 'ios',
self::TYPE_EMAIL => self::STRING_TYPE_EMAIL,
self::TYPE_ANDROID => self::STRING_TYPE_ANDROID,
self::TYPE_IOS => self::STRING_TYPE_IOS,
];

public static $stringToType = [
'email' => self::TYPE_EMAIL,
'android' => self::TYPE_ANDROID,
'ios' => self::TYPE_IOS,
self::STRING_TYPE_EMAIL => self::TYPE_EMAIL,
self::STRING_TYPE_ANDROID => self::TYPE_ANDROID,
self::STRING_TYPE_IOS => self::TYPE_IOS,
];

public $timestamps = false;
Expand Down Expand Up @@ -301,20 +311,23 @@ public static function removeDeviceById($idUser, $idDevice)
/**
* Deletes all devices of the target user id.
* @param int $idUser User identification.
* @param string $type Device type.
* @return boolean
* @throws PushApiException
*/
public static function deleteDevicesByType($idUser, $type)
{
if ($type == self::TYPE_EMAIL) {
if ($type == self::STRING_TYPE_EMAIL) {
throw new PushApiException(PushApiException::INVALID_ACTION, "Cannot remove all emails");
}

$devices = Device::where('user_id', $idUser)->get();

// Deleting only the devices of the same type and decrementing the user device counter
foreach ($devices as $device) {
if ($device->type == $type) {
if (self::$typeToString[$device->type] == $type) {
$device->delete();
User::decrementDevice($idUser, $device->type);
}
}

Expand Down

0 comments on commit d64490e

Please sign in to comment.