public function createJsonRequest($method, array $params = [])
 {
     $this->request = new Request(Arr::get($params, 'getParams', []), [], Arr::get($params, 'attributes', []), [], [], [], Arr::get($params, 'content') !== null ? json_encode($params['content']) : '');
     $this->request->setMethod($method);
     $this->request->headers->set('CONTENT_TYPE', 'application/json');
     return $this->request;
 }
Exemple #2
0
 /**
  * {@inheritDoc}
  */
 public function checkClientCredentials($clientId, $clientSecret = null)
 {
     $select = new Select($this->config['client_table']);
     $select->where(array('client_id' => $clientId));
     $result = $this->execute($select)->current();
     return Arr::get($result, 'client_secret', null) === $clientSecret;
 }
 /**
  * {@inheritDoc}
  */
 public function register(Application $app)
 {
     $app['email.mapper'] = $app->share(function (Application $app) {
         return new EmailMapper($app['db'], new EmailEntity());
     });
     $app['email.service'] = $app->share(function (Application $app) {
         $service = new EmailService();
         $service->setEmailMapper($app['email.mapper'])->setEmailConfig($app['config']->load('email'))->setResque($app['resque']);
         return $service;
     });
     $app['email.sender'] = $app->share(function (Application $app) {
         $emailConfig = $app['config']->load('email');
         if (!($apiKey = Arr::path($emailConfig, 'sender.mandrill.apiKey'))) {
             return;
         }
         $sender = new MandrillSender(new Mandrill($apiKey), $app['email.mapper']);
         $sender->setConfig($emailConfig);
         return $sender;
     });
     $app['email.send'] = $app->share(function (Application $app) {
         $command = new SendEmailCommand('email:send');
         $command->setEmailMapper($app['email.mapper']);
         if ($app['email.sender']) {
             $command->setEmailSender($app['email.sender']);
         }
         return $command;
     });
 }
 /**
  * Wrap the handle function and only allow a record through if it is not a
  * DummyException
  *
  * {@inheritDoc}
  */
 public function handle(array $record)
 {
     $e = Arr::path($record, 'context.exception');
     if ($e !== null and $e instanceof DummyException) {
         return false;
     }
     return $this->handler->handle($record);
 }
 public function withUserFoundHavingPassword($password, $attributes = [])
 {
     $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
     $attributes['enabled'] = Arr::get($attributes, 'enabled', '1');
     $attributes['verified'] = Arr::get($attributes, 'verified', '1');
     $attributes['password'] = $hashedPassword;
     $user = new UserEntity($attributes);
     $this->mockUserService->expects($this->any())->method('findByEmail')->will($this->returnValue($user));
 }
 public function setMockInputWithArguments(array $args = [])
 {
     $this->mocks['input'] = $this->getMockBuilder('Symfony\\Component\\Console\\Input\\ArrayInput')->disableOriginalConstructor()->getMock();
     $this->mocks['input']->expects($this->any())->method('getArguments')->will($this->returnValue($args));
     $getter = function ($field) use($args) {
         return Arr::get($args, $field);
     };
     $this->mocks['input']->expects($this->any())->method('getArgument')->will($this->returnCallback($getter));
 }
 /**
  * Create an email entity from an array and populate with default data
  *
  * @param  array  $data Data to populate the email
  * @return Email
  */
 public function createFromArray(array $data)
 {
     $headers = json_encode(Arr::path($this->emailConfig, 'defaults.headers', []));
     $defaults = ['headers' => $headers, 'sender_email' => Arr::path($this->emailConfig, 'defaults.sender.email'), 'sender_name' => Arr::path($this->emailConfig, 'defaults.sender.name')];
     $email = $this->emailMapper->getPrototype();
     $email = $email->exchangeArray(array_merge($defaults, $data));
     $email = $this->emailMapper->persist($email);
     return $email;
 }
 /**
  * @param RollbarNotifier  $rollbarNotifier RollbarNotifier object constructed with valid token
  * @param string           $environment
  * @param boolean          $bubble          Whether the messages that are handled can bubble up the stack or not
  */
 public function __construct($config, $environment, $bubble = true)
 {
     $token = Arr::get($config, 'post_server_item_access_token');
     if (!$token) {
         throw new ConfigException('Rollbar is enabled but the post server item access token is not set.');
     }
     $this->rollbarNotifier = new RollbarNotifier(['access_token' => $token, 'environment' => $environment, 'batched' => false, 'root' => Arr::get($config, 'root')]);
     $level = Arr::path($config, 'level') ?: Logger::ERROR;
     parent::__construct($level, $bubble);
 }
 /**
  * Return the whitelist trap address with the specified email injected as a suffix
  *
  * Example:
  *     Email to transform : smith@email.com
  *     Trap email         : foo@bar.com
  *     Result             : foo+smith+email.com@bar.com
  *
  * @param  string $address Email address to transform
  * @return string          Transformed address
  */
 protected function injectIntoTrapAddress($address)
 {
     $trapAddress = Arr::path($this->config, 'whitelist.trap');
     if (!$trapAddress) {
         throw new RuntimeException('Email address not whitelisted but no email trap exists');
     }
     $address = str_ireplace('@', '+', $address);
     list($trapName, $trapDomain) = explode('@', $trapAddress);
     return sprintf('%s+%s@%s', $trapName, $address, $trapDomain);
 }
 public function setUpMockUrlGenerator()
 {
     $captured = $this->captured;
     $this->mockUrlGenerator = $this->getMock('Symfony\\Component\\Routing\\Generator\\UrlGeneratorInterface');
     $this->mockUrlGenerator->expects($this->any())->method('generate')->will($this->returnCallback(function ($name, $params, $refType) use($captured) {
         $generatedUrl = '/users/' . Arr::get($params, 'id');
         $captured->generatedUrl = $generatedUrl;
         return $generatedUrl;
     }));
     $this->captured = $captured;
 }
 public function register(Application $app)
 {
     $app['css-to-inline'] = $app->share(function ($app) {
         return new CssToInlineStyles();
     });
     $app['handlebars'] = $app->share(function ($app) {
         $emailConfig = $app['config']->load('template');
         $templatePath = Arr::path($emailConfig, 'handlebars.path', APPDIR . '/templates');
         return new Handlebars(['loader' => new FilesystemLoader($templatePath, ['extension' => '.hbs']), 'partials_loader' => new FilesystemLoader($templatePath, ['prefix' => '_'])]);
     });
     $app['template.service'] = $app->share(function ($app) {
         return new TemplateService($app['handlebars'], $app['css-to-inline']);
     });
 }
 /**
  * Create an email entity from an array and populate with default data
  *
  * @param  array  $data Data to populate the email
  * @return Email
  */
 public function createFromArray(array $data)
 {
     $headers = json_encode(Arr::path($this->emailConfig, 'defaults.headers', []));
     if (isset($data['sender_localpart'])) {
         if (!Arr::path($this->emailConfig, 'defaults.sender.domain')) {
             throw new \Exception('defaults.sender.domain not set in email config');
         }
         $data['sender_email'] = Arr::remove($data, 'sender_localpart') . '@' . Arr::path($this->emailConfig, 'defaults.sender.domain');
     }
     $defaults = ['headers' => $headers, 'sender_email' => Arr::path($this->emailConfig, 'defaults.sender.email'), 'sender_name' => Arr::path($this->emailConfig, 'defaults.sender.name')];
     $email = $this->emailMapper->getPrototype();
     $email = $email->exchangeArray(array_merge($defaults, $data));
     $email = $this->emailMapper->persist($email);
     return $email;
 }
 /**
  * Verify user registration with token and user id
  *
  * @param  Request $request
  * @return array
  */
 public function post(Request $request)
 {
     $id = $request->attributes->get('id');
     $token = Arr::get($this->getContentAsArray($request), 'token');
     if (!$token) {
         return $this->createSimpleResponse(422, 'Token not specified.');
     }
     $conditions = ['user_id' => $id, 'token' => $token, 'token_type_id' => TokenEntity::TYPE_VERIFY_REGISTRATION];
     $token = $this->userService->findTokenBy($conditions);
     if (!$token) {
         return $this->createNotFoundResponse();
     }
     try {
         $user = $this->userService->verifyRegistration($token);
     } catch (OutOfBoundsException $e) {
         $httpCodes = [UserService::INCORRECT_TOKEN_TYPE => 422, UserService::TOKEN_EXPIRED => 410, UserService::TOKEN_NOT_FOUND => 404];
         return $this->createErrorResponse(['token' => ['INVALID']], $httpCodes[$e->getCode()]);
     }
     $user = $user->getArrayCopy();
     unset($user['password']);
     return $user;
 }
 /**
  * Reset password using token and new password
  *
  * @param  Request $request
  * @return array
  */
 public function put(Request $request)
 {
     $token = Arr::get($this->getContentAsArray($request), 'token');
     // Ensure token is valid
     $token = $this->userService->findTokenBy(['token' => $token, 'token_type_id' => TokenEntity::TYPE_RESET_PASSWORD]);
     if (!$token) {
         return $this->createNotFoundResponse();
     }
     if ($token->getExpires() < time()) {
         return $this->createNotFoundResponse();
     }
     $user = $this->userService->findById($token->getUserId());
     if (!$user) {
         return $this->createNotFoundResponse();
     }
     $password = Arr::get($this->getContentAsArray($request), 'password');
     // Ensure user input is valid
     if (!$password) {
         return $this->createErrorResponse(['password' => ['EMPTY']], 422);
     }
     $this->userService->resetPassword($user, $password);
     $this->userService->deleteToken($token);
     return $this->userArrayWithoutPassword($user);
 }
 /**
  * Handle logout request
  *
  * @param  Request $request
  * @return Response
  */
 public function logout(Request $request)
 {
     $content = json_decode($request->getContent(), true);
     $securityToken = $this->security->getToken();
     $user = $securityToken->getUser();
     $accessToken = $securityToken->getOAuthToken();
     $refreshToken = Arr::get($content, 'refresh_token');
     $this->session->set('user', null);
     if (!$refreshToken) {
         return new Response('Refresh token not provided', 422);
     }
     try {
         $this->expireAccessToken($accessToken);
         $this->expireRefreshToken($refreshToken, $user);
     } catch (OutOfBoundsException $e) {
         return new Response($e->getMessage(), 422);
     }
     return new Response('', 200);
 }
 /**
  * Get values which are saved to the database
  *
  * Useful if as_array is overridden to return values not
  * saved to the database.
  *
  * @return array
  */
 public function getDbValues()
 {
     return Arr::extract($this->getArrayCopy(), $this->getColumns());
 }
 /**
  * Get the query parameters given for the SQL query provided
  *
  * @param  integer $key Key of the SQL query run (0 = the first query run, 1 = the second, etc)
  * @return array|null   List of parameters or null if none found
  */
 protected function getQueryParams($key = 0)
 {
     return Arr::get($this->queryParameters, $key);
 }
 /**
  * Export database data to dbData install file
  *
  * @param  string $outputPath Path where file should be exported
  */
 protected function dumpData($outputPath)
 {
     $tables = Arr::get($this->installConfig, 'dataTables', []);
     /**
      *  Do not attempt to create an empty data install file if no tables are to be exported.
      *  Otherwise all tables will be exported.
      */
     if (!count($tables)) {
         return;
     }
     $command = sprintf('mysqldump %s %s -u %s -p%s --no-create-info > %s', escapeshellarg($this->dbConfig['database']), implode(' ', $tables), escapeshellarg($this->dbConfig['username']), escapeshellarg($this->dbConfig['password']), escapeshellarg($outputPath . '/' . self::DATA_FILE));
     return shell_exec($command);
 }
