Пример #1
0
 /**
  * @param Parameters $params
  * @param Builder $queryBuilder
  *
  * @return Builder
  */
 public function createQuery($params, $queryBuilder)
 {
     $this->value = $params->toArray();
     /*
      * search jobs by keywords
      */
     if (isset($this->value['params']['search']) && !empty($this->value['params']['search'])) {
         $search = strtolower($this->value['params']['search']);
         $expression = $queryBuilder->expr()->operator('$text', ['$search' => $search]);
         $queryBuilder->field(null)->equals($expression->getQuery());
     }
     if (isset($this->value['params']['status']) && !empty($this->value['params']['status'])) {
         if ($this->value['params']['status'] != 'all') {
             $queryBuilder->field('status.name')->equals($this->value['params']['status']);
         }
     } else {
         $queryBuilder->field('status.name')->equals(Status::CREATED);
     }
     if (isset($this->value['params']['companyId']) && !empty($this->value['params']['companyId'])) {
         $queryBuilder->field('organization')->equals(new \MongoId($this->value['params']['companyId']));
     }
     if (isset($this->value['sort'])) {
         foreach (explode(",", $this->value['sort']) as $sort) {
             $queryBuilder->sort($this->filterSort($sort));
         }
     }
     return $queryBuilder;
 }
Пример #2
0
 /**
  * getSuggestions
  *
  * This returns an array of suggestions based on current request parameters.
  * This logic is present in the factory class so that it can be easily shared
  * by multiple AJAX handlers.
  *
  * @param \Zend\Stdlib\Parameters $request    The user request
  * @param string                  $typeParam  Request parameter containing search
  * type
  * @param string                  $queryParam Request parameter containing query
  * string
  *
  * @return array
  */
 public function getSuggestions($request, $typeParam = 'type', $queryParam = 'q')
 {
     // Process incoming parameters:
     $type = $request->get($typeParam, '');
     $query = $request->get($queryParam, '');
     // get Autocomplete_Type config
     $searcher = $request->get('searcher', 'Solr');
     $options = $this->getServiceLocator()->get('SearchManager')->setSearchClassId($searcher)->getOptionsInstance();
     $config = ConfigReader::getConfig($options->getSearchIni());
     $types = isset($config->Autocomplete_Types) ? $config->Autocomplete_Types->toArray() : array();
     // Figure out which handler to use:
     if (!empty($type) && isset($types[$type])) {
         $module = $types[$type];
     } else {
         if (isset($config->Autocomplete->default_handler)) {
             $module = $config->Autocomplete->default_handler;
         } else {
             $module = false;
         }
     }
     // Get suggestions:
     if ($module) {
         if (strpos($module, ':') === false) {
             $module .= ':';
             // force colon to avoid warning in explode below
         }
         list($name, $params) = explode(':', $module, 2);
         $handler = $this->get($name);
         $handler->setConfig($params);
     }
     return isset($handler) && is_object($handler) ? array_values($handler->getSuggestions($query)) : array();
 }
Пример #3
0
 /**
  *  Test with project path set
  */
 public function testWithProjectPathSet()
 {
     $this->console->expects($this->never())->method('writeFailLine')->with($this->equalTo('task_check_working_path_mandatory'));
     $this->parameters->set('workingPath', '/path/to/project/');
     $task = new ProjectPathMandatory();
     $result = $task($this->route, $this->console, $this->parameters);
     $this->assertEquals(0, $result);
 }
Пример #4
0
 /**
  * Initialize the object's search settings from a request object.
  *
  * @param \Zend\StdLib\Parameters $request Parameter object representing user
  * request.
  *
  * @return void
  */
 protected function initSearch($request)
 {
     // Convert special 'id' parameter into a standard hidden filter:
     $idParam = $request->get('id', []);
     if (!empty($idParam)) {
         $this->addHiddenFilter('ids:' . implode("\t", $idParam));
     }
 }
