Doctrine Record Listener - php

I have a listener which contains a preSave() method. Is there a way for me to halt doctrine
from calling the save method if a condition fails. Unfortunately I am not allowed to throw an exception. Is there any other way?

My first idea would be to set a flag in the preSave()-method and to check for that flag in the save()-method. But I think skipOperation() is what you are looking for:
public function preSave(Doctrine_Event $event)
{
if (!$condition) {
$event->skipOperation();
}
}

Related

Implementing a try/catch block in php constructor function

I have a query with try-catch block. I am going to create object and if it fails it will throw error message or say redirect on some other page.
Code
function __construct() {
try{
$this->ServiceObj = AnyClass::getService('XXX');
}
catch{
return Redirect::to('/');
}
}
public function MyOwnFunction() {
$getValueofCode = $this->_ServiceObj->set($endPoint_Url); //it's only example method not want to set anything
}
Is this correct way to define and use the try catch block in a constructor? Can I use try & catch block in construction? If NO than is there a better way to achieve this?
Thanks in Advance!!!
You can definitely use try catch in a constructor, just don't forget to specify the exception class you want to catch like catch (\Exception $e). However Laravel will not process the returned redirect. (By definition constructors shouldn't even return something)
An easy fix for this would be calling send() on the redirect. This will return it immediately to the client and stop the app.
try{
$this->ServiceObj = AnyClass::getService('XXX');
}
catch(\Exception $e){
Redirect::to('/')->send();
}
But since you mentioned a login page, you might be better of using a before filter to check and redirect. Like the built in auth filter does.
A third solution would be App::error. In app/start/global.php you could do something like this:
App::error(function(FooBarException $exception)
{
return Redirect::to('/');
});
Of course this only works if your exception is specific enough (replace FooBarException with the exception you want to catch)

Is it bad practice to add a flag to throw an exception?