Exemple #19
0
 /**
  * Initialize Resque
  *
  * @param array $config
  */
 public function __construct($config = [])
 {
     ResqueLib::setBackend(Arr::get($config, 'host'));
 }
Exemple #20
0
 /**
  * Convert a multi-dimensional array into a single-dimensional array.
  *
  *     $array = array('set' => array('one' => 'something'), 'two' => 'other');
  *
  *     // Flatten the array
  *     $array = Arr::flatten($array);
  *
  *     // The array will now be
  *     array('one' => 'something', 'two' => 'other');
  *
  * [!!] The keys of array values will be discarded.
  *
  * @param  array $array array to flatten
  * @return array
  *                     @since   3.0.6
  */
 public static function flatten($array)
 {
     $is_assoc = Arr::isAssoc($array);
     $flat = [];
     foreach ($array as $key => $value) {
         if (is_array($value)) {
             $flat = array_merge($flat, Arr::flatten($value));
         } else {
             if ($is_assoc) {
                 $flat[$key] = $value;
             } else {
                 $flat[] = $value;
             }
         }
     }
     return $flat;
 }
Exemple #21
0
 /**
  *
  * @test
  * @dataProvider providerFlatten
  */
 public function testFlatten($source, $expected)
 {
     $this->assertSame($expected, Arr::flatten($source));
 }