Пример #5
0
 /**
  * @param UploaderModelInterface $model
  * @param null $values
  * @return string
  * @throws InvalidArgumentException
  */
 public function render($model, $values = null)
 {
     if (!$model instanceof UploaderModelInterface) {
         throw new InvalidArgumentException("Unsupportable type of model, required type UploaderModelInterface");
     }
     $resources = $model->getResourcePaths();
     $url = array_pop($resources);
     $funcNum = $this->params->get('CKEditorFuncNum', 0);
     return "<script type='text/javascript'>\n                    window.parent.CKEDITOR.tools.callFunction({$funcNum}, '" . $url . "', '');\n                </script>";
 }
Пример #6
0
 /**
  * Add filters to the object based on values found in the request object.
  *
  * @param \Zend\StdLib\Parameters $request Parameter object representing user
  * request.
  *
  * @return void
  */
 protected function initFilters($request)
 {
     // Special filter -- if the "id" parameter is set, limit to a specific list:
     $id = $request->get('id');
     if (!empty($id)) {
         $this->addFilter("lists:{$id}");
     }
     // Otherwise use standard parent behavior:
     return parent::initFilters($request);
 }
Пример #7
0
 /**
  * @param $request
  * @return array|mixed|User
  * @throws \Exception
  */
 public function login($request)
 {
     $adapter = $this->getAuthPlugin()->getAuthAdapter();
     $pin = $request->get('pin');
     $accountId = $request->get('accountId');
     if (!empty($pin)) {
         $user = $this->getUserByPin($pin, $accountId);
         $credentials = array('username' => $user->getUsername(), 'password' => $user->getPassword());
     } else {
         $credentials = array('username' => $request->get('username'), 'password' => $request->get('password'));
     }
     $params = new Parameters();
     $params->set('identity', $credentials['username']);
     $params->set('credential', $credentials['password']);
     $emulatedRequest = new Request();
     $emulatedRequest->setPost($params);
     $result = $adapter->prepareForAuthentication($emulatedRequest);
     if ($result instanceof Response) {
         return $result;
     }
     $auth = $this->getAuthPlugin()->getAuthService()->authenticate($adapter);
     if (!$auth->isValid()) {
         $isRegistered = $this->isRegistered($credentials);
         $accountUser = $this->getAccountUsersByParams($params);
         if ($accountUser != null && !$isRegistered) {
             if ($this->getAgencyIsDeleted($accountUser->getAccountId())) {
                 throw new \Exception(self::AGENCY_DELETED_MESSAGE);
             }
             return $this->createUserFromAccountUsers($accountUser);
         }
         $account = $this->getAccountByParams($params);
         if ($account != null && !$isRegistered) {
             return $this->createUserFromAccount($account);
         }
         if ($accountUser != null && $isRegistered) {
             return $this->updateUser($accountUser);
         }
         $result = $auth->getMessages();
         $message = "Bad request.";
         if (isset($result[0])) {
             $message = $result[0];
         }
         throw new \Exception($message);
     }
     $accountUser = $this->getAccountUsersByParams($params);
     if ($this->getAgencyIsDeleted($accountUser->getAccountId())) {
         throw new \Exception(self::AGENCY_DELETED_MESSAGE);
     }
     if ($this->getUserIsDeleted($credentials['username'])) {
         throw new \Exception(self::USER_DELETED_MESSAGE);
     }
     $user = $this->getAuthPlugin()->getIdentity();
     return $user;
 }
Пример #8
0
 /**
  * Support method for _initSearch() -- handle basic settings.
  *
  * @param \Zend\StdLib\Parameters $request Parameter object representing user
  * request.
  *
  * @return boolean True if search settings were found, false if not.
  */
 protected function initBasicSearch($request)
 {
     // If no lookfor parameter was found, we have no search terms to
     // add to our array!
     if (is_null($lookfor = $request->get('lookfor'))) {
         return false;
     }
     // Set the search (handler is always Author for this module):
     $this->setBasicSearch($lookfor, 'Author');
     return true;
 }
Пример #9
0
 /**
  * init
  *
  * Called at the end of the Search Params objects' initFromRequest() method.
  * This method is responsible for setting search parameters needed by the
  * recommendation module and for reading any existing search parameters that may
  * be needed.
  *
  * @param \VuFind\Search\Base\Params $params  Search parameter object
  * @param \Zend\StdLib\Parameters    $request Parameter object representing user
  * request.
  *
  * @return void
  */
 public function init($params, $request)
 {
     // Build a search parameters object:
     $sm = $this->getSearchManager()->setSearchClassId($this->getSearchClassId());
     $params = $sm->getParams();
     $params->setLimit($this->limit);
     $params->setBasicSearch($request->get($this->requestParam));
     // Perform the search:
     $this->results = $sm->setSearchClassId($this->getSearchClassId())->getResults($params);
     $this->results->performAndProcessSearch();
 }
 public function testPagesActionCanBeAccessedByPost()
 {
     $this->routeMatch->setParam('action', 'pages');
     $this->request->setMethod('POST');
     $p = new Parameters();
     $p->set('role_id', '1');
     $this->request->setPost($p);
     $result = $this->controller->dispatch($this->request);
     $response = $this->controller->getResponse();
     $this->assertInstanceOf('Zend\\Http\\Response', $result);
     $this->assertEquals(302, $response->getStatusCode());
 }
Пример #11
0
 /**
  *  Test with controller existing
  */
 public function testWithKnownHydrators()
 {
     $this->console->expects($this->never())->method('writeFailLine')->with($this->equalTo('task_check_base_hydrator_param_unknown'));
     $this->console->expects($this->never())->method('colorize');
     $knownHydrators = ['ArraySerializable', 'ClassMethods', 'ObjectProperty', 'Reflection'];
     foreach ($knownHydrators as $hydrator) {
         $this->parameters->set('paramBaseHydrator', $hydrator);
         $task = new BaseHydratorParam();
         $result = $task($this->route, $this->console, $this->parameters);
         $this->assertEquals(0, $result);
     }
 }
Пример #12
0
 /**
  * Support method for _initSearch() -- handle basic settings.
  *
  * @param \Zend\StdLib\Parameters $request Parameter object representing user
  * request.
  *
  * @return boolean True if search settings were found, false if not.
  */
 protected function initBasicSearch($request)
 {
     // If no lookfor parameter was found, we have no search terms to
     // add to our array!
     if (is_null($lookfor = $request->get('author'))) {
         return false;
     }
     // Force the search to be a phrase:
     $lookfor = '"' . str_replace('"', '\\"', $lookfor) . '"';
     // Set the search (handler is always Author for this module):
     $this->setBasicSearch($lookfor, 'Author');
     return true;
 }
 public function testRunActionWithParams()
 {
     $params = array('strict' => true, 'verbose' => true, 'debug' => true);
     $runner = $this->getMockForAbstractClass('HumusPHPUnitModule\\RunnerInterface');
     $runner->expects($this->once())->method('setParams')->with($params);
     $runner->expects($this->once())->method('run');
     $params = new Parameters();
     $params->set('strict', true);
     $params->set('verbose', true);
     $params->set('debug', true);
     $this->request->setParams($params);
     $this->controller->setRunner($runner);
     $response = new Response();
     $this->controller->dispatch($this->request, $response);
 }
 /**
  * @return Http\Client
  */
 public function getHttpClient()
 {
     if (!$this->httpClient instanceof Http\Client) {
         $this->httpClient = $this->getHttpClientFactory()->createHttpClient($this->options->get(self::OPT_HTTP_CLIENT, array()));
     }
     return $this->httpClient;
 }
Пример #15
0
 /**
  * @param ServerRequestInterface $request
  * @param ResponseInterface      $response
  *
  * @return HtmlResponse|RedirectResponse
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response)
 {
     try {
         $album = (array) $this->albumService->getAlbum($request->getAttribute('id'));
     } catch (\Exception $e) {
         return new HtmlResponse($this->template->render('error::404'), 404);
     }
     if ($request->getMethod() === 'POST') {
         $body = new Parameters($request->getParsedBody());
         $del = $body->get('del', 'No');
         if (strtolower($del) === 'yes') {
             $this->albumService->deleteAlbum($album);
         }
         return new RedirectResponse($this->router->generateUri('album.index'));
     }
     return new HtmlResponse($this->template->render('album::delete', ['album' => $album]));
 }
 /**
  * @param Parameters $params
  *
  * @return Parameters
  */
 protected function initDefaults(Parameters $params)
 {
     if (is_null($params->get('quality')) || !strlen(trim($params->get('quality')))) {
         $params->set('quality', QualityInterface::QUALITY_THUMBNAIL);
     }
     if (is_null($params->get('source')) || !strlen(trim($params->get('source')))) {
         $params->set('source', SourceNameInterface::SOURCE_USER);
     }
     return $params;
 }
Пример #17
0
 /**
  *  Test with module path existing
  */
 public function testWithModulePathExisting()
 {
     $this->console->expects($this->never())->method('writeFailLine')->with($this->equalTo('task_check_working_path_not_exists'));
     $this->console->expects($this->never())->method('colorize');
     $this->parameters->set('projectModuleDir', $this->zf2rapidModuleDir);
     $task = new ModulePathExists();
     $result = $task($this->route, $this->console, $this->parameters);
     $this->assertEquals(0, $result);
 }
Пример #18
0
 /**
  * This returns an array of suggestions based on current request parameters.
  * This logic is present in the factory class so that it can be easily shared
  * by multiple AJAX handlers.
  *
  * @param \Zend\Stdlib\Parameters $request    The user request
  * @param string                  $typeParam  Request parameter containing search
  * type
  * @param string                  $queryParam Request parameter containing query
  * string
  *
  * @return array
  */
 public function getSuggestions($request, $typeParam = 'type', $queryParam = 'q')
 {
     // Process incoming parameters:
     $type = $request->get($typeParam, '');
     $query = $request->get($queryParam, '');
     $searcher = $request->get('searcher', 'Solr');
     $hiddenFilters = $request->get('hiddenFilters', []);
     // If we're using a combined search box, we need to override the searcher
     // and type settings.
     if (substr($type, 0, 7) == 'VuFind:') {
         list(, $tmp) = explode(':', $type, 2);
         list($searcher, $type) = explode('|', $tmp, 2);
     }
     // get Autocomplete_Type config
     $options = $this->getServiceLocator()->get('VuFind\\SearchOptionsPluginManager')->get($searcher);
     $config = $this->getServiceLocator()->get('VuFind\\Config')->get($options->getSearchIni());
     $types = isset($config->Autocomplete_Types) ? $config->Autocomplete_Types->toArray() : [];
     // Figure out which handler to use:
     if (!empty($type) && isset($types[$type])) {
         $module = $types[$type];
     } else {
         if (isset($config->Autocomplete->default_handler)) {
             $module = $config->Autocomplete->default_handler;
         } else {
             $module = false;
         }
     }
     // Get suggestions:
     if ($module) {
         if (strpos($module, ':') === false) {
             $module .= ':';
             // force colon to avoid warning in explode below
         }
         list($name, $params) = explode(':', $module, 2);
         $handler = $this->get($name);
         $handler->setConfig($params);
     }
     if (is_callable([$handler, 'addFilters'])) {
         $handler->addFilters($hiddenFilters);
     }
     return isset($handler) && is_object($handler) ? array_values($handler->getSuggestions($query)) : [];
 }
 /**
  *  Test with controller plugin existing
  */
 public function testWithControllerPluginExisting()
 {
     $this->console->expects($this->once())->method('writeTaskLine')->with($this->equalTo('task_check_checking_file'), ['controller plugin']);
     $this->console->expects($this->never())->method('writeFailLine')->with($this->equalTo('task_check_file_exists_not_found'));
     $this->console->expects($this->never())->method('colorize');
     $this->parameters->set('controllerPluginDir', $this->zf2rapidControllerPluginDir);
     $this->parameters->set('paramControllerPlugin', $this->zf2rapidControllerPluginName);
     file_put_contents($this->zf2rapidControllerPluginDir . $this->zf2rapidControllerPluginFile, 'class TestPlugin {}');
     $task = new ControllerPluginExists();
     $result = $task($this->route, $this->console, $this->parameters);
     $this->assertEquals(0, $result);
 }
 /**
  * Sends the HTTP request and returns the response.
  * 
  * @param Http\Request $httpRequest
  * @throws HttpClientException
  * @return Http\Response
  */
 public function sendHttpRequest(Http\Request $httpRequest)
 {
     $this->setLastHttpRequest($httpRequest);
     $this->httpClient->setOptions($this->options->get(self::OPT_HTTP_OPTIONS, array()));
     try {
         $httpResponse = $this->httpClient->send($httpRequest);
     } catch (\Exception $e) {
         throw new HttpClientException(sprintf("Exception during HTTP request: [%s] %s", get_class($e), $e->getMessage()));
     }
     $this->setLastHttpResponse($httpResponse);
     return $httpResponse;
 }
