Throw exceptions instead of silently returning null
I'm trying to find the namespace of an XML file with:
$saxonProc = new SaxonProcessor(); $xPathProcessor = $saxonProc->newXPathProcessor(); $xPathProcessor->setContextFile($file->getPathname()); $item = $xPathProcessor->evaluateSingle('/*/namespace::*[name()=\'\']');
According to the documentation:
evaluateSingle(string $xpathStr) Compile and evaluate an XPath expression whose result is expected to be a single item, with a given context item. The expression is supplied as a character string, and the result returned as an XdmItem.
So the return value is expected to be an XdmItem. However, when the expression could not be evaluated, it can also return null.
It would be great if exceptions can be thrown when these situations occur. (I expect these can be applied on other functions as well?), so these exceptions can be caught with a try-catch block. Now, the return type is not documented, but 'silently' returning a null value is also not desirable.
Updated by Michael Kay about 3 years ago
- Assignee set to O'Neil Delpratt
I think this is more of a documentation issue than anything else. Your XPath expression is perfectly valid and returns an empty sequence. The interface documentation for
evaluateSingle should be clearer about exactly what happens when the XPath result is not a single item (i.e. when it's empty, or when there's more than one item in the result).
Updated by O'Neil Delpratt about 3 years ago
- Category set to Documentation
Hi, in the first instance I will follow through with comment #1 by updating the documentation for this method:
return null if the expression returns an empty sequence. If the expression returns a sequence of more than one item, any items after the first are ignored.
If I was to always expect to find a value, then maybe throwing an exception would be more useful.
We do welcome suggestions, but I would think that returning a
null is valid in this situaton as it is not an error for the XPath expression nothing is selected. Here we represent the empty sequence with a
Updated by Peter Jan about 3 years ago
Hi, thank you both for your response.
Im perfectly fine with just updating the documentation, that will help. I'm not sure if this is limited to the
evaluateSingle method, but ill leave that to your estimate.
If you can let me know when this has been resolved, Ill send a PR to https://github.com/JetBrains/phpstorm-stubs.
Updated by Peter Jan almost 3 years ago
PHPStorm stubs updated in https://github.com/JetBrains/phpstorm-stubs/pull/976
Please register to edit this issue