Exemple #22
0
 /**
  * Get the count of results from a given query
  *
  * @param  Select $query
  * @return int
  */
 protected function getQueryResultCount(Select $query)
 {
     $queryString = $this->getSqlObject()->getSqlStringForSqlObject($query, $this->dbAdapter->getPlatform());
     $format = 'Select count(*) as `count` from (%s) as `query_count`';
     $countQueryString = sprintf($format, $queryString);
     $countQuery = $this->dbAdapter->query($countQueryString);
     $result = $countQuery->execute()->current();
     return (int) Arr::get($result, 'count');
 }
 /**
  * Register log handler for Rollbar
  *
  * @return RollbarHandler
  */
 protected function getRollbarHandler($environment)
 {
     $rollbarConfig = Arr::get($this->config, 'rollbar', []);
     return new RollbarHandler($rollbarConfig, $environment);
 }
 /**
  * Find roles for a user by user ID
  *
  * @param  string $userId
  * @return array  Array of role names
  */
 public function findRoleNamesByUserId($userId)
 {
     $query = $this->getSqlObject()->select()->join('user_roles', 'user_roles.id = pvt_roles_users.role_id', ['name'])->where(['user_id' => $userId]);
     $results = $this->execute($query)->toArray();
     return Arr::pluck($results, 'name');
 }
 public function testPutReturns200AndUserEntityWithPasswordRemoved()
 {
     $this->withUserServiceFindTokenByReturningToken();
     $this->withUserServiceFindByIdReturningUser();
     $response = $this->performPutRequest();
     $this->assertEquals(200, $response->getStatusCode());
     $responseBody = json_decode($response->getContent(), true);
     $this->assertEquals(null, Arr::get($responseBody, 'content'));
 }