Пример #21
0
 /**
  *  Test with form existing
  */
 public function testWithFormExisting()
 {
     $this->console->expects($this->once())->method('writeTaskLine')->with($this->equalTo('task_check_checking_file'), ['form']);
     $this->console->expects($this->never())->method('writeFailLine')->with($this->equalTo('task_check_file_exists_not_found'));
     $this->console->expects($this->never())->method('colorize');
     $this->parameters->set('formDir', $this->zf2rapidFormDir);
     $this->parameters->set('paramForm', $this->zf2rapidFormName);
     file_put_contents($this->zf2rapidFormDir . $this->zf2rapidFormFile, 'class TestForm {}');
     $task = new FormExists();
     $result = $task($this->route, $this->console, $this->parameters);
     $this->assertEquals(0, $result);
 }
Пример #22
0
 /**
  *  Test with validator existing
  */
 public function testWithValidatorExisting()
 {
     $this->console->expects($this->once())->method('writeTaskLine')->with($this->equalTo('task_check_checking_file'), array('validator'));
     $this->console->expects($this->never())->method('writeFailLine')->with($this->equalTo('task_check_file_exists_not_found'));
     $this->console->expects($this->never())->method('colorize');
     $this->parameters->set('validatorDir', $this->zf2rapidValidatorDir);
     $this->parameters->set('paramValidator', $this->zf2rapidValidatorName);
     file_put_contents($this->zf2rapidValidatorDir . $this->zf2rapidValidatorFile, 'class TestValidator {}');
     $task = new ValidatorExists();
     $result = $task($this->route, $this->console, $this->parameters);
     $this->assertEquals(0, $result);
 }
