Skip to content

Instantly share code, notes, and snippets.

@nask0
Created April 15, 2016 09:10
Show Gist options
  • Save nask0/bd402cbfbc789f702ccb84f52db03e99 to your computer and use it in GitHub Desktop.
Save nask0/bd402cbfbc789f702ccb84f52db03e99 to your computer and use it in GitHub Desktop.
<?php
namespace CloseContacts\Lib\DataServices;
use \CloseContacts\Models\Devices;
use \CloseContacts\Models\UsersRoles;
use \CloseContacts\Models\Users as UsersModel;
use \CloseContacts\Lib\Utilities\Str;
use \CloseContacts\Lib\Utilities\Date;
use \CloseContacts\Lib\Security\Utils as SecUtils;
class Users extends DataServiceAbstract
{
/**
* @param array $data
* @return bool|array (get errors with $this->getValidationErrors())
*/
public function save( array $data )
{
try {
// VALIDATION STUFF GOES HERE, INTENTIONALLY OMITTED FOR EXAMPLE
// requested data is filtered and validated at this point, start db transaction
$tx = $this->_getTransaction();
$newUser = new UsersModel();
$newUser->setTransaction($tx);
$newUser->setName( $userData['name'] );
$newUser->setUsername( $userData['username'] );
$newUser->setCountryCode( $userData['country_code'] );
$newUser->setPhoneNumber( $userData['phone_number'] );
$newUser->setIsVerified( 0 );
$newUser->setCreatedAt( Date::getUTCTimestamp() );
$newUser->setUpdatedAt( Date::getUTCTimestamp() );
// Note: in one perfect world private keys/salts should be kept separate from db
$newUser->setSalt( base64_encode('salt') );
$newUser->setPrivateKey( base64_encode('private key') );
$newUser->setPassword( 'password' );
if( false === $newUser->save() ) {
$tx->rollback( 'Unable to save new user' );
}
$newDevice = new Devices();
$newDevice->setTransaction( $tx );
$newDevice->setUuid( $deviceData['device_uuid'] );
$newDevice->setPlatform( $deviceData['platform'] );
$newDevice->setPhoneNumber( $userData['phone_number'] );
$newDevice->setUserId( $newUser->getId() );
$newDevice->setIsEnabled( 0 );
$newDevice->setIsPrimary( 1 );
$newDevice->setIsVerified( 0 );
$newDevice->setCreatedAt( Date::getUTCTimestamp() );
$newDevice->setUpdatedAt( Date::getUTCTimestamp() );
if( false === $newDevice->save() ) {
$tx->rollback( 'Unable to save new device' );
}
$roles = new UsersRoles();
$roles->setUserId( $newUser->getId() );
$roles->setRoleId( UsersRoles::ROLE_NON_VERIFIED_USER );
if( false === $roles->save() ) {
$tx->rollback( 'Unable to save user role' );
}
$tx->commit();
return array_merge(
$newUser->toArray([ 'id', 'name', 'username', 'is_verified', 'phone_number', 'country_code', 'created_at' ]),
[
'platform' => $newDevice->getPlatform(),
'deviceId' => $newDevice->getId(),
'deviceUUID' => $newDevice->getUuid()
]
);
} catch( \Exception $e ) {
$this->_setValidationError( 'unexpected', 'Unable to register user : ' . $e->getMessage() );
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment