Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Undefined method 'getAttribute'. #1076

Closed
juanyves opened this issue Apr 4, 2020 · 2 comments
Closed

Undefined method 'getAttribute'. #1076

juanyves opened this issue Apr 4, 2020 · 2 comments

Comments

@juanyves
Copy link

juanyves commented Apr 4, 2020

Intelephense doesn't recognize the getAttribute method for a DOM object

To Reproduce

<?php $html = "<figure class='thumbnail '><span class='ACrL3ZACrpZGVvL3BsYXllcl9nZW5fY21lZGlhPTE5NDM2NzcwJmNmaWxtPTkyODYuaHRtbA== thumbnail-container thumbnail-link' title='xxxxxxxx'><img class='thumbnail-img' src='http://site.com/path/xxxx.jpg' alt='xxxxxx' width='216' height='288' /></span></figure>?>";

$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$src = $xpath->query("//*[@class='thumbnail-img']")->item(0)->getAttribute('src');

{
"resource": "/path/test5.php",
"owner": "generated_diagnostic_collection_name#2",
"code": "1013",
"severity": 8,
"message": "Undefined method 'getAttribute'.",
"source": "intelephense",
"startLineNumber": 30,
"startColumn": 67,
"endLineNumber": 30,
"endColumn": 79
}

Platform and version
win10

@KapitanOczywisty
Copy link
Contributor

By documentation: DOMXPath->query() returns DOMNodeList and DOMNodeList->item() returns DOMNode which doesn't have getAttribute. Sometimes that DOMNode is DOMElement, but this cannot be hardcoded in every case.

Possible solutions:

A) Get src directly

$src = $xpath->evaluate("string(//*[@class='thumbnail-img']/@src)");

B) Force type with phpdoc

/** @var DOMElement $element */
$element = $xpath->query("//*[@class='thumbnail-img']")->item(0);
$src = $element->getAttribute('src');

C) Add .phpstorm.meta.php file somewhere in workspace. With that all DOMNodeList->item() will show DOMElement as returned type

<?php
namespace PHPSTORM_META {
  override(\DOMNodeList::item(0), map(['' => \DOMElement::class]));
}

@bmewburn
Copy link
Owner

bmewburn commented Apr 5, 2020

Closing, this is working as designed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants