protected function before() { parent::before(); Application::getInstance()->getDispatchedAction($controllerName, $action); if ($action != 'Logout' && $this->authenticationHelper->isLoggedIn()) { $this->redirectToRoute('Store', 'List'); } }
protected function before() { parent::before(); $this->session = Application::getInstance()->getDiContainer()->getSessionRegistry()->getSession('www'); $this->authenticationHelper = new AuthenticationHelper($this->session); if (!$this->authenticationHelper->isLoggedIn() && IndexController::class !== get_class($this)) { $this->redirectToRoute('Index', 'Login'); } }
/** * Called at script shutdown if the shutdown is because of a fatal error. * * @param int $errorLevel The error code {@uses E_*} * @param string $message The error message. * @param string $file The file where the error occured. * @param int $line The line in the file where the error occured. * @param string $errorId The internal ID of the error. */ function handleShutdown($errorLevel, $message, $file, $line, $errorId) { $debugger = Application::getInstance()->getDiContainer()->getDebugger(); if ($debugger) { $debugItem = new ErrorItem($errorLevel, $message, $file, $line, array(), $errorId); $debugger->addItem($debugItem); // In case of Fatal error, the code probably halted, so we have to handle it $debugger->handleShutdown(); } }
public function testInit() { $container = Application::getInstance()->getDiContainer(); $this->assertFalse(isset($container[DiHelper::KEY_DI_HELPER]), 'The DI helper should not be set before the test'); $this->assertFalse(isset($container[DiHelper::KEY_FACTORY]), 'The factory should not be set before the test'); DiHelper::init(); $this->assertTrue(isset($container[DiHelper::KEY_DI_HELPER]), 'The DI helper should be set after the test'); $this->assertTrue(isset($container[DiHelper::KEY_FACTORY]), 'The factory should be set after the test'); $this->assertInstanceOf(DiHelper::class, $container[DiHelper::KEY_DI_HELPER], 'The container returns the wrong class for the DI helper'); $this->assertInstanceOf(Factory::class, $container[DiHelper::KEY_FACTORY], 'The container returns the wrong class for the factory'); }
/** * Returns an authenticated CURL request to the Vend store with the specified path with the passed GET params. * * @param string $path The URI for the request. * @param array $params The GET params for the request as an associative array. * @param bool $skipContentType If TRUE, the Content-Type header will not be set. * * @return CurlHttpRequest */ protected function getAuthenticatedRequestForUri($path, array $params = [], $skipContentType = false) { $url = sprintf('https://%s.vendhq.com/%s%s', $this->domainPrefix, ltrim($path, '/'), empty($params) ? '' : '?' . http_build_query($params)); $request = Application::getInstance()->getDiContainer()->getCurlHttpRequest(); $request->setUrl($url); $request->addHeader('User-Agent: Shoppinpal Vend PHP API v0.1.0'); if (!$skipContentType) { $request->addHeader('Content-Type: application/json'); } $this->authHelper->addAuthorisationHeaderToRequest($request); return $request; }
/** * Renders the output. * * @param float $startTime The unix timestamp of the application start with microseconds. * @param float $runTime The number of seconds with microseconds, the application run for. * @param int $currentMemory The current memory usage in bytes. * @param int $peakMemory The peak memory usage in bytes. * @param array $items 2 dimensional array of the debug items, where the 1st dimension's key is the type. * @param array $serverParams Params of the $_SERVER superglobal. * @param array $postParams Params what received through post method. * @param array $getParams Params what received through get method. * @param array $cookieParams Params what received through cookies. * @param array $sessionParams Data what stored in the session. * * @return void */ public function render($startTime, $runTime, $currentMemory, $peakMemory, array $items, array $serverParams, array $postParams, array $getParams, array $cookieParams, array $sessionParams) { $response = Application::getInstance()->getResponse(); /** @var \YapepBase\Response\HttpResponse $response */ if (!$response instanceof HttpResponse || !in_array($response->getContentType(), array(MimeType::HTML, MimeType::XHTML))) { // This renderer only works for HTTP transport and HTML content type return; } $viewDo = new ViewDo(MimeType::HTML); $viewDo->set(array('startTime' => $startTime, 'runTime' => $runTime, 'peakMemory' => $peakMemory, 'items' => $items, 'serverParams' => $serverParams, 'postParams' => $postParams, 'getParams' => $getParams, 'cookieParams' => $cookieParams, 'sessionParams' => $sessionParams)); $template = new ConsoleDebuggerTemplate($viewDo, 'startTime', 'runTime', 'peakMemory', 'items', 'serverParams', 'postParams', 'getParams', 'cookieParams', 'sessionParams'); $template->render(); }
/** * Runs the command and returns the command output and the separated STDERR in the outgoing parameter. * * Uses the "system.commandOutputHelper.work.path" config, what is describes the directory where the temporary * file pointer will be added. (default => /tmp) * * @param CommandExecutor $command The command executor object. * @param string $stdErr The error messages [Outgoing] * * @return \YapepBase\Shell\CommandOutput The output of the command. * @throws \Exception */ public function runCommandWithStdErr(CommandExecutor $command, &$stdErr) { $dir = Config::getInstance()->get('system.commandOutputHelper.work.path', '/tmp'); $pipePath = tempnam($dir, 'stderr-'); $fileHandler = Application::getInstance()->getDiContainer()->getFileHandler(); try { posix_mkfifo($pipePath, 0755); $command->setOutputRedirection(CommandExecutor::OUTPUT_REDIRECT_STDERR, $pipePath); $result = $command->run(); $stdErr = $fileHandler->getAsString($pipePath); $fileHandler->remove($pipePath); } catch (\Exception $e) { if ($fileHandler->checkIsPathExists($pipePath)) { $fileHandler->remove($pipePath); } throw $e; } return $result; }
/** * Constructor * * @param array $data The file data with the same structure as the default PHP $_FILES array. * * @throws \YapepBase\Exception\ParameterException If the provided data array doesn't have the required structure. */ public function __construct(array $data) { if (!isset($data['name']) || !isset($data['error']) || !isset($data['size']) || empty($data['tmp_name']) && $data['error'] == UPLOAD_ERR_OK) { throw new ParameterException('Invalid array provided. Some required fields are missing'); } $this->filenames = array_values((array) $data['name']); $this->sizes = array_values((array) $data['size']); $this->temporaryFiles = array_values((array) $data['tmp_name']); $this->types = isset($data['type']) ? array_values((array) $data['type']) : array(); $this->errors = array_values((array) $data['error']); $nameCount = count($this->filenames); if ($nameCount != count($this->sizes) || $nameCount != count($this->types)) { // The sizes don't match, so it's an invalid data array throw new ParameterException('Invalid array provided. The size of the keys do not match'); } $fileHandler = Application::getInstance()->getDiContainer()->getFileHandler(); // If the filesize is smaller than 0, we have a file that's bigger than 2GB, repopulate the file sizes. foreach ($this->sizes as $index => $size) { if ($size < 0 && $fileHandler->checkIsPathExists($this->temporaryFiles[$index])) { $this->sizes[$index] = $fileHandler->getSize($this->temporaryFiles[$index]); } } }
/** * Translates the specified string. * * @param string $messageId The string. * @param array $parameters The parameters for the translation. * * @return string */ protected function _($messageId, $parameters = array()) { return Application::getInstance()->getI18nTranslator()->translate($messageId, $parameters); }
/** * Checks if the given controller and action is the same as the actual. * * <b>Warning:</b> If you wan't to use this method on an ErrorPage it can throw an Exception, * because by default the error pages don't have to be set in the routing table. * So to avoid this, you just have to add your error pages into your routing table. * * @param string $controller Name of the controller * @param string $action Name of the action * * @return bool */ public function checkIsCurrentControllerAction($controller, $action) { // Get the current controller and action $currentController = null; $currentAction = null; Application::getInstance()->getDispatchedAction($currentController, $currentAction); return $currentController == $controller && $currentAction == $action; }
function testRedirectToRoute() { $previousLevel = ob_get_level(); $router = new RouterMock(); Application::getInstance()->setRouter($router); $request = new HttpRequest(array(), array(), array(), array('REQUEST_URI' => '/'), array(), array()); $out = new OutputMock(); $response = new HttpResponse($out); $o = new HttpMockController($request, $response); try { $o->testRedirectToRoute(); $this->resetObToLevel($previousLevel); $this->fail('RedirectToRoute test should result in a RedirectException'); } catch (RedirectException $e) { $this->assertEquals(RedirectException::TYPE_EXTERNAL, $e->getCode()); } $response->send(); $this->assertEquals(303, $out->responseCode); $this->assertEquals(array('/?test=test&test2%5B0%5D=test1&test2%5B1%5D=test2#test'), $out->headers['Location']); $this->resetObToLevel($previousLevel); }
protected function tearDown() { Application::setInstance($this->previousApplication); }
/** * Returns a helper by it's name * * @param string $name The name of the Helper class to return. * (Without the namespace and Helper suffix) * @param bool $isController If TRUE a View Helper will be returned, and a Common Helper otherwise * * @return \YapepBase\Helper\HelperAbstract */ protected function getHelper($helperName, $isController = true) { if ($isController) { return Application::getInstance()->getDiContainer()->getHelperForController($helperName); } else { return Application::getInstance()->getDiContainer()->getHelper($helperName); } }
/** * Sends the request and returns the result object. * * @return CurlHttpRequestResult * @throws CurlException */ public function send() { if (empty($this->url)) { throw new CurlException('Trying to send an HTTP request without setting the URL'); } if (!$this->isMethodValid($this->method)) { throw new CurlException('Trying to send an HTTP request with an invalid method: ' . $this->method); } $options = $this->options; $options[CURLOPT_RETURNTRANSFER] = true; $options[CURLOPT_HEADER] = true; $url = $this->url; switch ($this->method) { case self::METHOD_GET: case self::METHOD_HEAD: if ($this->method == self::METHOD_GET) { $options[CURLOPT_HTTPGET] = true; } else { $options[CURLOPT_CUSTOMREQUEST] = $this->method; } $query = empty($this->payloadType) ? null : $this->getProcessedPayload(); if (!empty($query)) { if (!is_string($query)) { throw new CurlException('Non string processed query string received for a ' . $this->method . ' request'); } $urlParts = parse_url($url); if (false === $urlParts || empty($urlParts['scheme']) || empty($urlParts['host'])) { throw new CurlException('Invalid URL: ' . $url); } $urlParts['query'] = empty($urlParts['query']) ? $query : $query . '&' . $urlParts['query']; // Rebuild the URL. If we have pecl_http with http_build_url use it, // otherwise use the PHP implementation. $url = function_exists('http_build_url') ? http_build_url($urlParts) : $this->buildUrl($urlParts); } break; case self::METHOD_POST: default: if ($this->method == self::METHOD_POST) { $options[CURLOPT_POST] = true; } else { $options[CURLOPT_CUSTOMREQUEST] = $this->method; } if (!empty($this->payloadType)) { $payload = $this->getProcessedPayload(); if (!empty($payload)) { $options[CURLOPT_POSTFIELDS] = $payload; } } } if (!empty($this->headers)) { $options[CURLOPT_HTTPHEADER] = array_values($this->headers); } $curl = curl_init($url); if (!empty($this->cookies)) { $cookies = array(); foreach ($this->cookies as $name => $value) { $cookies[] = $name . '=' . $value; } curl_setopt($curl, CURLOPT_COOKIE, implode('; ', $cookies)); } curl_setopt_array($curl, $options); $debugger = $this->debuggerDisabled ? false : Application::getInstance()->getDiContainer()->getDebugger(); // If we have a debugger, we have to log the query $startTime = microtime(true); $result = curl_exec($curl); if ($debugger !== false) { $debugger->addItem(new CurlRequestItem(CurlRequestItem::PROTOCOL_HTTP, $this->method, $this->url, (array) $this->payload, $this->headers, $this->options, microtime(true) - $startTime)); } $error = null; $info = array(); if (false === $result) { $error = curl_error($curl); } else { $info = curl_getinfo($curl); } curl_close($curl); return new CurlHttpRequestResult($result, $info, $error); }
<?php /** * This file is part of YAPEPBase. * * @package YapepBase * @copyright 2011 The YAPEP Project All rights reserved. * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ use YapepBase\Autoloader\SimpleAutoloader; use YapepBase\Autoloader\AutoloaderRegistry; include_once __DIR__ . '/../bootstrap.php'; define('TEST_DIR', __DIR__); \YapepBase\Application::getInstance()->getDiContainer()->getErrorHandlerRegistry()->addErrorHandler(new \YapepBase\ErrorHandler\ExceptionCreatorErrorHandler()); $autoloadDirs = (require realpath(__DIR__ . '/../vendor/composer/autoload_namespaces.php')); // Autoloader setup $autoloader = new SimpleAutoloader(); if (defined('APP_ROOT')) { $autoloader->addClassPath(APP_ROOT . '/class'); } $autoloader->addClassPath(TEST_DIR); foreach ($autoloadDirs as $dir) { $autoloader->addClassPath($dir); } AutoloaderRegistry::getInstance()->addAutoloader($autoloader); unset($autoloader);
/** * Tests data storage in the view DO * * @return void */ public function testViewDoHandling() { $script = new BatchScriptMock(); $script->setToView('test', 'testValue'); $this->assertSame('testValue', Application::getInstance()->getDiContainer()->getViewDo()->get('test'), 'The data stored in the view DO does not match.'); }
/** * Redirects the client to the URL specified by the controller and action. * * @param string $controller The name of the controller. * @param string $action The action of the controller. * @param array $routeParams Associative array containing the route parameters for the URL. * @param array $getParams Associative array containing the GET parameters for the URL. * @param string $anchor The anchor for the URL * @param int $statusCode The status code of the redirect (3XX). * * @return void * * @throws \YapepBase\Exception\RedirectException To stop execution of the controller. * @throws \YapepBase\Exception\RouterException If there was an error creating the URL. */ protected function redirectToRoute($controller, $action, $routeParams = array(), $getParams = array(), $anchor = '', $statusCode = 303) { $url = Application::getInstance()->getRouter()->getTargetForControllerAction($controller, $action, $routeParams); if (!empty($getParams)) { $url .= '?' . \http_build_query($getParams, null, '&'); } if (!empty($anchor)) { $url .= '#' . $anchor; } $this->redirectToUrl($url, $statusCode); // @codeCoverageIgnoreStart }
/** * Deletes every data in the storage. * * <b>Warning!</b> Flushes the whole memcached server * * @return mixed */ public function clear() { if ($this->readOnly) { throw new StorageException('Trying to write to a read only storage'); } $debugger = Application::getInstance()->getDiContainer()->getDebugger(); $startTime = microtime(true); $this->memcache->flush(); // If we have a debugger, we have to log the request if (!$this->debuggerDisabled && $debugger !== false) { $debugger->addItem(new StorageItem('memcache', 'memcache.' . $this->currentConfigurationName, StorageItem::METHOD_CLEAR, null, microtime(true) - $startTime)); } }
/** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. */ protected function tearDown() { Config::getInstance()->clear(); Application::getInstance()->setDiContainer(new SystemContainer()); }
/** * Returns a UserDao instance * * @return \VendTools\Dao\UserDao */ protected function getUserDao() { return Application::getInstance()->getDiContainer()->getDao('User'); }
/** * Runs a query and returns the result object. * * @param string $query The query to execute. * @param array $params The parameters for the query. * * @return \YapepBase\Database\DbResult The result of the query. * * @throws \YapepBase\Exception\DatabaseException On execution errors. */ public function query($query, array $params = array()) { if (empty($this->connection)) { throw new DatabaseException('Connection to the database is not established'); } try { $debugger = Application::getInstance()->getDiContainer()->getDebugger(); // If we have a debugger, we have to log the query if ($debugger !== false) { // We have to quote the parameters to make the displayed query usable $paramsQuoted = array(); foreach ($params as $paramName => $paramValue) { $paramsQuoted[$paramName] = $this->quote($paramValue); } $debugItem = new SqlQueryItem($this->getBackendType(), $this->getBackendType() . '.' . $this->connectionName, $query, $paramsQuoted); $debugger->addItem($debugItem); $startTime = microtime(true); } $statement = $this->connection->prepare($query); foreach ($params as $key => $value) { $statement->bindValue(':' . $this->paramPrefix . $key, $value, $this->getParamType($value)); } $statement->execute(); // If we have a debugger, we have to log the execution time if ($debugger !== false) { $debugItem->setExecutionTime(microtime(true) - $startTime); } return new DbResult($statement); } catch (PDOException $exception) { $this->transactionFailed = true; $message = null; $code = 0; $this->parsePdoException($exception, $message, $code); throw new DatabaseException($message, $code, $exception); } }
public function testSetToView() { $controller = $this->getController(); $controller->setAction(function (MockController $instance) { $instance->setToView('test', 'test value'); }); $controller->run('Test'); $this->assertEquals('test value', Application::getInstance()->getDiContainer()->getViewDo()->get('test')); }
/** * Displays the interface of the Debugger (if it has one). * * @return void */ protected function render() { // We only render if we have renderers and the render() method has not been called yet. if ($this->isRendered || empty($this->renderers)) { return; } $this->isRendered = true; $endTime = microtime(true); $runTime = $endTime - $this->startTime; $currentMemory = memory_get_usage(true); $peakMemory = memory_get_peak_usage(true); /** @var \YapepBase\Debugger\IDebuggerRenderer $renderer */ foreach ($this->renderers as $renderer) { $renderer->render($this->startTime, $runTime, $currentMemory, $peakMemory, $this->items, $_SERVER, $_POST, $_GET, $_COOKIE, Application::getInstance()->getDiContainer()->getSessionRegistry()->getAllData()); } }
/** * Removes event handler registration * * @return void */ public function removeEventHandler() { $registry = Application::getInstance()->getDiContainer()->getEventHandlerRegistry(); $registry->removeEventHandler(Event::TYPE_APPLICATION_BEFORE_CONTROLLER_RUN, $this); $registry->removeEventHandler(Event::TYPE_APPLICATION_AFTER_CONTROLLER_RUN, $this); }
/** * Send a request to the Vend tokens endpoint. * * @param string $domainPrefix The domain prefix for the vend store. * @param array $params The parameters for the request. * * @return OAuthResponseDo * @throws Exception If there is an error during the request. * @throws \YapepBase\Exception\CurlException If there is a communication problem. * @throws \YapepBase\Exception\ParameterException If the response data is not in the required format. */ protected function sendVendTokenRequest($domainPrefix, array $params) { $url = 'https://' . $domainPrefix . '.vendhq.com/api/1.0/token'; $request = Application::getInstance()->getDiContainer()->getCurlHttpRequest(); $request->setMethod(CurlHttpRequest::METHOD_POST); $request->setUrl($url); $request->setPayload($params, CurlHttpRequest::PAYLOAD_TYPE_FORM_ENCODED); $result = $request->send(); if (!$result->isRequestSuccessful()) { if ($result->getError()) { $additionalInfo = 'Curl error: ' . $result->getError(); } else { $statusCode = $result->getResponseCode(); preg_match('#^HTTP/[0-9\\.]+ ' . (int) $statusCode . '[^\\n]+#ms', $result->getResponseHeaders(), $matches); $additionalInfo = 'Status line: ' . $matches[0]; } throw new Exception('Error while sending the access token request. ' . $additionalInfo, 0, null, $result); } $resultJson = json_decode($result->getResponseBody(), true); if (empty($resultJson)) { throw new Exception('Error while decoding JSON response from the access token request. Error: ' . json_last_error_msg(), 0, null, $result); } return new OAuthResponseDo($resultJson); }
/** * Returns a common helper by it's name * * @param string $name The name of the Helper class to return. * (Without the namespace and Helper suffix) * * @return \YapepBase\Helper\HelperAbstract */ protected function getHelper($helperName) { return Application::getInstance()->getDiContainer()->getHelper($helperName); }
#!/usr/bin/php <?php namespace Test; use YapepBase\Application; require __DIR__ . '/../bootstrap.php'; // Ugly global hack just for demo :) Application::getInstance()->getDiContainer()->get('test.testScript')->run();
/** * Deletes every data in the storage. * * @throws \YapepBase\Exception\StorageException If the Storage is read only. * * @return void */ public function clear() { if ($this->readOnly) { throw new StorageException('Trying to write to a read only storage'); } $startTime = microtime(true); try { $this->fileHandler->removeDirectory($this->path, true); } catch (FileException $e) { throw new StorageException('Unable to remove the directory: ' . $this->path, 0, $e); } $debugger = Application::getInstance()->getDiContainer()->getDebugger(); if (!$this->debuggerDisabled && $debugger !== false) { $debugger->addItem(new StorageItem('file', 'file.' . $this->currentConfigurationName, StorageItem::METHOD_CLEAR, null, microtime(true) - $startTime)); } }
/** * Sends the request. * * @return boolean TRUE on success, FALSE on failure * * @throws \YapepBase\Exception\Exception If there was an error. */ public function send() { if (!empty($this->cookies)) { $cookies = array(); foreach ($this->cookies as $name => $value) { $cookies[] = $name . '=' . $value; } curl_setopt($this->curl, CURLOPT_COOKIE, implode('; ', $cookies)); } $debugger = Application::getInstance()->getDiContainer()->getDebugger(); // If we have a debugger, we have to log the query $startTime = microtime(true); $result = curl_exec($this->curl); if ($debugger !== false) { $debugger->addItem(new CurlRequestItem(CurlRequestItem::PROTOCOL_HTTP, $this->method, $this->url, $this->parameters, $this->additionalHeaders, $this->extraOptions, microtime(true) - $startTime)); } if (false === $result) { $this->error = curl_error($this->curl); throw new \YapepBase\Exception\Exception('Curl Error:' . curl_error($this->curl)); } $info = curl_getinfo($this->curl); curl_close($this->curl); $this->responseBody = (string) substr($result, $info['header_size']); $this->responseHeaders = (string) substr($result, 0, $info['header_size']); $this->responseInfo = $info; return true; }
/** * Tests the event handler registration * * @return void */ public function testEventHandlerRegistration() { $storage = $this->getStorageMock(); $eventHandlerRegistry = Application::getInstance()->getDiContainer()->getEventHandlerRegistry(); $session = $this->getSession(null, array(), $storage, true); $this->assertTrue(in_array($session, $eventHandlerRegistry->getEventHandlers(Event::TYPE_APPLICATION_BEFORE_CONTROLLER_RUN), true), 'Autoregistration failed for APPSTART event'); $this->assertTrue(in_array($session, $eventHandlerRegistry->getEventHandlers(Event::TYPE_APPLICATION_AFTER_CONTROLLER_RUN), true), 'Autoegistration failed for APPFINISH event'); $session->removeEventHandler(); $this->assertFalse(in_array($session, $eventHandlerRegistry->getEventHandlers(Event::TYPE_APPLICATION_BEFORE_CONTROLLER_RUN), true), 'Unregistration failed for APPSTART event'); $this->assertFalse(in_array($session, $eventHandlerRegistry->getEventHandlers(Event::TYPE_APPLICATION_AFTER_CONTROLLER_RUN), true), 'Unregistration failed for APPFINISH event'); $session->registerEventHandler(); $this->assertTrue(in_array($session, $eventHandlerRegistry->getEventHandlers(Event::TYPE_APPLICATION_BEFORE_CONTROLLER_RUN), true), 'Manual registration failed for APPSTART event'); $this->assertTrue(in_array($session, $eventHandlerRegistry->getEventHandlers(Event::TYPE_APPLICATION_AFTER_CONTROLLER_RUN), true), 'Manual registration failed for APPFINISH event'); }