Exception PHP Class Code Examples

This page contains top rated real world PHP examples of class Exception extracted from open source projects. You can rate examples to help us improve the quality of examples

Example #1
Show file File: SolverCompositeTest.php Project: kraken-php/framework
0
 /**
  *
  */
 public function testApiSolver_RejectsPromise_OnFirstRejection()
 {
     $ex1 = new Exception('Exception');
     $ex2 = new Exception('Other Exception');
     $params = ['params1' => 'value1'];
     $queue = '';
     $solver1 = $this->getMock(SolverInterface::class, [], [], '', false);
     $solver1->expects($this->once())->method('solve')->with($ex1, $params)->will($this->returnCallback(function () use(&$queue, $ex2) {
         $queue .= 'A';
         return Promise::doReject($ex2);
     }));
     $solver2 = $this->getMock(SolverInterface::class, [], [], '', false);
     $solver2->expects($this->never())->method('solve')->with($ex1, $params)->will($this->returnCallback(function () use(&$queue) {
         $queue .= 'B';
     }));
     $solver3 = $this->getMock(SolverInterface::class, [], [], '', false);
     $solver3->expects($this->never())->method('solve')->with($ex1, $params)->will($this->returnCallback(function () use(&$queue) {
         $queue .= 'C';
     }));
     $solver = $this->createSolver([$solver1, $solver2, $solver3]);
     $callable = $this->createCallableMock();
     $callable->expects($this->once())->method('__invoke')->with($ex2);
     $result = $this->callProtectedMethod($solver, 'solver', [$ex1, $params]);
     $result->then(null, $callable);
     $this->assertSame('A', $queue);
 }
Example #2
Show file File: PromiseRejectedTestTrait.php Project: hazaveh/mySQLtoes
0
 /** @test */
 public function alwaysShouldRejectWhenHandlerRejectsForRejectedPromise()
 {
     $adapter = $this->getPromiseTestAdapter();
     $exception1 = new \Exception();
     $exception2 = new \Exception();
     $mock = $this->createCallableMock();
     $mock->expects($this->once())->method('__invoke')->with($this->identicalTo($exception2));
     $adapter->reject($exception1);
     $adapter->promise()->always(function () use($exception2) {
         return \React\Promise\reject($exception2);
     })->then(null, $mock);
 }
Example #3
Show file File: SymfonyDisplayer.php Project: LuckyCyborg/simple-mvc-framework
0
 /**
  * Display the given exception to the user.
  *
  * @param  \Exception  $exception
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function display(Exception $exception)
 {
     if ($this->returnJson) {
         return new JsonResponse(array('error' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine()), 500);
     }
     return $this->symfony->createResponse($exception);
 }
Example #4
Show file File: AbstractUndefinedMemberException.php Project: a13wes/MRKT
0
 /**
  * Construct a new undefined member exception.
  *
  * @param string         $message   The exception message.
  * @param string         $className The name of the class from which the member was requested.
  * @param string         $property  The name of the property used to search for the member.
  * @param mixed          $value     The value of the property used to search for the member.
  * @param Exception|null $cause     The cause, if available.
  */
 public function __construct($message, $className, $property, $value, Exception $cause = null)
 {
     $this->className = $className;
     $this->property = $property;
     $this->value = $value;
     parent::__construct($message, 0, $cause);
 }
Example #5
Show file File: Handler.php Project: VictorAvelar/sfg
0
 /**
  * Render an exception into an HTTP response.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Exception  $e
  * @return \Illuminate\Http\Response
  */
 public function render($request, Exception $e)
 {
     if ($e instanceof ModelNotFoundException) {
         $e = new NotFoundHttpException($e->getMessage(), $e);
     }
     return parent::render($request, $e);
 }
Example #6
Show file File: WebLoggerTest.php Project: kidaa30/magento2-platformsh
0
 public function testLogError()
 {
     $e1 = new \Exception('Dummy Exception1');
     $e2 = new \Exception('Dummy Exception2');
     $this->webLogger->logError($e1);
     $this->assertContains('[ERROR]', self::$log);
     $this->assertContains('Exception', self::$log);
     $this->assertContains($e1->getMessage(), self::$log);
     $this->webLogger->logError($e2);
     $this->assertContains('[ERROR]', self::$log);
     $this->assertContains('Exception', self::$log);
     $this->assertContains($e1->getMessage(), self::$log);
     $this->assertContains($e2->getMessage(), self::$log);
 }
Example #7
Show file File: function.action.php Project: GerDner/luck-docker
0
/**
 * Method to fast deploy a query to enlight
 *
 * The params array knows the following keys
 * - name : The name of the action to call
 * - params : optional params array for the specific action call
 *
 * @param                          $params
 * @param Enlight_Template_Default $template
 * @return string
 * @throws Exception
 */
function smarty_function_action($params, Enlight_Template_Default $template)
{
    /** @var $front Enlight_Controller_Front */
    $front = Enlight_Application::Instance()->Front();
    $dispatcher = clone $front->Dispatcher();
    $modules = $dispatcher->getControllerDirectory();
    if (empty($modules)) {
        $e = new Exception('Action helper depends on valid front controller instance');
        //$e->setView($view);
        throw $e;
    }
    $request = $front->Request();
    $response = $front->Response();
    if (empty($request) || empty($response)) {
        $e = new Exception('Action view helper requires both a registered request and response object in the front controller instance');
        //$e->setView($view);
        throw $e;
    }
    if (isset($params['name'])) {
        $params['action'] = $params['name'];
        unset($params['name']);
    }
    if (isset($params['params'])) {
        $userParams = (array) $params['params'];
        unset($params['params']);
    } else {
        $userParams = array();
    }
    $params = array_merge($userParams, $params);
    $request = clone $request;
    $response = clone $response;
    $request->clearParams();
    $response->clearHeaders()->clearRawHeaders()->clearBody();
    if (isset($params['module'])) {
        $request->setModuleName($params['module'])->setControllerName('index')->setActionName('index');
    }
    if (isset($params['controller'])) {
        $request->setControllerName($params['controller'])->setActionName('index');
    }
    $request->setParam('_isSubrequest', true);
    $request->setActionName(isset($params['action']) ? $params['action'] : 'index');
    $request->setParams($params)->setDispatched(true);
    $dispatcher->dispatch($request, $response);
    if (!$request->isDispatched() || $response->isRedirect()) {
        // forwards and redirects render nothing
        return '';
    }
    $return = $response->getBody();
    return $return;
}
Example #8
Show file File: SocketServerTest.php Project: kraken-php/framework
0
 /**
  *
  */
 public function testApiHandleError_TriesToHandleError_WhenComponentThrowsException()
 {
     $ex1 = new Exception();
     $ex2 = new Exception();
     $listener = $this->createListener();
     $component = $this->createComponent();
     $component->expects($this->once())->method('handleError')->with($this->isInstanceOf(NetworkConnection::class), $ex2)->will($this->throwException($ex1));
     $socket = $this->getMock(SocketInterface::class, [], [], '', false);
     $socket->conn = new NetworkConnection($socket);
     $server = $this->createSocketServer($listener, $component, ['close']);
     $server->expects($this->once())->method('close')->with($socket);
     $server->handleError($socket, $ex2);
 }
Example #9
Show file File: MultiTransferExceptionTest.php Project: alvarobfdev/applog
0
 public function testAssociatesExceptionsWithRequests()
 {
     $r1 = new Request('GET', 'http://www.foo.com');
     $re1 = new \Exception('foo');
     $re2 = new \Exception('bar');
     $e = new MultiTransferException();
     $e->add($re2);
     $e->addFailedRequestWithException($r1, $re1);
     $this->assertSame($re1, $e->getExceptionForFailedRequest($r1));
     $this->assertNull($e->getExceptionForFailedRequest(new Request('POST', '/foo')));
 }
Example #10
Show file File: ExceptionRendererTest.php Project: dgamboaestrada/cakephp-api
0
 public function testGenericExceptionDuringRendering()
 {
     $this->markTestSkipped();
     $Exception = new Exception('Hello World');
     $NestedException = new Exception('Generic Exception Description');
     $Controller = $this->getMock('Cake\\Controller\\Controller', ['render']);
     $Controller->request = new Request();
     $Controller->response = $this->getMock('Cake\\Network\\Response');
     $Renderer = $this->getMock('Crud\\Error\\ExceptionRenderer', ['_getController'], [], '', false);
     $Renderer->expects($this->once())->method('_getController')->with()->will($this->returnValue($Controller));
     $Renderer->__construct($Exception);
     $Renderer->render();
     $viewVars = $Controller->viewVars;
     $this->assertTrue(!empty($viewVars['_serialize']));
     $expected = ['success', 'data'];
     $actual = $viewVars['_serialize'];
     $this->assertEquals($expected, $actual);
     $expected = ['code' => 500, 'url' => $Controller->request->here(), 'message' => 'Hello World', 'exception' => ['class' => 'Cake\\Core\\Exception\\Exception', 'code' => 500, 'message' => 'Hello World']];
     $actual = $viewVars['data'];
     unset($actual['trace']);
     $this->assertEquals($expected, $actual);
     $this->assertTrue(isset($viewVars['success']));
     $this->assertFalse($viewVars['success']);
     $this->assertTrue(isset($viewVars['code']));
     $this->assertSame(500, $viewVars['code']);
     $this->assertTrue(isset($viewVars['url']));
     $this->assertSame($Controller->request->here(), $viewVars['url']);
     $this->assertTrue(isset($viewVars['message']));
     $this->assertSame('Generic Exception Description', $viewVars['message']);
     $this->assertTrue(isset($viewVars['error']));
     $this->assertSame($NestedException, $viewVars['error']);
 }
Example #11
Show file File: Session.php Project: claudinec/galan-wiki
0
 /**
  * Fetch a value from the session that was set with self::setSecret()
  * @param string|int $key
  * @param mixed $default Returned if $this->exists( $key ) would be false or decryption fails
  * @return mixed
  */
 public function getSecret($key, $default = null)
 {
     global $wgSessionInsecureSecrets;
     // Fetch
     $encrypted = $this->get($key, null);
     if ($encrypted === null) {
         return $default;
     }
     // The code for unsealing, checking, and decrypting (with OpenSSL) is
     // taken from Chris Steipp's OATHAuthUtils class in
     // Extension::OATHAuth.
     // Unseal and check
     $pieces = explode('.', $encrypted);
     if (count($pieces) !== 3) {
         $ex = new \Exception('Invalid sealed-secret format');
         $this->logger->warning($ex->getMessage(), ['exception' => $ex]);
         return $default;
     }
     list($hmac, $iv, $ciphertext) = $pieces;
     list($encKey, $hmacKey) = $this->getSecretKeys();
     $integCalc = hash_hmac('sha256', $iv . '.' . $ciphertext, $hmacKey, true);
     if (!hash_equals($integCalc, base64_decode($hmac))) {
         $ex = new \Exception('Sealed secret has been tampered with, aborting.');
         $this->logger->warning($ex->getMessage(), ['exception' => $ex]);
         return $default;
     }
     // Decrypt
     // @todo: import a pure-PHP library for AES instead of doing $wgSessionInsecureSecrets
     if (function_exists('openssl_decrypt')) {
         $serialized = openssl_decrypt(base64_decode($ciphertext), 'aes-256-ctr', $encKey, OPENSSL_RAW_DATA, base64_decode($iv));
         if ($serialized === false) {
             $ex = new \Exception('Decyption failed: ' . openssl_error_string());
             $this->logger->debug($ex->getMessage(), ['exception' => $ex]);
             return $default;
         }
     } elseif (function_exists('mcrypt_decrypt')) {
         $serialized = mcrypt_decrypt('rijndael-128', $encKey, base64_decode($ciphertext), 'ctr', base64_decode($iv));
         if ($serialized === false) {
             $ex = new \Exception('Decyption failed');
             $this->logger->debug($ex->getMessage(), ['exception' => $ex]);
             return $default;
         }
     } elseif ($wgSessionInsecureSecrets) {
         $ex = new \Exception('No encryption is available, retrieving data that was stored as plain text');
         $this->logger->warning($ex->getMessage(), ['exception' => $ex]);
         $serialized = base64_decode($ciphertext);
     } else {
         throw new \BadMethodCallException('Encryption is not available. You really should install the PHP OpenSSL extension, ' . 'or failing that the mcrypt extension. But if you really can\'t and you\'re willing ' . 'to accept insecure storage of sensitive session data, set ' . '$wgSessionInsecureSecrets = true in LocalSettings.php to make this exception go away.');
     }
     $value = unserialize($serialized);
     if ($value === false && $serialized !== serialize(false)) {
         $value = $default;
     }
     return $value;
 }