Пример #23
0
 /**
  *  Test with existing file
  */
 public function testWithExistingFile()
 {
     $this->parameters->set('workingPath', $this->zf2rapidFileDir);
     $expectedConfig = array('foo' => 'bar', 'one' => 'two');
     file_put_contents($this->zf2rapidFileDir . $this->zf2rapidFileName, json_encode($expectedConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
     $task = new ConfigFile();
     $result = $task($this->route, $this->console, $this->parameters);
     $this->assertEquals(0, $result);
     $this->assertEquals($expectedConfig, $this->parameters->config);
     $this->assertFileExists($this->zf2rapidFileDir . $this->zf2rapidFileName);
     $this->assertEquals($expectedConfig, json_decode(file_get_contents($this->zf2rapidFileDir . $this->zf2rapidFileName), true));
 }
Пример #24
0
 /**
  * Process renewal requests.
  *
  * @param \Zend\Stdlib\Parameters $request Request object
  * @param \VuFind\ILS\Connection  $catalog ILS connection object
  * @param array                   $patron  Current logged in patron
  *
  * @return array                  The result of the renewal, an
  * associative array keyed by item ID (empty if no renewals performed)
  */
 public function processRenewals($request, $catalog, $patron)
 {
     // Pick IDs to renew based on which button was pressed:
     $all = $request->get('renewAll');
     $selected = $request->get('renewSelected');
     if (!empty($all)) {
         $ids = $request->get('renewAllIDS');
     } else {
         if (!empty($selected)) {
             $ids = $request->get('renewSelectedIDS');
         } else {
             $ids = [];
         }
     }
     // Retrieve the flashMessenger helper:
     $flashMsg = $this->getController()->flashMessenger();
     // If there is actually something to renew, attempt the renewal action:
     if (is_array($ids) && !empty($ids)) {
         $renewResult = $catalog->renewMyItems(['details' => $ids, 'patron' => $patron]);
         if ($renewResult !== false) {
             // Assign Blocks to the Template
             if (isset($renewResult['blocks']) && is_array($renewResult['blocks'])) {
                 foreach ($renewResult['blocks'] as $block) {
                     $flashMsg->setNamespace('info')->addMessage($block);
                 }
             }
             // Send back result details:
             return $renewResult['details'];
         } else {
             // System failure:
             $flashMsg->setNamespace('error')->addMessage('renew_error');
         }
     } else {
         if (!empty($all) || !empty($selected)) {
             // Button was clicked but no items were selected:
             $flashMsg->setNamespace('error')->addMessage('renew_empty_selection');
         }
     }
     return [];
 }
Пример #25
0
 /**
  *  Test hydrator param
  */
 public function testHydratorParam()
 {
     $this->parameters->set('moduleSrcDir', '/path/to/module/dir/testModule/src');
     $this->parameters->set('config', ['namespaceHydrator' => 'Model\\Hydrator']);
     $paramValueMap = [['hydrator', null, 'HydratorName'], ['baseHydrator', null, 'BaseHydrator']];
     $this->route->method('getMatchedParam')->will($this->returnValueMap($paramValueMap));
     $task = new Params();
     $result = $task($this->route, $this->console, $this->parameters);
     $this->assertEquals(0, $result);
     $this->assertEquals('HydratorName', $this->parameters->paramHydrator);
     $this->assertEquals('BaseHydrator', $this->parameters->paramBaseHydrator);
     $this->assertEquals('/path/to/module/dir/testModule/src/Model/Hydrator', $this->parameters->hydratorDir);
 }
Пример #26
0
 /**
  *  Test with existing file
  */
 public function testWithExistingFile()
 {
     $this->parameters->set('workingPath', $this->zf2rapidFileDir);
     $setupConfig = ['foo' => 'bar', 'one' => 'two'];
     file_put_contents($this->zf2rapidFileDir . $this->zf2rapidFileName, json_encode($setupConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
     $expectedConfig = array_merge($setupConfig, ['configFileFormat' => 'php', 'flagAddDocBlocks' => 'true', 'fileDocBlockText' => 'ZF2 Application built by ZF2rapid', 'fileDocBlockCopyright' => '(c) 2015 John Doe', 'fileDocBlockLicense' => 'http://opensource.org/licenses/MIT The MIT License (MIT)', 'namespaceController' => 'Controller', 'namespaceControllerPlugin' => 'Controller\\Plugin', 'namespaceViewHelper' => 'View\\Helper', 'namespaceFilter' => 'Filter', 'namespaceValidator' => 'Validator', 'namespaceInputFilter' => 'InputFilter', 'namespaceForm' => 'Form', 'namespaceHydrator' => 'Hydrator', 'namespaceEntity' => 'Entity', 'namespaceTableGateway' => 'TableGateway', 'namespaceStorage' => 'Storage', 'namespaceRepository' => 'Repository']);
     $task = new ConfigFile();
     $result = $task($this->route, $this->console, $this->parameters);
     $this->assertEquals(0, $result);
     $this->assertEquals($expectedConfig, $this->parameters->config);
     $this->assertFileExists($this->zf2rapidFileDir . $this->zf2rapidFileName);
     $this->assertEquals($expectedConfig, json_decode(file_get_contents($this->zf2rapidFileDir . $this->zf2rapidFileName), true));
 }
Пример #27
0
 public function handleSort(Manager $manager, Parameters $request, $defaultSort, $target)
 {
     $user = $manager->isLoggedIn();
     $requestParams = $request->toArray();
     if ($user) {
         //in case user changed the the sort settings on the result list with a specialized UI control
         //we want to serialize the new value in database
         if (array_key_exists('sortControlElement', $requestParams)) {
             if (array_key_exists('sort', $requestParams)) {
                 $sort = $requestParams['sort'];
                 $dbSort = unserialize($user->default_sort);
                 $dbSort[$target] = $requestParams['sort'];
                 $user->default_sort = serialize($dbSort);
                 $user->save();
             } else {
                 $tSort = $request->get('sort');
                 $sort = !empty($tSort) ? $tSort : $defaultSort;
             }
         } else {
             $tSort = $request->get('sort');
             $sort = !empty($tSort) ? $tSort : $defaultSort;
             //overwrite sort if value is set in database
             if ($user->default_sort) {
                 $userDefaultSort = unserialize($user->default_sort);
                 if (isset($userDefaultSort[$target])) {
                     $sort = $userDefaultSort[$target];
                 }
             }
         }
     } else {
         $sort = $request->get('sort');
     }
     // Check for special parameter only relevant in RSS mode:
     if ($request->get('skip_rss_sort', 'unset') != 'unset') {
         $this->skipRssSort = true;
     }
     return $sort;
 }
Пример #28
0
 /**
  * @param ServerRequestInterface $request
  * @param ResponseInterface $response
  * @return ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response)
 {
     try {
         $album = $this->albumService->getAlbum($request->getAttribute('id'));
         if ($request->getMethod() === 'POST') {
             $body = new Parameters($request->getParsedBody());
             $del = $body->get('del', 'No');
             if (strtolower($del) === 'yes') {
                 $this->albumService->deleteAlbum($album);
                 /**
                  * @var Session $session
                  */
                 $session = $request->getAttribute('session');
                 $session->getSegment('App\\Album')->setFlash('flash', ['type' => 'success', 'message' => sprintf('Successfully deleted album %s (%s)', $album->getTitle(), $album->getArtist())]);
             }
             // Redirect to list of albums
             return new RedirectResponse($this->router->generateUri('album.index'));
         }
     } catch (\Exception $e) {
         // do something useful
     }
     return new HtmlResponse($this->template->render('album::delete', compact('album')));
 }