I have some methods in a class that I think could be useful for testing stuff, but also in some cases the program may want to halt completely if the check fails. Originally I was wrapping the method calls in if conditions and then throwing an exception, however, I ended up having the same if conditions in many methods and it seemed wasteful, so I added a boolean flag to the check method to have it throw an exception if the check failed. An example:
public function isValidDirection($direction, $throwException = false) {
if(!in_array($direction, $this->getDirections()) && $throwException) {
throw new \InvalidArgumentException(sprintf('Invalid direction value. Valid directions are: "%s"', implode(", ", $this->getDirections())));
}
return in_array($direction, $this->getDirections());
}
Is this a bad idea? I've not come across this kind of pattern before and I'm wondering are there any pitfalls to it?
An exception should be thrown in exceptional circumstances. That means when your code is in a situation that it is not prepared to handle. If your function is a validation function whose job it is to confirm the validity of data, there should hardly be any exceptional error possible. The job of the function is simple: take input, return true or false depending on whether it's valid. If you want to handle the case of invalid input by throwing an exception and you want to DRY that repetitive check, create another function which wraps your validation function. So you'd have two functions: isValidDirection($input) and assertIsValidDirection($input), the latter of which throws an exception if it's not valid and otherwise does nothing.
function isValidDirection($input) {
return ...; // true or false
}
function assertIsValidDirection($input) {
if (!isValidDirection($input)) {
throw new InvalidArgumentException;
}
}
This keeps both functions' responsibilities clear and their implementation simple.
Yeah, it's a bad idea. If the method gets into a state where it can't continue or otherwise shouldn't get into it should throw an exception. It's up to the calling code to handle the exception as it feels is necessary or let the program crash. Otherwise the caller is oblivious to the program failing and will continue and usually make the situation worse/harder to debug.
If, in the case that you don't want to halt your program you can catch the exception and log an error, or handle it some more graceful way depending on your situation. If you don't expect the error at all the program will crash (ideally during testing) and the error won't propagate; you then know exactly where to look to fix it.
So, if I understand it correctly, your code should throw an exception if the $direction isn't in getDirections.
e.g:
public function isValidDirection($direction) {
if(!in_array($direction, $this->getDirections())) {
throw new \InvalidArgumentException(sprintf('Invalid direction value. Valid directions are: "%s"', implode(", ", $this->getDirections())));
}
return in_array($direction, $this->getDirections());
}
(Also, you don't need to call getDirections 3 times, just call it once and store it in a variable)

How to catch ParamConverter exceptions in Symfony2?

Here is the exception I got:
No result was found for query although at least one row was expected.
I am basically getting that exception when a user id is not found in database.
Here is what my route looks like:
localhost/../user/18
and the code in my controller:
public function showAction(User $user){
// ..
}
I know I can use the kernel event exception to handle this, but is there an easier way to catch an exception generated by the ParamConverter?
In some cases it's useful to throw exception manually if object not found. You can tell action skip throw exception if entity not found by adding default value to param.
Example:
public function showUser(User $user = null) {
if (empty($user)) {
throw new CustomExceptionYouWant();
}
...
}
You can create your user ParamConverter by implementing ParamConverterInterface and inside it, create methods you can use as a custom exception or do other processing.
This a good exemple of what you want to create Custom ParamConverter

How can I retrieve the current error handler?

I'd like to find out what error handler is currently, well, handling errors.
I know that set_error_handler() will return the previous error handler, but is there a way to find out what the current error handler is without setting a new one?
Despite the lack of a get_error_handler() function in PHP, you can use a little trickery with set_error_handler() to retrieve the current error handler, although you might not be able to do much with that information, depending on it's value. Nonetheless:
set_error_handler($handler = set_error_handler('var_dump'));
// Set the handler back to itself immediately after capturing it.
var_dump($handler); // NULL | string | array(2) | Closure
Look, ma, it's idempotent!
Yes, there is a way to find out the error handler without setting up new one. This is not the one step native php function. but its effects are exactly that what you need.
summarizing all suggestions of #aurbano, #AL the X, #Jesse and #Dominic108 replacement method can look like this
function get_error_handler(){
$handler = set_error_handler(function(){});
restore_error_handler();
return $handler;
}
You could use set_error_handler(). set_error_handler() returns the current error handler (though as 'mixed'). After you retrieved it, use restore_error_handler(), which will leave it as it was.
This isn't possible in PHP - as you said, you could retrive the current error handler when you call set_error_handler and restore it with restore_error_handler
<?php
class MyException extends Exception {}
set_exception_handler(function(Exception $e){
echo "Old handler:".$e->getMessage();
});
$lastHandler = set_exception_handler(function(Exception $e) use (&$lastHandler) {
if ($e instanceof MyException) {
echo "New handler:".$e->getMessage();
return;
}
if (is_callable($lastHandler)) {
return call_user_func_array($lastHandler, [$e]);
}
throw $e;
});
Trigger the exception handler:
throw new MyException("Exception one", 1);
Output: New handler:Exception one
throw new Exception("Exception two", 1);
Output: Old handler:Exception two
one can also use https://stackoverflow.com/a/43342227 for getting the last exception handler:
function get_exception_handler()
{
$handler = set_exception_handler(function () {});
restore_exception_handler();
return $handler;
}
this might be useful if you want - eg in a unit test - which exception handler has been registered.
I check the source and the answer is no.

Selenium RC: How to check if an element has a given attribute?

I have some buttons with an onclick attribute and some that don't. I want to check if the specified element has the onclick attribute. How can I do this?
getAttribute() returns the attribute value when it has one. When it doesn't, it throws a RuntimeException and stops the test (even when I wrap it in a try/catch block).
$onclickValue = $this->getAttribute("$locator#onclick"); //works when the attribute exists
By using getEval(), you can execute the javascript hasAttribute() function. Using findElement(), will allow you to work with any type of locator pattern.
$hasAttribute = $this->getEval('this.browserbot.findElement("' . $locator . '").hasAttribute("onclick")');
if ($hasAttribute === 'true') {
//attribute exists
}
Note that getEval() returns a string, not a boolean.
You could first check if the element is present using XPath //location/of/element[#onclick]
Please excuse me if this does not apply to Selenium RC. In Selenium IDE, one can use the
assertElementNotPresent
command, which (despite the name) can determine whether a given attribute is present. It's only parameter is an element locator that can be of the form
element-id#attribute.
Of course this will only be appropriate if you know which elements should have the attribute in question. If not then I guess you'll have to iterate through element sets using XPath expressions.
The reason why a RuntimeException is thrown is because the way PHPUnit's selenium driver works.
It considers certain situations as errors that perform a stop() of the test execution. In particular, the code that stops the test in that situation is the following:
protected function getString($command, array $arguments)
{
try {
$result = $this->doCommand($command, $arguments);
}
catch (RuntimeException $e) {
$this->stop();
throw $e;
}
return (strlen($result) > 3) ? substr($result, 3) : '';
}
I already opened an issue regarding this way of handling errors in the driver at https://github.com/sebastianbergmann/phpunit/issues/276
BTW, removing the calls to stop() in both doCommand() and getString() of /usr/share/php/PHPUnit/Extensions/SeleniumTestCase/Driver.php will make your code able of catching the exception and handling it as you prefer.

Categories