Example #12
Show file File: WebLoggerTest.php Project: shabbirvividads/magento2
0
 public function testLogError()
 {
     $e1 = new \Exception('Dummy Exception1');
     $e2 = new \Exception('Dummy Exception2');
     $this->webLogger->logError($e1);
     $this->assertContains('[ERROR] exception \'Exception\' with message \'Dummy Exception1\'', self::$log);
     $this->webLogger->logError($e2);
     $this->assertContains('[ERROR] exception \'Exception\' with message \'Dummy Exception1\'', self::$log);
     $this->assertContains('[ERROR] exception \'Exception\' with message \'Dummy Exception2\'', self::$log);
 }
Example #13
Show file File: Dailymotion.php Project: luisbrito/Phraseanet
0
 /**
  * Set The exception to Bridge_Exception_ActionAuthNeedReconnect
  * if exception is instance of Zend_Gdata_App_HttpException and Http code 401
  *
  * @param  Exception $e
  * @return Void
  */
 public function handle_exception(Exception $e)
 {
     if ($e instanceof DailymotionAuthException) {
         $e = new Bridge_Exception_ActionAuthNeedReconnect($e->getMessage());
     } elseif ($e instanceof DailymotionApiException || $e instanceof DailymotionAuthRequiredException) {
         $e = new Exception($e->getMessage(), $e->getCode());
     }
     return;
 }
Example #14
Show file File: Matrixcode.php Project: ChristophWurst/pimcore
0
 /**
  * Renderer Constructor
  *
  * @param mixed $renderer           String name of renderer class, or \Zend_Config object.
  * @param mixed $rendererConfig     OPTIONAL; an array or \Zend_Config object with renderer parameters.
  * @return Pimcore_Image_Matrixcode_Renderer_Abstract
  */
 public static function getRenderer($renderer = 'image', $rendererConfig = array())
 {
     /*
      * Convert \Zend_Config argument to plain string
      * renderer name and separate config object.
      */
     if ($renderer instanceof \Zend_Config) {
         if (isset($renderer->rendererParams)) {
             $rendererConfig = $renderer->rendererParams->toArray();
         }
         if (isset($renderer->renderer)) {
             $renderer = (string) $renderer->renderer;
         }
     }
     if ($rendererConfig instanceof \Zend_Config) {
         $rendererConfig = $rendererConfig->toArray();
     }
     /*
      * Verify that renderer parameters are in an array.
      */
     if (!is_array($rendererConfig)) {
         $e = new Exception('Renderer parameters must be in an array or a \\Zend_Config object');
         throw $e;
     }
     /*
      * Verify that a renderer name has been specified.
      */
     if (!is_string($renderer) || empty($renderer)) {
         $e = new Exception('Renderer name must be specified in a string');
         throw $e;
     }
     /*
      * Form full renderer class name
      */
     $rendererNamespace = '\\Pimcore\\Image\\Matrixcode\\Renderer';
     if (isset($rendererConfig['rendererNamespace'])) {
         $rendererNamespace = $rendererConfig['rendererNamespace'];
     }
     $rendererName = $rendererNamespace . '\\' . ucfirst($renderer);
     /*
      * Load the renderer class.
      */
     if (!class_exists($rendererName)) {
         \Zend_Loader::loadClass($rendererName);
     }
     /*
      * Create an instance of the renderer class.
      */
     $rdrAdapter = new $rendererName($rendererConfig);
     /*
      * Verify that the object created is a descendent of the abstract renderer type.
      */
     if (!$rdrAdapter instanceof \Pimcore\Image\Matrixcode\Renderer\AbstractRenderer) {
         $e = new Exception("Renderer class '{$rendererName}' does not extend Pimcore_Image_Matrixcode_Renderer_Abstract");
         throw $e;
     }
     return $rdrAdapter;
 }
