XPath: get value using relative path (PHP, Symfony, DOMCrawler) error - symfony

I'm writing a test to test my understanding of XPath with Symfony's DomCrawler:
$crawler = new Crawler();
$crawler->add('<foo><foo>bar</foo></foo>');
$crawlerWithNodes = $crawler->filterXPath('/foo/foo');
$this->assertEquals('bar', $crawlerWithNodes->text());
But the above results in:
InvalidArgumentException: The current node list is empty.
On line:
$this->assertEquals('bar', $crawlerWithNodes->text());
What am I doing wrong?

You need to load the content as DOMDocument instead of simple string (is interpreted as HTML).
You also need to add the _root prefix in the xpath string if you want to find an absolute path in the structure. See the Symfony\Component\DomCrawler\Tests\CrawlerTest cass for further example (testFilterXpathComplexQueries method)
Consider the following test method:
public function testCrawlerAsHtml()
{
$crawler = new Crawler();
$crawler->add('<html><body><foo><foo>bar</foo></foo></body></html>');
//die(var_dump($crawler->html()));
$crawlerWithNodes = $crawler->filterXPath('/_root/html/body/foo/foo');
$this->assertEquals('bar', $crawlerWithNodes->text());
}
public function testCrawlerAsDomElement()
{
$dom = new \DOMDocument();
$dom->loadXML('<foo><foo>bar</foo></foo>');
$crawler = new Crawler();
$crawler->add($dom);
// die(var_dump($crawler->html()));
$crawlerWithNodes = $crawler->filterXPath('/_root/foo/foo');
$this->assertEquals('bar', $crawlerWithNodes->text());
}
Hope this help

Related

Drupal 8 | Wrong alias used

Bonjour,
I have a problem on Drupal 8 that I can't solve, that's why I'm calling on you.
I have 2 aliases for the same node :
/public/event/10
/pro/event/10
I have a block_1 that only appears on the " /public/* " pages and a block_2 on the " /pro/* " pages.
When I access to the url "/pro/event/10", block_1 is displayed and not block_2.
I conclude that Drupal selects the alias "/public/event/10" (probably the first one he finds) while I'm on the page "/pro/event/10".
How can I programmatically tell Drupal the right alias to use?
Thank you in advance for your help.
Here is the code if it can help someone
class OOutboundPathProcessor implements OutboundPathProcessorInterface
{
function processOutbound($path, &$options = [], Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL)
{
// Only for nodes
if (!isset($options['entity_type']) OR $options['entity_type'] !== 'node')
{
return $path;
}
// Get current 'space'
$espace = \Drupal::service('session')->get('espace');
// Get the node to process
$node = $options['entity'];
// New path
$str_path = "/%s/%s/%s";
$new_path = sprintf($str_path, $espace, $node->bundle(), $node->id());
// Check new path
$isValid = \Drupal::service('path.validator')->isValid($new_path);
if ($isValid === true) return $new_path;
return $path;
}
}
You might want to create your own path_processor_outbound service by implementing OutboundPathProcessorInterface.
This implementation may work on /node/{id} paths if the current requests path matches /public/event/** or /pro/event/**.
Analyzing the node entity for it's type (bundle): If it is event generate and return your desired path; if it is not event don't manipulate the path and return the original.
Writing the actual implementation in PHP code may be your own pleasure ;-)

Mocking a GuzzleHttp response

How should I mock a Guzzle response properly. When testing a parser I'm writing, the test html is contained in files. In my PHPUnit tests I'm doing file_read_contents and passing the result into my method. Occasionally the HTML will link to a seperate file. I can mock this response like so:
public function testAlgo()
{
$mock = new MockAdapter(function() {
$mockhtml = file_get_contents($this->dir . '/HTML/authorship-test-cases/h-card_with_u-url_that_is_also_rel-me.html');
$stream = Stream\create($mockhtml);
return new Response(200, array(), $stream);
});
$html = file_get_contents($this->dir . '/HTML/authorship-test-cases/h-entry_with_rel-author_pointing_to_h-card_with_u-url_that_is_also_rel-me.html');
$parser = new Parser();
$parser->parse($html, $adaptor = $mock);
Then in my actual method, when I make the guzzle request this code works:
try {
if($adapter) {
$guzzle = new \GuzzleHttp\Client(['adapter' => $adapter]);
} else {
$guzzle = new \GuzzleHttp\Client();
}
$response = $guzzle->get($authorPage);
So obviously this isn't ideal. Does anyone know of a better way of doing this?
$html = (string) $response->getBody();
EDIT: I'm now using the __construct() methid to set up a default Guzzle Client. Then a using a second function that can be called by tests to replace the Client with a new Client that has the mock adapter. I'm not sure if this is the best way to do things.
You can use the MockPlugin API, like so:
$plugin = new MockPlugin();
$plugin->addResponse(__DIR__.'/twitter_200_response.txt');
The txt file then contains everything from your response, including headers.
There are also good approaches available here: http://www.sitepoint.com/unit-testing-guzzlephp/
Also there are articles found here: http://guzzle3.readthedocs.io/testing/unit-testing.html

ClearCanvas DicomFile.DataSet -- How to add a new Tag?

im trying to add a new tag to my DicomFile.DataSet in ClearCanvas.
I notice there is the method "DicomFile.DataSet.RemoveAttribute" but no "AddAtribute" method. So I have been looking at the method "LoadDicomFields" & "SaveDicomFields" but so far can't seem to get them to work. Ive tried to pass in a "DicomFieldAttribute" to these methods, but to no avail.
What am I missing here? Or what do I need to do to add a new tag to the DataSet.
DicomFieldAttribute c = new DicomFieldAttribute(tag);
List<DicomFieldAttribute> cs = new List<DicomFieldAttribute>();
cs.Add(c);
DicomFile.DataSet.LoadDicomFields(cs);
DicomFile.DataSet.SaveDicomFields(cs);
if(DicomFile.DataSet.Contains(tag))
{
tag = 0; //BreakPoint never reached here
}
Or I tried this as well::
DicomFieldAttribute c = new DicomFieldAttribute(tag);
DicomFile.DataSet.LoadDicomFields(c);
DicomFile.DataSet.SaveDicomFields(c);
if(DicomFile.DataSet.Contains(tag))
{
tag = 0; //BreakPoint never reached here
}
Ive been stuck on what would seem to be a trivial task.
You're confusing a bit the use of attributes. The DicomFiledAttribute is a .NET attribute that can be placed on members of a class so that the class is automatically populated with values from a DicomAttributeCollection or or to have the class automatically populated with values from the DicomAttribute Collection. Ie, given a test class like this:
public class TestClass
{
[DicomField(DicomTags.SopClassUid, DefaultValue = DicomFieldDefault.Default)]
public DicomUid SopClassUid = null;
[DicomField(DicomTags.SopInstanceUid, DefaultValue = DicomFieldDefault.Default)]
public DicomUid SOPInstanceUID = null;
[DicomField(DicomTags.StudyDate, DefaultValue = DicomFieldDefault.Default)]
public DateTime StudyDate;
}
You could populate an instance of the class like this:
DicomFile file = new DicomFile("filename.dcm");
file.Load();
TestClass testInstance = new TestClass();
file.DataSet.LoadDicomFields(testInstance);
// testInstance should now be populated with the values from file
If you're interested in just populating some DICOM tags, the DicomAttributeCollection has an indexer in it. The indexer will automatically create a DicomAttribute instance if it doesn't already exist, for the tag requested via the indexer. So, to populate a value, you can do soemthing like this:
DicomFile file = new DicomFile("filename.dcm");
file.DataSet[DicomTags.SopInstanceUid].SetStringValue("1.1.1");
If you want to create the DicomAttribute yourself, you can do something like this:
DicomAttribute attrib = new DicomAttributeUI(DicomTags.SopInstanceUid);
attrib.SetStringValue("1.1.1");
DicomFile file = new DicomFile("filename.dcm");
file.DataSet[DicomTags.SopInstanceUid] = attrib;

NVelocity not finding the template

I'm having some difficulty with using NVelocity in an ASP.NET MVC application. I'm using it as a way of generating emails.
As far as I can make out the details I'm passing are all correct, but it fails to load the template.
Here is the code:
private const string defaultTemplatePath = "Views\\EmailTemplates\\";
...
velocityEngine = new VelocityEngine();
basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, defaultTemplatePath);
ExtendedProperties properties = new ExtendedProperties();
properties.Add(RuntimeConstants.RESOURCE_LOADER, "file");
properties.Add(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, basePath);
velocityEngine.Init(properties);
The basePath is the correct directory, I've pasted the value into explorer to ensure it is correct.
if (!velocityEngine.TemplateExists(name))
throw new InvalidOperationException(string.Format("Could not find a template named '{0}'", name));
Template result = velocityEngine.GetTemplate(name);
'name' above is a valid filename in the folder defined as basePath above. However, TemplateExists returns false. If I comment that conditional out and let it fail on the GetTemplate method call the stack trace looks like this:
at NVelocity.Runtime.Resource.ResourceManagerImpl.LoadResource(String resourceName, ResourceType resourceType, String encoding)
at NVelocity.Runtime.Resource.ResourceManagerImpl.GetResource(String resourceName, ResourceType resourceType, String encoding)
at NVelocity.Runtime.RuntimeInstance.GetTemplate(String name, String encoding)
at NVelocity.Runtime.RuntimeInstance.GetTemplate(String name)
at NVelocity.App.VelocityEngine.GetTemplate(String name)
...
I'm now at a bit of an impasse. I feel that the answer is blindingly obvious, but I just can't seem to see it at the moment.
Have you considered using Castle's NVelocityTemplateEngine?
Download from the "TemplateEngine Component 1.1 - September 29th, 2009" section and reference the following assemblies:
using Castle.Components.Common.TemplateEngine.NVelocityTemplateEngine;
using Castle.Components.Common.TemplateEngine;
Then you can simply call:
using (var writer = new StringWriter())
{
_templateEngine.Process(data, string.Empty, writer, _templateContents);
return writer.ToString();
}
Where:
_templateEngine is your NVelocityTemplateEngine
data is your Dictionary of information (I'm using a Dictionary to enable me to access objects by a key ($objectKeyName) in my template.
_templateContents is the actual template string itself.
I hope this is of help to you!
Just to add, you'll want to put that into a static method returning a string of course!
Had this issue recently - NVelocity needs to be initialised with the location of the template files. In this case mergeValues is an anonymous type so in my template I can just refer to $Values.SomeItem:
private string Merge(Object mergeValues)
{
var velocity = new VelocityEngine();
var props = new ExtendedProperties();
props.AddProperty("file.resource.loader.path", #"D:\Path\To\Templates");
velocity.Init(props);
var template = velocity.GetTemplate("MailTemplate.vm");
var context = new VelocityContext();
context.Put("Values", mergeValues);
using (var writer = new StringWriter())
{
template.Merge(context, writer);
return writer.ToString();
}
}
Try setting the file.resource.loader.path
http://weblogs.asp.net/george_v_reilly/archive/2007/03/06/img-srchttpwwwcodegenerationnetlogosnveloc.aspx
Okay - So I'm managed to get something working but it is a bit of a hack and isn't anywhere near a solution that I want, but it got something working.
Basically, I manually load in the template into a string then pass that string to the velocityEngine.Evaluate() method which writes the result into the the given StringWriter. The side effect of this is that the #parse instructions in the template don't work because it still cannot find the files.
using (StringWriter writer = new StringWriter())
{
velocityEngine.Evaluate(context, writer, templateName, template);
return writer.ToString();
}
In the code above templateName is irrelevant as it isn't used. template is the string that contains the entire template that has been pre-loaded from disk.
I'd still appreciate any better solutions as I really don't like this.
The tests are the ultimate authority:
http://fisheye2.atlassian.com/browse/castleproject/NVelocity/trunk/src/NVelocity.Tests/Test/ParserTest.cs?r=6005#l122
Or you could use the TemplateEngine component which is a thin wrapper around NVelocity that makes things easier.

NVelocity -- #parse with embedded resources

I'm generating emails based off embedded NVelocity templates and would like to do something with dynamically included sections. So my embedded resources are something like this:
DigestMail.vm
_Document.vm
_ActionItem.vm
_Event.vm
My email routine will get a list of objects and will pass each of these along with the proper view to DigestMail.vm:
public struct ItemAndView
{
public string View;
public object Item;
}
private void GenerateWeeklyEmail(INewItems[] newestItems)
{
IList<ItemAndView> itemAndViews = new List<ItemAndView>();
foreach (var item in newestItems)
{
itemAndViews.Add(new ItemAndView
{
View = string.Format("MyAssembly.MailTemplates._{0}.vm", item.GetType().Name),
Item = item
});
}
var context = new Dictionary<string, object>();
context["Recipient"] = _user;
context["Items"] = itemAndViews;
string mailBody = _templater.Merge("MyAssembly.MailTemplates.DigestMail.vm", context);
}
And in my DigestMail.vm template I've got something like this:
#foreach($Item in $Items)
====================================================================
#parse($Item.viewname)
#end
But it's unable to #parse when given the path to an embedded resource like this. Is there any way I can tell it to parse each of these embedded templates?
Hey Jake, is .viewname a property? I'm not seeing you setting it in your code, how about you use the following:
#foreach($Item in $Items)
====================================================================
$Item.viewname
#end
I don't know why you're parsing the $Item.viename rather than just using the above? I'm suggesting this as I've just never needed to parse anything!
Please refer to this post where we've discussed the generation of templates.
Hope this helps!

Resources