Пример #29
0
 /**
  *  Test with module dir creating succeed
  */
 public function testWithModuleDirCreatingSucceed()
 {
     $this->console->expects($this->once())->method('writeTaskLine')->with($this->equalTo('task_create_structure_module_root_created'));
     $this->console->expects($this->once())->method('colorize');
     $this->parameters->set('moduleDir', $this->zf2rapidModuleDir);
     $this->parameters->set('moduleConfigDir', $this->zf2rapidModuleDir . 'config/');
     $this->parameters->set('moduleSrcDir', $this->zf2rapidModuleDir . 'src/');
     $this->parameters->set('moduleViewDir', $this->zf2rapidModuleDir . 'view/');
     $task = new CreateModuleStructure();
     $result = $task($this->route, $this->console, $this->parameters);
     $this->assertEquals(0, $result);
     $this->assertFileExists($this->zf2rapidModuleDir);
     $this->assertFileExists($this->zf2rapidModuleDir . 'config/');
     $this->assertFileExists($this->zf2rapidModuleDir . 'src/');
     $this->assertFileExists($this->zf2rapidModuleDir . 'view/');
 }
 public function testSaveWithException()
 {
     $scope = 'sadfa';
     $scopeId = 0;
     $this->redirectFactory->expects($this->once())->method('create')->willReturn($this->redirect);
     $this->request->expects($this->exactly(2))->method('getParam')->withConsecutive(['scope'], ['scope_id'])->willReturnOnConsecutiveCalls($scope, $scopeId);
     $this->request->expects($this->once())->method('getParams')->willReturn(['header_default_title' => 'Default title']);
     $this->request->expects($this->once())->method('getFiles')->willReturn($this->fileParams);
     $this->fileParams->expects($this->once())->method('toArray')->willReturn(['header_logo' => ['tmp_name' => '', 'error' => 4]]);
     $this->configFactory->expects($this->once())->method('create')->with($scope, $scopeId, ['header_default_title' => 'Default title'])->willReturn($this->designConfig);
     $exception = new \Exception(__('Exception message'));
     $this->designConfigRepository->expects($this->once())->method('save')->with($this->designConfig)->willThrowException($exception);
     $this->messageManager->expects($this->once())->method('addException')->with($exception, 'Something went wrong while saving this configuration: Exception message');
     $this->dataPersistor->expects($this->once())->method('set')->with('theme_design_config', ['header_default_title' => 'Default title']);
     $this->redirect->expects($this->once())->method('setPath')->with('theme/design_config/edit', ['scope' => $scope, 'scope_id' => $scopeId]);
     $this->assertSame($this->redirect, $this->controller->execute());
 }