Example #15
Show file File: ExceptionStack.php Project: deepakb/test-driven-development-example
0
 public function testNestedExceptions()
 {
     $exceptionThree = new Exception('Three');
     $exceptionTwo = new InvalidArgumentException('Two', 0, $exceptionThree);
     $exceptionOne = new Exception('One', 0, $exceptionTwo);
     throw $exceptionOne;
 }
Example #16
Show file File: WealthbotRebalancer.php Project: junjinZ/wealthbot
0
 /**
  * Buy security
  *
  * @param Security $security
  * @param Account $account
  * @param $amount
  * @param bool $dryRun
  * @return float|int
  * @throws \Exception
  */
 public function buySecurity(Security $security, Account $account, $amount, $dryRun = false)
 {
     $price = $security->getPrice();
     $buyQuantity = $price > 0 ? floor($amount / $price) : 0;
     $buyAmount = $buyQuantity * $price;
     if (!$security->isCanBePurchased($buyQuantity, $buyAmount)) {
         $exception = new \Exception(sprintf('Buying security error: cannot buy security with id: %s, qty: %s, amount: %s.', $security->getId(), $buyQuantity, $buyAmount));
         $this->logger->logError($exception);
         throw $exception;
     }
     if (!$this->checkTransaction($account, $amount, $security, 'buy')) {
         $exception = new \Exception("Cannot buy: {$security->getId()} . Transaction check fails. (Amount:{$amount})");
         $this->logger->logError($exception);
         throw $exception;
     }
     if (!$dryRun) {
         $this->logger->logInfo("Buy security {$security->getId()} qty: {$buyQuantity}; amount: {$buyAmount}");
         $security->buy($buyQuantity, $buyAmount);
         $queueItem = new QueueItem();
         $queueItem->setRebalancerActionId($this->getRebalancerAction()->getId());
         $queueItem->setSecurity($security);
         $queueItem->setAccount($account);
         $queueItem->setQuantity($buyQuantity);
         $queueItem->setAmount($buyAmount);
         $queueItem->setStatus(QueueItem::STATUS_BUY);
         $this->getRebalancerQueue()->addItem($queueItem);
     }
     return $buyAmount;
 }
Example #17
Show file File: HookDispatcher.php Project: unkerror/Budabot
0
 /**
  * Adds hook information to exception thrown from it.
  *
  * @param HookInterface $hook      hook instance
  * @param \Exception    $exception exception
  */
 private function addHookInformationToException(HookInterface $hook, \Exception $exception)
 {
     $refl = new \ReflectionObject($exception);
     $message = $refl->getProperty('message');
     $message->setAccessible(true);
     $message->setValue($exception, sprintf('Exception has been thrown in "%s" hook, defined in %s' . "\n\n%s", $hook->getEventName(), $hook->getPath(), $exception->getMessage()));
 }