repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6 values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1 value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.toggleClass | public function toggleClass($classname)
{
$classes = explode(' ', $classname);
foreach ($this as $i => $node) {
$c = self::create($node);
/** @var \DOMNode $node */
foreach ($classes as $class) {
if ($c->hasClass($class)) {
$c->removeClass($class);
} else {
$c->addClass($class);
}
}
}
return $this;
} | php | public function toggleClass($classname)
{
$classes = explode(' ', $classname);
foreach ($this as $i => $node) {
$c = self::create($node);
/** @var \DOMNode $node */
foreach ($classes as $class) {
if ($c->hasClass($class)) {
$c->removeClass($class);
} else {
$c->addClass($class);
}
}
}
return $this;
} | [
"public",
"function",
"toggleClass",
"(",
"$",
"classname",
")",
"{",
"$",
"classes",
"=",
"explode",
"(",
"' '",
",",
"$",
"classname",
")",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"i",
"=>",
"$",
"node",
")",
"{",
"$",
"c",
"=",
"self",
":... | Add or remove one or more classes from each element in the set of matched elements, depending the class’s presence.
@param string $classname One or more classnames separated by spaces
@return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
@api | [
"Add",
"or",
"remove",
"one",
"or",
"more",
"classes",
"from",
"each",
"element",
"in",
"the",
"set",
"of",
"matched",
"elements",
"depending",
"the",
"class’s",
"presence",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L662-L677 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.unwrap | public function unwrap()
{
$parents = array();
foreach($this as $i => $node) {
$parents[] = $node->parentNode;
}
self::create($parents)->unwrapInner();
return $this;
} | php | public function unwrap()
{
$parents = array();
foreach($this as $i => $node) {
$parents[] = $node->parentNode;
}
self::create($parents)->unwrapInner();
return $this;
} | [
"public",
"function",
"unwrap",
"(",
")",
"{",
"$",
"parents",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"i",
"=>",
"$",
"node",
")",
"{",
"$",
"parents",
"[",
"]",
"=",
"$",
"node",
"->",
"parentNode",
";",
"}",
"sel... | Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.
@return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
@api | [
"Remove",
"the",
"parents",
"of",
"the",
"set",
"of",
"matched",
"elements",
"from",
"the",
"DOM",
"leaving",
"the",
"matched",
"elements",
"in",
"their",
"place",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L685-L694 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.unwrapInner | public function unwrapInner()
{
foreach($this as $i => $node) {
if (!$node->parentNode instanceof \DOMElement) {
throw new \InvalidArgumentException('DOMElement does not have a parent DOMElement node.');
}
/** @var \DOMNode[] $children */
$children = iterator_to_array($node->childNodes);
foreach ($children as $child) {
$node->parentNode->insertBefore($child, $node);
}
$node->parentNode->removeChild($node);
}
} | php | public function unwrapInner()
{
foreach($this as $i => $node) {
if (!$node->parentNode instanceof \DOMElement) {
throw new \InvalidArgumentException('DOMElement does not have a parent DOMElement node.');
}
/** @var \DOMNode[] $children */
$children = iterator_to_array($node->childNodes);
foreach ($children as $child) {
$node->parentNode->insertBefore($child, $node);
}
$node->parentNode->removeChild($node);
}
} | [
"public",
"function",
"unwrapInner",
"(",
")",
"{",
"foreach",
"(",
"$",
"this",
"as",
"$",
"i",
"=>",
"$",
"node",
")",
"{",
"if",
"(",
"!",
"$",
"node",
"->",
"parentNode",
"instanceof",
"\\",
"DOMElement",
")",
"{",
"throw",
"new",
"\\",
"InvalidA... | Remove the matched elements, but promote the children to take their place.
@return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
@api | [
"Remove",
"the",
"matched",
"elements",
"but",
"promote",
"the",
"children",
"to",
"take",
"their",
"place",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L702-L717 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.wrap | public function wrap($wrappingElement)
{
$content = self::create($wrappingElement);
$newnodes = array();
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
$newnode = $content->getNode(0);
/** @var \DOMNode $newnode */
// $newnode = static::importNewnode($newnode, $node, $i);
if ($newnode->ownerDocument !== $node->ownerDocument) {
$newnode = $node->ownerDocument->importNode($newnode, true);
} else {
if ($i > 0) {
$newnode = $newnode->cloneNode(true);
}
}
$oldnode = $node->parentNode->replaceChild($newnode, $node);
while ($newnode->hasChildNodes()) {
$elementFound = false;
foreach ($newnode->childNodes as $child) {
if ($child instanceof \DOMElement) {
$newnode = $child;
$elementFound = true;
break;
}
}
if (!$elementFound) {
break;
}
}
$newnode->appendChild($oldnode);
$newnodes[] = $newnode;
}
$content->clear();
$content->add($newnodes);
return $this;
} | php | public function wrap($wrappingElement)
{
$content = self::create($wrappingElement);
$newnodes = array();
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
$newnode = $content->getNode(0);
/** @var \DOMNode $newnode */
// $newnode = static::importNewnode($newnode, $node, $i);
if ($newnode->ownerDocument !== $node->ownerDocument) {
$newnode = $node->ownerDocument->importNode($newnode, true);
} else {
if ($i > 0) {
$newnode = $newnode->cloneNode(true);
}
}
$oldnode = $node->parentNode->replaceChild($newnode, $node);
while ($newnode->hasChildNodes()) {
$elementFound = false;
foreach ($newnode->childNodes as $child) {
if ($child instanceof \DOMElement) {
$newnode = $child;
$elementFound = true;
break;
}
}
if (!$elementFound) {
break;
}
}
$newnode->appendChild($oldnode);
$newnodes[] = $newnode;
}
$content->clear();
$content->add($newnodes);
return $this;
} | [
"public",
"function",
"wrap",
"(",
"$",
"wrappingElement",
")",
"{",
"$",
"content",
"=",
"self",
"::",
"create",
"(",
"$",
"wrappingElement",
")",
";",
"$",
"newnodes",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"this",
"as",
"$",
"i",
"=>",
... | Wrap an HTML structure around each element in the set of matched elements
The HTML structure must contain only one root node, e.g.:
Works: <div><div></div></div>
Does not work: <div></div><div></div>
@param string|HtmlPageCrawler|\DOMNode $wrappingElement
@return HtmlPageCrawler $this for chaining
@api | [
"Wrap",
"an",
"HTML",
"structure",
"around",
"each",
"element",
"in",
"the",
"set",
"of",
"matched",
"elements"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L731-L767 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.wrapAll | public function wrapAll($content)
{
$content = self::create($content);
$parent = $this->getNode(0)->parentNode;
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
if ($node->parentNode !== $parent) {
throw new \LogicException('Nodes to be wrapped with wrapAll() must all have the same parent');
}
}
$newnode = $content->getNode(0);
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $parent);
$newnode = $parent->insertBefore($newnode,$this->getNode(0));
$content->clear();
$content->add($newnode);
while ($newnode->hasChildNodes()) {
$elementFound = false;
foreach ($newnode->childNodes as $child) {
if ($child instanceof \DOMElement) {
$newnode = $child;
$elementFound = true;
break;
}
}
if (!$elementFound) {
break;
}
}
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
$newnode->appendChild($node);
}
return $this;
} | php | public function wrapAll($content)
{
$content = self::create($content);
$parent = $this->getNode(0)->parentNode;
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
if ($node->parentNode !== $parent) {
throw new \LogicException('Nodes to be wrapped with wrapAll() must all have the same parent');
}
}
$newnode = $content->getNode(0);
/** @var \DOMNode $newnode */
$newnode = static::importNewnode($newnode, $parent);
$newnode = $parent->insertBefore($newnode,$this->getNode(0));
$content->clear();
$content->add($newnode);
while ($newnode->hasChildNodes()) {
$elementFound = false;
foreach ($newnode->childNodes as $child) {
if ($child instanceof \DOMElement) {
$newnode = $child;
$elementFound = true;
break;
}
}
if (!$elementFound) {
break;
}
}
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
$newnode->appendChild($node);
}
return $this;
} | [
"public",
"function",
"wrapAll",
"(",
"$",
"content",
")",
"{",
"$",
"content",
"=",
"self",
"::",
"create",
"(",
"$",
"content",
")",
";",
"$",
"parent",
"=",
"$",
"this",
"->",
"getNode",
"(",
"0",
")",
"->",
"parentNode",
";",
"foreach",
"(",
"$... | Wrap an HTML structure around all elements in the set of matched elements.
@param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content
@throws \LogicException
@return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
@api | [
"Wrap",
"an",
"HTML",
"structure",
"around",
"all",
"elements",
"in",
"the",
"set",
"of",
"matched",
"elements",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L777-L814 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.wrapInner | public function wrapInner($content)
{
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
self::create($node->childNodes)->wrapAll($content);
}
return $this;
} | php | public function wrapInner($content)
{
foreach ($this as $i => $node) {
/** @var \DOMNode $node */
self::create($node->childNodes)->wrapAll($content);
}
return $this;
} | [
"public",
"function",
"wrapInner",
"(",
"$",
"content",
")",
"{",
"foreach",
"(",
"$",
"this",
"as",
"$",
"i",
"=>",
"$",
"node",
")",
"{",
"/** @var \\DOMNode $node */",
"self",
"::",
"create",
"(",
"$",
"node",
"->",
"childNodes",
")",
"->",
"wrapAll",... | Wrap an HTML structure around the content of each element in the set of matched elements.
@param string|HtmlPageCrawler|\DOMNode|\DOMNodeList $content
@return \Wa72\HtmlPageDom\HtmlPageCrawler $this for chaining
@api | [
"Wrap",
"an",
"HTML",
"structure",
"around",
"the",
"content",
"of",
"each",
"element",
"in",
"the",
"set",
"of",
"matched",
"elements",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L823-L830 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.saveHTML | public function saveHTML()
{
if ($this->isHtmlDocument()) {
return $this->getDOMDocument()->saveHTML();
} else {
$doc = new \DOMDocument('1.0', 'UTF-8');
$root = $doc->appendChild($doc->createElement('_root'));
foreach ($this as $node) {
$root->appendChild($doc->importNode($node, true));
}
$html = trim($doc->saveHTML());
return preg_replace('@^<'.self::FRAGMENT_ROOT_TAGNAME.'[^>]*>|</'.self::FRAGMENT_ROOT_TAGNAME.'>$@', '', $html);
}
} | php | public function saveHTML()
{
if ($this->isHtmlDocument()) {
return $this->getDOMDocument()->saveHTML();
} else {
$doc = new \DOMDocument('1.0', 'UTF-8');
$root = $doc->appendChild($doc->createElement('_root'));
foreach ($this as $node) {
$root->appendChild($doc->importNode($node, true));
}
$html = trim($doc->saveHTML());
return preg_replace('@^<'.self::FRAGMENT_ROOT_TAGNAME.'[^>]*>|</'.self::FRAGMENT_ROOT_TAGNAME.'>$@', '', $html);
}
} | [
"public",
"function",
"saveHTML",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isHtmlDocument",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getDOMDocument",
"(",
")",
"->",
"saveHTML",
"(",
")",
";",
"}",
"else",
"{",
"$",
"doc",
"=",
"new",... | Get the HTML code fragment of all elements and their contents.
If the first node contains a complete HTML document return only
the full code of this document.
@return string HTML code (fragment)
@api | [
"Get",
"the",
"HTML",
"code",
"fragment",
"of",
"all",
"elements",
"and",
"their",
"contents",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L841-L854 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.isHtmlDocument | public function isHtmlDocument()
{
$node = $this->getNode(0);
if ($node instanceof \DOMElement
&& $node->ownerDocument instanceof \DOMDocument
&& $node->ownerDocument->documentElement === $node
&& $node->nodeName == 'html'
) {
return true;
} else {
return false;
}
} | php | public function isHtmlDocument()
{
$node = $this->getNode(0);
if ($node instanceof \DOMElement
&& $node->ownerDocument instanceof \DOMDocument
&& $node->ownerDocument->documentElement === $node
&& $node->nodeName == 'html'
) {
return true;
} else {
return false;
}
} | [
"public",
"function",
"isHtmlDocument",
"(",
")",
"{",
"$",
"node",
"=",
"$",
"this",
"->",
"getNode",
"(",
"0",
")",
";",
"if",
"(",
"$",
"node",
"instanceof",
"\\",
"DOMElement",
"&&",
"$",
"node",
"->",
"ownerDocument",
"instanceof",
"\\",
"DOMDocumen... | checks whether the first node contains a complete html document
(as opposed to a document fragment)
@return boolean | [
"checks",
"whether",
"the",
"first",
"node",
"contains",
"a",
"complete",
"html",
"document",
"(",
"as",
"opposed",
"to",
"a",
"document",
"fragment",
")"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L867-L879 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.getDOMDocument | public function getDOMDocument()
{
$node = $this->getNode(0);
$r = null;
if ($node instanceof \DOMElement
&& $node->ownerDocument instanceof \DOMDocument
) {
$r = $node->ownerDocument;
}
return $r;
} | php | public function getDOMDocument()
{
$node = $this->getNode(0);
$r = null;
if ($node instanceof \DOMElement
&& $node->ownerDocument instanceof \DOMDocument
) {
$r = $node->ownerDocument;
}
return $r;
} | [
"public",
"function",
"getDOMDocument",
"(",
")",
"{",
"$",
"node",
"=",
"$",
"this",
"->",
"getNode",
"(",
"0",
")",
";",
"$",
"r",
"=",
"null",
";",
"if",
"(",
"$",
"node",
"instanceof",
"\\",
"DOMElement",
"&&",
"$",
"node",
"->",
"ownerDocument",... | get ownerDocument of the first element
@return \DOMDocument|null | [
"get",
"ownerDocument",
"of",
"the",
"first",
"element"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L886-L896 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.addContent | public function addContent($content, $type = null)
{
if (empty($type)) {
$type = 'text/html;charset=UTF-8';
}
if (substr($type, 0, 9) == 'text/html' && !preg_match('/<html\b[^>]*>/i', $content)) {
// string contains no <html> Tag => no complete document but an HTML fragment!
$this->addHtmlFragment($content);
} else {
parent::addContent($content, $type);
}
} | php | public function addContent($content, $type = null)
{
if (empty($type)) {
$type = 'text/html;charset=UTF-8';
}
if (substr($type, 0, 9) == 'text/html' && !preg_match('/<html\b[^>]*>/i', $content)) {
// string contains no <html> Tag => no complete document but an HTML fragment!
$this->addHtmlFragment($content);
} else {
parent::addContent($content, $type);
}
} | [
"public",
"function",
"addContent",
"(",
"$",
"content",
",",
"$",
"type",
"=",
"null",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"type",
")",
")",
"{",
"$",
"type",
"=",
"'text/html;charset=UTF-8'",
";",
"}",
"if",
"(",
"substr",
"(",
"$",
"type",
"... | Adds HTML/XML content to the HtmlPageCrawler object (but not to the DOM of an already attached node).
Function overriden from Crawler because HTML fragments are always added as complete documents there
@param string $content A string to parse as HTML/XML
@param null|string $type The content type of the string
@return null|void | [
"Adds",
"HTML",
"/",
"XML",
"content",
"to",
"the",
"HtmlPageCrawler",
"object",
"(",
"but",
"not",
"to",
"the",
"DOM",
"of",
"an",
"already",
"attached",
"node",
")",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L934-L945 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.add | public function add($node)
{
if ($node instanceof Crawler) {
foreach ($node as $childnode) {
$this->addNode($childnode);
}
} else {
parent::add($node);
}
} | php | public function add($node)
{
if ($node instanceof Crawler) {
foreach ($node as $childnode) {
$this->addNode($childnode);
}
} else {
parent::add($node);
}
} | [
"public",
"function",
"add",
"(",
"$",
"node",
")",
"{",
"if",
"(",
"$",
"node",
"instanceof",
"Crawler",
")",
"{",
"foreach",
"(",
"$",
"node",
"as",
"$",
"childnode",
")",
"{",
"$",
"this",
"->",
"addNode",
"(",
"$",
"childnode",
")",
";",
"}",
... | Adds a node to the current list of nodes.
This method uses the appropriate specialized add*() method based
on the type of the argument.
Overwritten from parent to allow Crawler to be added
@param null|\DOMNodeList|array|\DOMNode|Crawler $node A node
@api | [
"Adds",
"a",
"node",
"to",
"the",
"current",
"list",
"of",
"nodes",
"."
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L1020-L1029 |
wasinger/htmlpagedom | src/HtmlPageCrawler.php | HtmlPageCrawler.isDisconnected | public function isDisconnected()
{
$parent = $this->getNode(0)->parentNode;
return ($parent == null || $parent->tagName == self::FRAGMENT_ROOT_TAGNAME);
} | php | public function isDisconnected()
{
$parent = $this->getNode(0)->parentNode;
return ($parent == null || $parent->tagName == self::FRAGMENT_ROOT_TAGNAME);
} | [
"public",
"function",
"isDisconnected",
"(",
")",
"{",
"$",
"parent",
"=",
"$",
"this",
"->",
"getNode",
"(",
"0",
")",
"->",
"parentNode",
";",
"return",
"(",
"$",
"parent",
"==",
"null",
"||",
"$",
"parent",
"->",
"tagName",
"==",
"self",
"::",
"FR... | Checks whether the first node in the set is disconnected (has no parent node)
@return bool | [
"Checks",
"whether",
"the",
"first",
"node",
"in",
"the",
"set",
"is",
"disconnected",
"(",
"has",
"no",
"parent",
"node",
")"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPageCrawler.php#L1054-L1058 |
wasinger/htmlpagedom | src/HtmlPage.php | HtmlPage.setTitle | public function setTitle($title)
{
$t = $this->dom->getElementsByTagName('title')->item(0);
if ($t == null) {
$t = $this->dom->createElement('title');
$this->getHeadNode()->appendChild($t);
}
$t->nodeValue = htmlspecialchars($title);
} | php | public function setTitle($title)
{
$t = $this->dom->getElementsByTagName('title')->item(0);
if ($t == null) {
$t = $this->dom->createElement('title');
$this->getHeadNode()->appendChild($t);
}
$t->nodeValue = htmlspecialchars($title);
} | [
"public",
"function",
"setTitle",
"(",
"$",
"title",
")",
"{",
"$",
"t",
"=",
"$",
"this",
"->",
"dom",
"->",
"getElementsByTagName",
"(",
"'title'",
")",
"->",
"item",
"(",
"0",
")",
";",
"if",
"(",
"$",
"t",
"==",
"null",
")",
"{",
"$",
"t",
... | Sets the page title of the HTML document
@param string $title | [
"Sets",
"the",
"page",
"title",
"of",
"the",
"HTML",
"document"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPage.php#L92-L100 |
wasinger/htmlpagedom | src/HtmlPage.php | HtmlPage.getTitle | public function getTitle()
{
$t = $this->dom->getElementsByTagName('title')->item(0);
if ($t == null) {
return null;
} else {
return $t->nodeValue;
}
} | php | public function getTitle()
{
$t = $this->dom->getElementsByTagName('title')->item(0);
if ($t == null) {
return null;
} else {
return $t->nodeValue;
}
} | [
"public",
"function",
"getTitle",
"(",
")",
"{",
"$",
"t",
"=",
"$",
"this",
"->",
"dom",
"->",
"getElementsByTagName",
"(",
"'title'",
")",
"->",
"item",
"(",
"0",
")",
";",
"if",
"(",
"$",
"t",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}"... | Get the page title of the HTML document
@return null|string | [
"Get",
"the",
"page",
"title",
"of",
"the",
"HTML",
"document"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPage.php#L107-L115 |
wasinger/htmlpagedom | src/HtmlPage.php | HtmlPage.setMeta | public function setMeta($name, $content)
{
$c = $this->filterXPath('descendant-or-self::meta[@name = \'' . $name . '\']');
if (count($c) == 0) {
$node = $this->dom->createElement('meta');
$node->setAttribute('name', $name);
$this->getHeadNode()->appendChild($node);
$c->addNode($node);
}
$c->setAttribute('content', $content);
} | php | public function setMeta($name, $content)
{
$c = $this->filterXPath('descendant-or-self::meta[@name = \'' . $name . '\']');
if (count($c) == 0) {
$node = $this->dom->createElement('meta');
$node->setAttribute('name', $name);
$this->getHeadNode()->appendChild($node);
$c->addNode($node);
}
$c->setAttribute('content', $content);
} | [
"public",
"function",
"setMeta",
"(",
"$",
"name",
",",
"$",
"content",
")",
"{",
"$",
"c",
"=",
"$",
"this",
"->",
"filterXPath",
"(",
"'descendant-or-self::meta[@name = \\''",
".",
"$",
"name",
".",
"'\\']'",
")",
";",
"if",
"(",
"count",
"(",
"$",
"... | Set a META tag with specified 'name' and 'content' attributes
@TODO: add support for multiple meta tags with the same name but different languages
@param $name
@param $content | [
"Set",
"a",
"META",
"tag",
"with",
"specified",
"name",
"and",
"content",
"attributes"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPage.php#L125-L135 |
wasinger/htmlpagedom | src/HtmlPage.php | HtmlPage.getMeta | public function getMeta($name)
{
$node = $this->filterXPath('descendant-or-self::meta[@name = \'' . $name . '\']')->getNode(0);
if ($node instanceof \DOMElement) {
return $node->getAttribute('content');
} else {
return null;
}
} | php | public function getMeta($name)
{
$node = $this->filterXPath('descendant-or-self::meta[@name = \'' . $name . '\']')->getNode(0);
if ($node instanceof \DOMElement) {
return $node->getAttribute('content');
} else {
return null;
}
} | [
"public",
"function",
"getMeta",
"(",
"$",
"name",
")",
"{",
"$",
"node",
"=",
"$",
"this",
"->",
"filterXPath",
"(",
"'descendant-or-self::meta[@name = \\''",
".",
"$",
"name",
".",
"'\\']'",
")",
"->",
"getNode",
"(",
"0",
")",
";",
"if",
"(",
"$",
"... | Get the content attribute of a meta tag with the specified name attribute
@param string $name
@return null|string | [
"Get",
"the",
"content",
"attribute",
"of",
"a",
"meta",
"tag",
"with",
"the",
"specified",
"name",
"attribute"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPage.php#L154-L162 |
wasinger/htmlpagedom | src/HtmlPage.php | HtmlPage.setBaseHref | public function setBaseHref($url)
{
$node = $this->filterXPath('descendant-or-self::base')->getNode(0);
if ($node == null) {
$node = $this->dom->createElement('base');
$this->getHeadNode()->appendChild($node);
}
$node->setAttribute('href', $url);
} | php | public function setBaseHref($url)
{
$node = $this->filterXPath('descendant-or-self::base')->getNode(0);
if ($node == null) {
$node = $this->dom->createElement('base');
$this->getHeadNode()->appendChild($node);
}
$node->setAttribute('href', $url);
} | [
"public",
"function",
"setBaseHref",
"(",
"$",
"url",
")",
"{",
"$",
"node",
"=",
"$",
"this",
"->",
"filterXPath",
"(",
"'descendant-or-self::base'",
")",
"->",
"getNode",
"(",
"0",
")",
";",
"if",
"(",
"$",
"node",
"==",
"null",
")",
"{",
"$",
"nod... | Set the base tag with href attribute set to parameter $url
@param string $url | [
"Set",
"the",
"base",
"tag",
"with",
"href",
"attribute",
"set",
"to",
"parameter",
"$url"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPage.php#L169-L177 |
wasinger/htmlpagedom | src/HtmlPage.php | HtmlPage.getBaseHref | public function getBaseHref()
{
$node = $this->filterXPath('descendant-or-self::base')->getNode(0);
if ($node instanceof \DOMElement) {
return $node->getAttribute('href');
} else {
return null;
}
} | php | public function getBaseHref()
{
$node = $this->filterXPath('descendant-or-self::base')->getNode(0);
if ($node instanceof \DOMElement) {
return $node->getAttribute('href');
} else {
return null;
}
} | [
"public",
"function",
"getBaseHref",
"(",
")",
"{",
"$",
"node",
"=",
"$",
"this",
"->",
"filterXPath",
"(",
"'descendant-or-self::base'",
")",
"->",
"getNode",
"(",
"0",
")",
";",
"if",
"(",
"$",
"node",
"instanceof",
"\\",
"DOMElement",
")",
"{",
"retu... | Get the href attribute from the base tag, null if not present in document
@return null|string | [
"Get",
"the",
"href",
"attribute",
"from",
"the",
"base",
"tag",
"null",
"if",
"not",
"present",
"in",
"document"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPage.php#L184-L192 |
wasinger/htmlpagedom | src/HtmlPage.php | HtmlPage.getHeadNode | public function getHeadNode()
{
$head = $this->dom->getElementsByTagName('head')->item(0);
if ($head == null) {
$head = $this->dom->createElement('head');
$head = $this->dom->documentElement->insertBefore($head, $this->getBodyNode());
}
return $head;
} | php | public function getHeadNode()
{
$head = $this->dom->getElementsByTagName('head')->item(0);
if ($head == null) {
$head = $this->dom->createElement('head');
$head = $this->dom->documentElement->insertBefore($head, $this->getBodyNode());
}
return $head;
} | [
"public",
"function",
"getHeadNode",
"(",
")",
"{",
"$",
"head",
"=",
"$",
"this",
"->",
"dom",
"->",
"getElementsByTagName",
"(",
"'head'",
")",
"->",
"item",
"(",
"0",
")",
";",
"if",
"(",
"$",
"head",
"==",
"null",
")",
"{",
"$",
"head",
"=",
... | Get the document's HEAD section as DOMElement
@return \DOMElement | [
"Get",
"the",
"document",
"s",
"HEAD",
"section",
"as",
"DOMElement"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPage.php#L210-L218 |
wasinger/htmlpagedom | src/HtmlPage.php | HtmlPage.getBodyNode | public function getBodyNode()
{
$body = $this->dom->getElementsByTagName('body')->item(0);
if ($body == null) {
$body = $this->dom->createElement('body');
$body = $this->dom->documentElement->appendChild($body);
}
return $body;
} | php | public function getBodyNode()
{
$body = $this->dom->getElementsByTagName('body')->item(0);
if ($body == null) {
$body = $this->dom->createElement('body');
$body = $this->dom->documentElement->appendChild($body);
}
return $body;
} | [
"public",
"function",
"getBodyNode",
"(",
")",
"{",
"$",
"body",
"=",
"$",
"this",
"->",
"dom",
"->",
"getElementsByTagName",
"(",
"'body'",
")",
"->",
"item",
"(",
"0",
")",
";",
"if",
"(",
"$",
"body",
"==",
"null",
")",
"{",
"$",
"body",
"=",
... | Get the document's body as DOMElement
@return \DOMElement | [
"Get",
"the",
"document",
"s",
"body",
"as",
"DOMElement"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPage.php#L225-L233 |
wasinger/htmlpagedom | src/HtmlPage.php | HtmlPage.minify | public function minify(array $options = array())
{
if (!class_exists('Wa72\\HtmlPrettymin\\PrettyMin')) {
throw new \Exception('Function minify needs composer package wa72/html-pretty-min');
}
$pm = new PrettyMin($options);
$pm->load($this->dom)->minify();
return $this;
} | php | public function minify(array $options = array())
{
if (!class_exists('Wa72\\HtmlPrettymin\\PrettyMin')) {
throw new \Exception('Function minify needs composer package wa72/html-pretty-min');
}
$pm = new PrettyMin($options);
$pm->load($this->dom)->minify();
return $this;
} | [
"public",
"function",
"minify",
"(",
"array",
"$",
"options",
"=",
"array",
"(",
")",
")",
"{",
"if",
"(",
"!",
"class_exists",
"(",
"'Wa72\\\\HtmlPrettymin\\\\PrettyMin'",
")",
")",
"{",
"throw",
"new",
"\\",
"Exception",
"(",
"'Function minify needs composer p... | minify the HTML document
@param array $options Options passed to PrettyMin::__construct()
@return HtmlPage
@throws \Exception | [
"minify",
"the",
"HTML",
"document"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/HtmlPage.php#L336-L344 |
wasinger/htmlpagedom | src/Helpers.php | Helpers.trimNewlines | public static function trimNewlines($string)
{
$string = str_replace("\n", ' ', $string);
$string = str_replace("\r", ' ', $string);
$string = preg_replace('/\s+/', ' ', $string);
return trim($string);
} | php | public static function trimNewlines($string)
{
$string = str_replace("\n", ' ', $string);
$string = str_replace("\r", ' ', $string);
$string = preg_replace('/\s+/', ' ', $string);
return trim($string);
} | [
"public",
"static",
"function",
"trimNewlines",
"(",
"$",
"string",
")",
"{",
"$",
"string",
"=",
"str_replace",
"(",
"\"\\n\"",
",",
"' '",
",",
"$",
"string",
")",
";",
"$",
"string",
"=",
"str_replace",
"(",
"\"\\r\"",
",",
"' '",
",",
"$",
"string"... | remove newlines from string and minimize whitespace (multiple whitespace characters replaced by one space)
useful for cleaning up text retrieved by HtmlPageCrawler::text() (nodeValue of a DOMNode)
@param string $string
@return string | [
"remove",
"newlines",
"from",
"string",
"and",
"minimize",
"whitespace",
"(",
"multiple",
"whitespace",
"characters",
"replaced",
"by",
"one",
"space",
")",
"useful",
"for",
"cleaning",
"up",
"text",
"retrieved",
"by",
"HtmlPageCrawler",
"::",
"text",
"()",
"(",... | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/Helpers.php#L18-L24 |
wasinger/htmlpagedom | src/Helpers.php | Helpers.cssStringToArray | public static function cssStringToArray($css)
{
$statements = explode(';', preg_replace('/\s+/s', ' ', $css));
$styles = array();
foreach ($statements as $statement) {
$statement = trim($statement);
if ('' === $statement) {
continue;
}
$p = strpos($statement, ':');
if ($p <= 0) {
continue;
} // invalid statement, just ignore it
$key = trim(substr($statement, 0, $p));
$value = trim(substr($statement, $p + 1));
$styles[$key] = $value;
}
return $styles;
} | php | public static function cssStringToArray($css)
{
$statements = explode(';', preg_replace('/\s+/s', ' ', $css));
$styles = array();
foreach ($statements as $statement) {
$statement = trim($statement);
if ('' === $statement) {
continue;
}
$p = strpos($statement, ':');
if ($p <= 0) {
continue;
} // invalid statement, just ignore it
$key = trim(substr($statement, 0, $p));
$value = trim(substr($statement, $p + 1));
$styles[$key] = $value;
}
return $styles;
} | [
"public",
"static",
"function",
"cssStringToArray",
"(",
"$",
"css",
")",
"{",
"$",
"statements",
"=",
"explode",
"(",
"';'",
",",
"preg_replace",
"(",
"'/\\s+/s'",
",",
"' '",
",",
"$",
"css",
")",
")",
";",
"$",
"styles",
"=",
"array",
"(",
")",
";... | Convert CSS string to array
@param string $css list of CSS properties separated by ;
@return array name=>value pairs of CSS properties | [
"Convert",
"CSS",
"string",
"to",
"array"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/Helpers.php#L32-L50 |
wasinger/htmlpagedom | src/Helpers.php | Helpers.getBodyNodeFromHtmlFragment | public static function getBodyNodeFromHtmlFragment($html, $charset = 'UTF-8')
{
$html = '<html><body>' . $html . '</body></html>';
$current = libxml_use_internal_errors(true);
$disableEntities = libxml_disable_entity_loader(true);
$d = new \DOMDocument('1.0', $charset);
$d->validateOnParse = true;
if (function_exists('mb_convert_encoding') && in_array(
strtolower($charset),
array_map('strtolower', mb_list_encodings())
)
) {
$html = mb_convert_encoding($html, 'HTML-ENTITIES', $charset);
}
@$d->loadHTML($html);
libxml_use_internal_errors($current);
libxml_disable_entity_loader($disableEntities);
return $d->getElementsByTagName('body')->item(0);
} | php | public static function getBodyNodeFromHtmlFragment($html, $charset = 'UTF-8')
{
$html = '<html><body>' . $html . '</body></html>';
$current = libxml_use_internal_errors(true);
$disableEntities = libxml_disable_entity_loader(true);
$d = new \DOMDocument('1.0', $charset);
$d->validateOnParse = true;
if (function_exists('mb_convert_encoding') && in_array(
strtolower($charset),
array_map('strtolower', mb_list_encodings())
)
) {
$html = mb_convert_encoding($html, 'HTML-ENTITIES', $charset);
}
@$d->loadHTML($html);
libxml_use_internal_errors($current);
libxml_disable_entity_loader($disableEntities);
return $d->getElementsByTagName('body')->item(0);
} | [
"public",
"static",
"function",
"getBodyNodeFromHtmlFragment",
"(",
"$",
"html",
",",
"$",
"charset",
"=",
"'UTF-8'",
")",
"{",
"$",
"html",
"=",
"'<html><body>'",
".",
"$",
"html",
".",
"'</body></html>'",
";",
"$",
"current",
"=",
"libxml_use_internal_errors",... | Helper function for getting a body element
from an HTML fragment
@param string $html A fragment of HTML code
@param string $charset
@return \DOMNode The body node containing child nodes created from the HTML fragment | [
"Helper",
"function",
"for",
"getting",
"a",
"body",
"element",
"from",
"an",
"HTML",
"fragment"
] | train | https://github.com/wasinger/htmlpagedom/blob/d7b8854f695d30569d16f60d5c2e617b2b49789d/src/Helpers.php#L75-L93 |
Symplify/Statie | packages/Tweeter/src/TwitterApi/TwitterApiWrapper.php | TwitterApiWrapper.publishTweetWithImage | public function publishTweetWithImage(string $status, string $imageFile): void
{
$media = $this->callPost(self::IMAGE_UPLOAD_URL, [
'media' => base64_encode(FileSystem::read($imageFile)),
]);
$this->callPost(self::UPDATE_URL, [
'status' => $status,
'media_ids' => $media['media_id'],
]);
} | php | public function publishTweetWithImage(string $status, string $imageFile): void
{
$media = $this->callPost(self::IMAGE_UPLOAD_URL, [
'media' => base64_encode(FileSystem::read($imageFile)),
]);
$this->callPost(self::UPDATE_URL, [
'status' => $status,
'media_ids' => $media['media_id'],
]);
} | [
"public",
"function",
"publishTweetWithImage",
"(",
"string",
"$",
"status",
",",
"string",
"$",
"imageFile",
")",
":",
"void",
"{",
"$",
"media",
"=",
"$",
"this",
"->",
"callPost",
"(",
"self",
"::",
"IMAGE_UPLOAD_URL",
",",
"[",
"'media'",
"=>",
"base64... | Ref: https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-upload and
https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-update.html "media_ids" | [
"Ref",
":",
"https",
":",
"//",
"developer",
".",
"twitter",
".",
"com",
"/",
"en",
"/",
"docs",
"/",
"media",
"/",
"upload",
"-",
"media",
"/",
"api",
"-",
"reference",
"/",
"post",
"-",
"media",
"-",
"upload",
"and",
"https",
":",
"//",
"develope... | train | https://github.com/Symplify/Statie/blob/32d809bb596a34d292a4cda460dd914cca508496/packages/Tweeter/src/TwitterApi/TwitterApiWrapper.php#L95-L105 |
Symplify/Statie | src/Renderable/RouteFileDecorator.php | RouteFileDecorator.prefixWithDateIfFound | private function prefixWithDateIfFound(AbstractFile $file, string $outputPath): string
{
if ($file->getDate() === null) {
return $outputPath;
}
return str_replace(
[':year', ':month', ':day'],
[$file->getDateInFormat('Y'), $file->getDateInFormat('m'), $file->getDateInFormat('d')],
$outputPath
);
} | php | private function prefixWithDateIfFound(AbstractFile $file, string $outputPath): string
{
if ($file->getDate() === null) {
return $outputPath;
}
return str_replace(
[':year', ':month', ':day'],
[$file->getDateInFormat('Y'), $file->getDateInFormat('m'), $file->getDateInFormat('d')],
$outputPath
);
} | [
"private",
"function",
"prefixWithDateIfFound",
"(",
"AbstractFile",
"$",
"file",
",",
"string",
"$",
"outputPath",
")",
":",
"string",
"{",
"if",
"(",
"$",
"file",
"->",
"getDate",
"(",
")",
"===",
"null",
")",
"{",
"return",
"$",
"outputPath",
";",
"}"... | Only if the date is part of file name | [
"Only",
"if",
"the",
"date",
"is",
"part",
"of",
"file",
"name"
] | train | https://github.com/Symplify/Statie/blob/32d809bb596a34d292a4cda460dd914cca508496/src/Renderable/RouteFileDecorator.php#L114-L125 |
Symplify/Statie | packages/HeadlineAnchorLinker/src/HeadlineAnchorLinker.php | HeadlineAnchorLinker.processContent | public function processContent(string $content): string
{
return Strings::replace($content, self::HEADLINE_PATTERN, function (array $result): string {
$titleWithoutTags = strip_tags($result['title']);
$headlineId = Strings::webalize($titleWithoutTags);
$titleWithLink = Strings::match($result['title'], self::LINK_PATTERN);
$titleHasLink = is_array($titleWithLink) ? count($titleWithLink) > 0 : false;
// Title contains <a> element
if ($result['title'] !== $titleWithoutTags && $titleHasLink) {
return sprintf(
'<h%s id="%s">%s</h%s>',
$result['level'],
$headlineId,
$result['title'],
$result['level']
);
}
return sprintf(
'<h%s id="%s"><a href="#%s" class="heading-anchor">%s</a></h%s>',
$result['level'],
$headlineId,
$headlineId,
$result['title'],
$result['level']
);
});
} | php | public function processContent(string $content): string
{
return Strings::replace($content, self::HEADLINE_PATTERN, function (array $result): string {
$titleWithoutTags = strip_tags($result['title']);
$headlineId = Strings::webalize($titleWithoutTags);
$titleWithLink = Strings::match($result['title'], self::LINK_PATTERN);
$titleHasLink = is_array($titleWithLink) ? count($titleWithLink) > 0 : false;
// Title contains <a> element
if ($result['title'] !== $titleWithoutTags && $titleHasLink) {
return sprintf(
'<h%s id="%s">%s</h%s>',
$result['level'],
$headlineId,
$result['title'],
$result['level']
);
}
return sprintf(
'<h%s id="%s"><a href="#%s" class="heading-anchor">%s</a></h%s>',
$result['level'],
$headlineId,
$headlineId,
$result['title'],
$result['level']
);
});
} | [
"public",
"function",
"processContent",
"(",
"string",
"$",
"content",
")",
":",
"string",
"{",
"return",
"Strings",
"::",
"replace",
"(",
"$",
"content",
",",
"self",
"::",
"HEADLINE_PATTERN",
",",
"function",
"(",
"array",
"$",
"result",
")",
":",
"strin... | Before:
- <h2>Some headline</h2>
After:
- <h2 id="some-headline"><a href="#some-headline" class="heading-anchor">Some headline</a></h2> | [
"Before",
":",
"-",
"<h2",
">",
"Some",
"headline<",
"/",
"h2",
">"
] | train | https://github.com/Symplify/Statie/blob/32d809bb596a34d292a4cda460dd914cca508496/packages/HeadlineAnchorLinker/src/HeadlineAnchorLinker.php#L26-L54 |
Symplify/Statie | src/Console/Command/CreatePostCommand.php | CreatePostCommand.createPostFileName | private function createPostFileName(string $title, GeneratorElement $generatorElement): string
{
$webalizedDate = date('Y-m-d');
$webalizedTitle = Strings::lower(Strings::webalize($title));
$postFileName = sprintf('%s-%s.md', $webalizedDate, $webalizedTitle);
if ($this->createPostFileSystem->isNestedByYear($generatorElement)) {
$year = date('Y');
$postFileName = $year . '/' . $postFileName;
}
return $postFileName;
} | php | private function createPostFileName(string $title, GeneratorElement $generatorElement): string
{
$webalizedDate = date('Y-m-d');
$webalizedTitle = Strings::lower(Strings::webalize($title));
$postFileName = sprintf('%s-%s.md', $webalizedDate, $webalizedTitle);
if ($this->createPostFileSystem->isNestedByYear($generatorElement)) {
$year = date('Y');
$postFileName = $year . '/' . $postFileName;
}
return $postFileName;
} | [
"private",
"function",
"createPostFileName",
"(",
"string",
"$",
"title",
",",
"GeneratorElement",
"$",
"generatorElement",
")",
":",
"string",
"{",
"$",
"webalizedDate",
"=",
"date",
"(",
"'Y-m-d'",
")",
";",
"$",
"webalizedTitle",
"=",
"Strings",
"::",
"lowe... | Returns format based on directory nesting or not:
- 2019-01-01-some-post.md
- 2019/2019-01-01-some-post.md | [
"Returns",
"format",
"based",
"on",
"directory",
"nesting",
"or",
"not",
":"
] | train | https://github.com/Symplify/Statie/blob/32d809bb596a34d292a4cda460dd914cca508496/src/Console/Command/CreatePostCommand.php#L151-L164 |
scotteh/php-goose | src/Traits/NodeGravityTrait.php | NodeGravityTrait.updateScore | private function updateScore(Element $node, float $addToScore): void {
$currentScore = (float)$node->attr('gravityScore');
$node->attr('gravityScore', (string)($currentScore + $addToScore));
} | php | private function updateScore(Element $node, float $addToScore): void {
$currentScore = (float)$node->attr('gravityScore');
$node->attr('gravityScore', (string)($currentScore + $addToScore));
} | [
"private",
"function",
"updateScore",
"(",
"Element",
"$",
"node",
",",
"float",
"$",
"addToScore",
")",
":",
"void",
"{",
"$",
"currentScore",
"=",
"(",
"float",
")",
"$",
"node",
"->",
"attr",
"(",
"'gravityScore'",
")",
";",
"$",
"node",
"->",
"attr... | Adds a score to the gravityScore Attribute we put on divs
we'll get the current score then add the score we're passing in to the current
@param Element $node
@param float $addToScore | [
"Adds",
"a",
"score",
"to",
"the",
"gravityScore",
"Attribute",
"we",
"put",
"on",
"divs",
"we",
"ll",
"get",
"the",
"current",
"score",
"then",
"add",
"the",
"score",
"we",
"re",
"passing",
"in",
"to",
"the",
"current"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Traits/NodeGravityTrait.php#L32-L36 |
scotteh/php-goose | src/Traits/NodeGravityTrait.php | NodeGravityTrait.updateNodeCount | private function updateNodeCount(Element $node, int $addToCount): void {
$currentScore = (int)$node->attr('gravityNodes');
$node->attr('gravityNodes', (string)($currentScore + $addToCount));
} | php | private function updateNodeCount(Element $node, int $addToCount): void {
$currentScore = (int)$node->attr('gravityNodes');
$node->attr('gravityNodes', (string)($currentScore + $addToCount));
} | [
"private",
"function",
"updateNodeCount",
"(",
"Element",
"$",
"node",
",",
"int",
"$",
"addToCount",
")",
":",
"void",
"{",
"$",
"currentScore",
"=",
"(",
"int",
")",
"$",
"node",
"->",
"attr",
"(",
"'gravityNodes'",
")",
";",
"$",
"node",
"->",
"attr... | Stores how many decent nodes are under a parent node
@param Element $node
@param int $addToCount | [
"Stores",
"how",
"many",
"decent",
"nodes",
"are",
"under",
"a",
"parent",
"node"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Traits/NodeGravityTrait.php#L44-L48 |
scotteh/php-goose | src/Modules/Extractors/AdditionalDataExtractor.php | AdditionalDataExtractor.getVideos | private function getVideos(): array {
$videos = [];
$topNode = $this->article()->getTopNode();
if ($topNode instanceof Element && $topNode->parent() instanceof Element) {
$nodes = $topNode->parent()->find('embed, object, iframe, video');
foreach ($nodes as $node) {
if ($node->hasAttribute('src')) {
$src = $node->attr('src');
} else {
$src = $node->attr('data');
}
$match = array_reduce(self::$VIDEO_PROVIDERS, function($match, $domain) use ($src) {
$srcHost = (string)parse_url($src, PHP_URL_HOST);
$srcScheme = (string)parse_url($src, PHP_URL_SCHEME);
return $match || preg_match('@' . $domain . '$@i', $srcHost) && in_array($srcScheme, ['http', 'https']);
});
if (!$match) {
$srcPath = parse_url(strtolower($src), PHP_URL_PATH);
$srcExtension = pathinfo((string)$srcPath, PATHINFO_EXTENSION);
$match = in_array($srcExtension, self::$VIDEO_EXTENSIONS);
}
if ($match) {
$videos[] = $src;
}
}
}
return $videos;
} | php | private function getVideos(): array {
$videos = [];
$topNode = $this->article()->getTopNode();
if ($topNode instanceof Element && $topNode->parent() instanceof Element) {
$nodes = $topNode->parent()->find('embed, object, iframe, video');
foreach ($nodes as $node) {
if ($node->hasAttribute('src')) {
$src = $node->attr('src');
} else {
$src = $node->attr('data');
}
$match = array_reduce(self::$VIDEO_PROVIDERS, function($match, $domain) use ($src) {
$srcHost = (string)parse_url($src, PHP_URL_HOST);
$srcScheme = (string)parse_url($src, PHP_URL_SCHEME);
return $match || preg_match('@' . $domain . '$@i', $srcHost) && in_array($srcScheme, ['http', 'https']);
});
if (!$match) {
$srcPath = parse_url(strtolower($src), PHP_URL_PATH);
$srcExtension = pathinfo((string)$srcPath, PATHINFO_EXTENSION);
$match = in_array($srcExtension, self::$VIDEO_EXTENSIONS);
}
if ($match) {
$videos[] = $src;
}
}
}
return $videos;
} | [
"private",
"function",
"getVideos",
"(",
")",
":",
"array",
"{",
"$",
"videos",
"=",
"[",
"]",
";",
"$",
"topNode",
"=",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getTopNode",
"(",
")",
";",
"if",
"(",
"$",
"topNode",
"instanceof",
"Element",
... | Pulls out videos we like
@return string[] | [
"Pulls",
"out",
"videos",
"we",
"like"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/AdditionalDataExtractor.php#L83-L119 |
scotteh/php-goose | src/Modules/Extractors/AdditionalDataExtractor.php | AdditionalDataExtractor.getLinks | private function getLinks(): array {
$goodLinks = [];
$parentNode = $this->article()->getTopNode()->parent();
if ($parentNode instanceof Element) {
$candidates = $parentNode->find('a[href]');
foreach ($candidates as $el) {
if ($el->attr('href') != '#' && trim($el->attr('href')) != '') {
$goodLinks[] = [
'url' => $el->attr('href'),
'text' => Helper::textNormalise($el->text()),
];
}
}
}
return $goodLinks;
} | php | private function getLinks(): array {
$goodLinks = [];
$parentNode = $this->article()->getTopNode()->parent();
if ($parentNode instanceof Element) {
$candidates = $parentNode->find('a[href]');
foreach ($candidates as $el) {
if ($el->attr('href') != '#' && trim($el->attr('href')) != '') {
$goodLinks[] = [
'url' => $el->attr('href'),
'text' => Helper::textNormalise($el->text()),
];
}
}
}
return $goodLinks;
} | [
"private",
"function",
"getLinks",
"(",
")",
":",
"array",
"{",
"$",
"goodLinks",
"=",
"[",
"]",
";",
"$",
"parentNode",
"=",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getTopNode",
"(",
")",
"->",
"parent",
"(",
")",
";",
"if",
"(",
"$",
"pa... | Pulls out links we like
@return array | [
"Pulls",
"out",
"links",
"we",
"like"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/AdditionalDataExtractor.php#L126-L145 |
scotteh/php-goose | src/Traits/ArticleMutatorTrait.php | ArticleMutatorTrait.article | protected function article(Article $article = null): ?Article {
if ($article === null) {
return $this->article;
}
$this->article = $article;
return $this->article;
} | php | protected function article(Article $article = null): ?Article {
if ($article === null) {
return $this->article;
}
$this->article = $article;
return $this->article;
} | [
"protected",
"function",
"article",
"(",
"Article",
"$",
"article",
"=",
"null",
")",
":",
"?",
"Article",
"{",
"if",
"(",
"$",
"article",
"===",
"null",
")",
"{",
"return",
"$",
"this",
"->",
"article",
";",
"}",
"$",
"this",
"->",
"article",
"=",
... | @param Article $article
@return Article | [
"@param",
"Article",
"$article"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Traits/ArticleMutatorTrait.php#L22-L30 |
scotteh/php-goose | src/Text/StopWords.php | StopWords.getStopwordCount | public function getStopwordCount(string $content): WordStats {
if (empty($content)) {
return new WordStats();
}
$strippedInput = $this->removePunctuation($content);
$candidateWords = $this->getCandidateWords($strippedInput);
$overlappingStopWords = [];
foreach ($candidateWords as $w) {
if (in_array(mb_strtolower($w), $this->getWordList())) {
$overlappingStopWords[] = mb_strtolower($w);
}
}
return new WordStats([
'wordCount' => count($candidateWords),
'stopWordCount' => count($overlappingStopWords),
'stopWords' => $overlappingStopWords,
]);
} | php | public function getStopwordCount(string $content): WordStats {
if (empty($content)) {
return new WordStats();
}
$strippedInput = $this->removePunctuation($content);
$candidateWords = $this->getCandidateWords($strippedInput);
$overlappingStopWords = [];
foreach ($candidateWords as $w) {
if (in_array(mb_strtolower($w), $this->getWordList())) {
$overlappingStopWords[] = mb_strtolower($w);
}
}
return new WordStats([
'wordCount' => count($candidateWords),
'stopWordCount' => count($overlappingStopWords),
'stopWords' => $overlappingStopWords,
]);
} | [
"public",
"function",
"getStopwordCount",
"(",
"string",
"$",
"content",
")",
":",
"WordStats",
"{",
"if",
"(",
"empty",
"(",
"$",
"content",
")",
")",
"{",
"return",
"new",
"WordStats",
"(",
")",
";",
"}",
"$",
"strippedInput",
"=",
"$",
"this",
"->",... | @param string $content
@return WordStats | [
"@param",
"string",
"$content"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Text/StopWords.php#L87-L107 |
scotteh/php-goose | src/Text/StopWords.php | StopWords.getCandidateWords | public function getCandidateWords(string $strippedInput): array {
// Simple separating words in Japanese.
if ($this->getLanguage() === 'ja') {
$regexp = '/(' . implode('|', array_map('preg_quote', $this->getWordList())) . ')/';
$strippedInput = preg_replace($regexp, ' $1 ', $strippedInput);
}
return explode(' ', $strippedInput);
} | php | public function getCandidateWords(string $strippedInput): array {
// Simple separating words in Japanese.
if ($this->getLanguage() === 'ja') {
$regexp = '/(' . implode('|', array_map('preg_quote', $this->getWordList())) . ')/';
$strippedInput = preg_replace($regexp, ' $1 ', $strippedInput);
}
return explode(' ', $strippedInput);
} | [
"public",
"function",
"getCandidateWords",
"(",
"string",
"$",
"strippedInput",
")",
":",
"array",
"{",
"// Simple separating words in Japanese.",
"if",
"(",
"$",
"this",
"->",
"getLanguage",
"(",
")",
"===",
"'ja'",
")",
"{",
"$",
"regexp",
"=",
"'/('",
".",
... | @param string $strippedInput
@return array | [
"@param",
"string",
"$strippedInput"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Text/StopWords.php#L114-L122 |
scotteh/php-goose | src/Modules/Extractors/ContentExtractor.php | ContentExtractor.getTopNodeCandidatesByContents | private function getTopNodeCandidatesByContents(Article $article): array {
$results = [];
$nodes = $article->getDoc()->find('p, td, pre');
foreach ($nodes as $node) {
$wordStats = $this->config()->getStopWords()->getStopwordCount($node->text());
$highLinkDensity = $this->isHighLinkDensity($node);
if ($wordStats->getStopWordCount() > 2 && !$highLinkDensity) {
$results[] = $node;
}
}
return $results;
} | php | private function getTopNodeCandidatesByContents(Article $article): array {
$results = [];
$nodes = $article->getDoc()->find('p, td, pre');
foreach ($nodes as $node) {
$wordStats = $this->config()->getStopWords()->getStopwordCount($node->text());
$highLinkDensity = $this->isHighLinkDensity($node);
if ($wordStats->getStopWordCount() > 2 && !$highLinkDensity) {
$results[] = $node;
}
}
return $results;
} | [
"private",
"function",
"getTopNodeCandidatesByContents",
"(",
"Article",
"$",
"article",
")",
":",
"array",
"{",
"$",
"results",
"=",
"[",
"]",
";",
"$",
"nodes",
"=",
"$",
"article",
"->",
"getDoc",
"(",
")",
"->",
"find",
"(",
"'p, td, pre'",
")",
";",... | @param Article $article
@return array | [
"@param",
"Article",
"$article"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ContentExtractor.php#L33-L48 |
scotteh/php-goose | src/Modules/Extractors/ContentExtractor.php | ContentExtractor.getTopNodeCandidateScore | private function getTopNodeCandidateScore(Element $node, int $i, int $totalNodes): float {
$boostScore = (1.0 / ($i + 1)) * 50;
$bottomNodesForNegativeScore = $totalNodes * 0.25;
if ($totalNodes > 15) {
if ($totalNodes - $i <= $bottomNodesForNegativeScore) {
$booster = $bottomNodesForNegativeScore - ($totalNodes - $i);
$boostScore = pow($booster, 2) * -1;
$negscore = abs($boostScore);
if ($negscore > 40) {
$boostScore = 5;
}
}
}
$wordStats = $this->config()->getStopWords()->getStopwordCount($node->text());
$upscore = $wordStats->getStopWordCount() + $boostScore;
return $upscore;
} | php | private function getTopNodeCandidateScore(Element $node, int $i, int $totalNodes): float {
$boostScore = (1.0 / ($i + 1)) * 50;
$bottomNodesForNegativeScore = $totalNodes * 0.25;
if ($totalNodes > 15) {
if ($totalNodes - $i <= $bottomNodesForNegativeScore) {
$booster = $bottomNodesForNegativeScore - ($totalNodes - $i);
$boostScore = pow($booster, 2) * -1;
$negscore = abs($boostScore);
if ($negscore > 40) {
$boostScore = 5;
}
}
}
$wordStats = $this->config()->getStopWords()->getStopwordCount($node->text());
$upscore = $wordStats->getStopWordCount() + $boostScore;
return $upscore;
} | [
"private",
"function",
"getTopNodeCandidateScore",
"(",
"Element",
"$",
"node",
",",
"int",
"$",
"i",
",",
"int",
"$",
"totalNodes",
")",
":",
"float",
"{",
"$",
"boostScore",
"=",
"(",
"1.0",
"/",
"(",
"$",
"i",
"+",
"1",
")",
")",
"*",
"50",
";",... | @param Element $node
@param int $i
@param int $totalNodes
@return float | [
"@param",
"Element",
"$node",
"@param",
"int",
"$i",
"@param",
"int",
"$totalNodes"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ContentExtractor.php#L57-L76 |
scotteh/php-goose | src/Modules/Extractors/ContentExtractor.php | ContentExtractor.getTopNodeByScore | private function getTopNodeByScore(array $nodes): ?Element {
$topNode = null;
$topNodeScore = 0;
foreach ($nodes as $node) {
$score = $this->getScore($node);
if ($score > $topNodeScore) {
$topNode = $node;
$topNodeScore = $score;
}
if ($topNode === false) {
$topNode = $node;
}
}
if ($topNode && $this->getScore($topNode) < 20) {
return null;
}
return $topNode;
} | php | private function getTopNodeByScore(array $nodes): ?Element {
$topNode = null;
$topNodeScore = 0;
foreach ($nodes as $node) {
$score = $this->getScore($node);
if ($score > $topNodeScore) {
$topNode = $node;
$topNodeScore = $score;
}
if ($topNode === false) {
$topNode = $node;
}
}
if ($topNode && $this->getScore($topNode) < 20) {
return null;
}
return $topNode;
} | [
"private",
"function",
"getTopNodeByScore",
"(",
"array",
"$",
"nodes",
")",
":",
"?",
"Element",
"{",
"$",
"topNode",
"=",
"null",
";",
"$",
"topNodeScore",
"=",
"0",
";",
"foreach",
"(",
"$",
"nodes",
"as",
"$",
"node",
")",
"{",
"$",
"score",
"=",... | @param array $nodes
@return Element|null | [
"@param",
"array",
"$nodes"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ContentExtractor.php#L83-L105 |
scotteh/php-goose | src/Modules/Extractors/ContentExtractor.php | ContentExtractor.calculateBestNodeCandidateScores | private function calculateBestNodeCandidateScores(Element $node, float $upscore): self {
if ($node->parent() instanceof Element) {
$this->updateScore($node->parent(), $upscore);
$this->updateNodeCount($node->parent(), 1);
if ($node->parent()->parent() instanceof Element) {
$this->updateScore($node->parent()->parent(), $upscore / 2);
$this->updateNodeCount($node->parent()->parent(), 1);
}
}
return $this;
} | php | private function calculateBestNodeCandidateScores(Element $node, float $upscore): self {
if ($node->parent() instanceof Element) {
$this->updateScore($node->parent(), $upscore);
$this->updateNodeCount($node->parent(), 1);
if ($node->parent()->parent() instanceof Element) {
$this->updateScore($node->parent()->parent(), $upscore / 2);
$this->updateNodeCount($node->parent()->parent(), 1);
}
}
return $this;
} | [
"private",
"function",
"calculateBestNodeCandidateScores",
"(",
"Element",
"$",
"node",
",",
"float",
"$",
"upscore",
")",
":",
"self",
"{",
"if",
"(",
"$",
"node",
"->",
"parent",
"(",
")",
"instanceof",
"Element",
")",
"{",
"$",
"this",
"->",
"updateScor... | @param Element $node
@param float $upscore
@return self | [
"@param",
"Element",
"$node",
"@param",
"float",
"$upscore"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ContentExtractor.php#L113-L125 |
scotteh/php-goose | src/Modules/Extractors/ContentExtractor.php | ContentExtractor.updateBestNodeCandidates | private function updateBestNodeCandidates(Element $node, array $nodeCandidates): array {
if (!in_array($node->parent(), $nodeCandidates, true)) {
if ($node->parent() instanceof Element) {
$nodeCandidates[] = $node->parent();
}
}
if ($node->parent() instanceof Element) {
if (!in_array($node->parent()->parent(), $nodeCandidates, true)) {
if ($node->parent()->parent() instanceof Element) {
$nodeCandidates[] = $node->parent()->parent();
}
}
}
return $nodeCandidates;
} | php | private function updateBestNodeCandidates(Element $node, array $nodeCandidates): array {
if (!in_array($node->parent(), $nodeCandidates, true)) {
if ($node->parent() instanceof Element) {
$nodeCandidates[] = $node->parent();
}
}
if ($node->parent() instanceof Element) {
if (!in_array($node->parent()->parent(), $nodeCandidates, true)) {
if ($node->parent()->parent() instanceof Element) {
$nodeCandidates[] = $node->parent()->parent();
}
}
}
return $nodeCandidates;
} | [
"private",
"function",
"updateBestNodeCandidates",
"(",
"Element",
"$",
"node",
",",
"array",
"$",
"nodeCandidates",
")",
":",
"array",
"{",
"if",
"(",
"!",
"in_array",
"(",
"$",
"node",
"->",
"parent",
"(",
")",
",",
"$",
"nodeCandidates",
",",
"true",
... | @param Element $node
@param array $nodeCandidates
@return array | [
"@param",
"Element",
"$node",
"@param",
"array",
"$nodeCandidates"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ContentExtractor.php#L133-L149 |
scotteh/php-goose | src/Modules/Extractors/ContentExtractor.php | ContentExtractor.getTopNode | public function getTopNode(): ?Element {
$nodes = $this->getTopNodeCandidatesByContents($this->article());
$nodeCandidates = [];
$i = 0;
foreach ($nodes as $node) {
if ($this->isOkToBoost($node)) {
$upscore = $this->getTopNodeCandidateScore($node, $i, count($nodes));
$this->calculateBestNodeCandidateScores($node, $upscore);
$nodeCandidates = $this->updateBestNodeCandidates($node, $nodeCandidates);
$i++;
}
}
return $this->getTopNodeByScore($nodeCandidates);
} | php | public function getTopNode(): ?Element {
$nodes = $this->getTopNodeCandidatesByContents($this->article());
$nodeCandidates = [];
$i = 0;
foreach ($nodes as $node) {
if ($this->isOkToBoost($node)) {
$upscore = $this->getTopNodeCandidateScore($node, $i, count($nodes));
$this->calculateBestNodeCandidateScores($node, $upscore);
$nodeCandidates = $this->updateBestNodeCandidates($node, $nodeCandidates);
$i++;
}
}
return $this->getTopNodeByScore($nodeCandidates);
} | [
"public",
"function",
"getTopNode",
"(",
")",
":",
"?",
"Element",
"{",
"$",
"nodes",
"=",
"$",
"this",
"->",
"getTopNodeCandidatesByContents",
"(",
"$",
"this",
"->",
"article",
"(",
")",
")",
";",
"$",
"nodeCandidates",
"=",
"[",
"]",
";",
"$",
"i",
... | We're going to start looking for where the clusters of paragraphs are. We'll score a cluster based on the number of stopwords
and the number of consecutive paragraphs together, which should form the cluster of text that this node is around
also store on how high up the paragraphs are, comments are usually at the bottom and should get a lower score
@return Element|null | [
"We",
"re",
"going",
"to",
"start",
"looking",
"for",
"where",
"the",
"clusters",
"of",
"paragraphs",
"are",
".",
"We",
"ll",
"score",
"a",
"cluster",
"based",
"on",
"the",
"number",
"of",
"stopwords",
"and",
"the",
"number",
"of",
"consecutive",
"paragrap... | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ContentExtractor.php#L158-L176 |
scotteh/php-goose | src/Modules/Extractors/ContentExtractor.php | ContentExtractor.isOkToBoost | private function isOkToBoost(Element $node): bool {
$stepsAway = 0;
$minimumStopWordCount = 5;
$maxStepsAwayFromNode = 3;
// Find all previous sibling element nodes
$siblings = $node->precedingAll(function($node) {
return $node instanceof Element;
});
foreach ($siblings as $sibling) {
if ($sibling->is('p, strong')) {
if ($stepsAway >= $maxStepsAwayFromNode) {
return false;
}
$wordStats = $this->config()->getStopWords()->getStopwordCount($sibling->text());
if ($wordStats->getStopWordCount() > $minimumStopWordCount) {
return true;
}
$stepsAway += 1;
}
}
return false;
} | php | private function isOkToBoost(Element $node): bool {
$stepsAway = 0;
$minimumStopWordCount = 5;
$maxStepsAwayFromNode = 3;
// Find all previous sibling element nodes
$siblings = $node->precedingAll(function($node) {
return $node instanceof Element;
});
foreach ($siblings as $sibling) {
if ($sibling->is('p, strong')) {
if ($stepsAway >= $maxStepsAwayFromNode) {
return false;
}
$wordStats = $this->config()->getStopWords()->getStopwordCount($sibling->text());
if ($wordStats->getStopWordCount() > $minimumStopWordCount) {
return true;
}
$stepsAway += 1;
}
}
return false;
} | [
"private",
"function",
"isOkToBoost",
"(",
"Element",
"$",
"node",
")",
":",
"bool",
"{",
"$",
"stepsAway",
"=",
"0",
";",
"$",
"minimumStopWordCount",
"=",
"5",
";",
"$",
"maxStepsAwayFromNode",
"=",
"3",
";",
"// Find all previous sibling element nodes",
"$",
... | A lot of times the first paragraph might be the caption under an image so we'll want to make sure if we're going to
boost a parent node that it should be connected to other paragraphs, at least for the first n paragraphs
so we'll want to make sure that the next sibling is a paragraph and has at least some substantial weight to it
@param Element $node
@return bool | [
"A",
"lot",
"of",
"times",
"the",
"first",
"paragraph",
"might",
"be",
"the",
"caption",
"under",
"an",
"image",
"so",
"we",
"ll",
"want",
"to",
"make",
"sure",
"if",
"we",
"re",
"going",
"to",
"boost",
"a",
"parent",
"node",
"that",
"it",
"should",
... | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ContentExtractor.php#L187-L214 |
scotteh/php-goose | src/Modules/Extractors/PublishDateExtractor.php | PublishDateExtractor.getDateFromSchemaOrg | private function getDateFromSchemaOrg(): ?\DateTime {
$dt = null;
// Check for HTML tags (<meta>, <time>, etc.)
$nodes = $this->article()->getRawDoc()->find('*[itemprop="datePublished"]');
/* @var $node Element */
foreach ($nodes as $node) {
try {
if ($node->hasAttribute('datetime')) {
$dt = new \DateTime($node->getAttribute('datetime'));
break;
}
if ($node->hasAttribute('content')) {
$dt = new \DateTime($node->getAttribute('content'));
break;
}
}
catch (\Exception $e) {
// Do nothing here in case the node has unrecognizable date information.
}
}
if (!is_null($dt)) {
return $dt;
}
// Check for JSON-LD
$nodes = $this->article()->getRawDoc()->find('script[type="application/ld+json"]');
/* @var $node Element */
foreach ($nodes as $node) {
try {
$json = json_decode($node->text());
if (isset($json->datePublished)) {
$date = is_array($json->datePublished)
? array_shift($json->datePublished)
: $json->datePublished;
$dt = new \DateTime($date);
break;
}
}
catch (\Exception $e) {
// Do nothing here in case the node has unrecognizable date information.
}
}
return $dt;
} | php | private function getDateFromSchemaOrg(): ?\DateTime {
$dt = null;
// Check for HTML tags (<meta>, <time>, etc.)
$nodes = $this->article()->getRawDoc()->find('*[itemprop="datePublished"]');
/* @var $node Element */
foreach ($nodes as $node) {
try {
if ($node->hasAttribute('datetime')) {
$dt = new \DateTime($node->getAttribute('datetime'));
break;
}
if ($node->hasAttribute('content')) {
$dt = new \DateTime($node->getAttribute('content'));
break;
}
}
catch (\Exception $e) {
// Do nothing here in case the node has unrecognizable date information.
}
}
if (!is_null($dt)) {
return $dt;
}
// Check for JSON-LD
$nodes = $this->article()->getRawDoc()->find('script[type="application/ld+json"]');
/* @var $node Element */
foreach ($nodes as $node) {
try {
$json = json_decode($node->text());
if (isset($json->datePublished)) {
$date = is_array($json->datePublished)
? array_shift($json->datePublished)
: $json->datePublished;
$dt = new \DateTime($date);
break;
}
}
catch (\Exception $e) {
// Do nothing here in case the node has unrecognizable date information.
}
}
return $dt;
} | [
"private",
"function",
"getDateFromSchemaOrg",
"(",
")",
":",
"?",
"\\",
"DateTime",
"{",
"$",
"dt",
"=",
"null",
";",
"// Check for HTML tags (<meta>, <time>, etc.)",
"$",
"nodes",
"=",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getRawDoc",
"(",
")",
"-... | Check for and determine dates from Schema.org's datePublished property.
Checks HTML tags (e.g. <meta>, <time>, etc.) and JSON-LD.
@return \DateTime|null
@see https://schema.org/datePublished | [
"Check",
"for",
"and",
"determine",
"dates",
"from",
"Schema",
".",
"org",
"s",
"datePublished",
"property",
"."
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/PublishDateExtractor.php#L76-L125 |
scotteh/php-goose | src/Modules/Extractors/PublishDateExtractor.php | PublishDateExtractor.getDateFromDublinCore | private function getDateFromDublinCore(): ?\DateTime {
$dt = null;
$nodes = $this->article()->getRawDoc()->find('*[name="dc.date"], *[name="dc.date.issued"], *[name="DC.date.issued"]');
/* @var $node Element */
foreach ($nodes as $node) {
try {
if ($node->hasAttribute('content')) {
$dt = new \DateTime($node->getAttribute('content'));
break;
}
}
catch (\Exception $e) {
// Do nothing here in case the node has unrecognizable date information.
}
}
if (!is_null($dt)) {
return $dt;
}
return $dt;
} | php | private function getDateFromDublinCore(): ?\DateTime {
$dt = null;
$nodes = $this->article()->getRawDoc()->find('*[name="dc.date"], *[name="dc.date.issued"], *[name="DC.date.issued"]');
/* @var $node Element */
foreach ($nodes as $node) {
try {
if ($node->hasAttribute('content')) {
$dt = new \DateTime($node->getAttribute('content'));
break;
}
}
catch (\Exception $e) {
// Do nothing here in case the node has unrecognizable date information.
}
}
if (!is_null($dt)) {
return $dt;
}
return $dt;
} | [
"private",
"function",
"getDateFromDublinCore",
"(",
")",
":",
"?",
"\\",
"DateTime",
"{",
"$",
"dt",
"=",
"null",
";",
"$",
"nodes",
"=",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getRawDoc",
"(",
")",
"->",
"find",
"(",
"'*[name=\"dc.date\"], *[na... | Check for and determine dates based on Dublin Core standards.
@return \DateTime|null
@see http://dublincore.org/documents/dcmi-terms/#elements-date
@see http://dublincore.org/documents/2000/07/16/usageguide/qualified-html.shtml | [
"Check",
"for",
"and",
"determine",
"dates",
"based",
"on",
"Dublin",
"Core",
"standards",
"."
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/PublishDateExtractor.php#L135-L157 |
scotteh/php-goose | src/Modules/Extractors/PublishDateExtractor.php | PublishDateExtractor.getDateFromOpenGraph | private function getDateFromOpenGraph(): ?\DateTime {
$dt = null;
$og_data = $this->article()->getOpenGraph();
try {
if (isset($og_data['published_time'])) {
$dt = new \DateTime($og_data['published_time']);
}
if (is_null($dt) && isset($og_data['pubdate'])) {
$dt = new \DateTime($og_data['pubdate']);
}
}
catch (\Exception $e) {
// Do nothing here in case the node has unrecognizable date information.
}
return $dt;
} | php | private function getDateFromOpenGraph(): ?\DateTime {
$dt = null;
$og_data = $this->article()->getOpenGraph();
try {
if (isset($og_data['published_time'])) {
$dt = new \DateTime($og_data['published_time']);
}
if (is_null($dt) && isset($og_data['pubdate'])) {
$dt = new \DateTime($og_data['pubdate']);
}
}
catch (\Exception $e) {
// Do nothing here in case the node has unrecognizable date information.
}
return $dt;
} | [
"private",
"function",
"getDateFromOpenGraph",
"(",
")",
":",
"?",
"\\",
"DateTime",
"{",
"$",
"dt",
"=",
"null",
";",
"$",
"og_data",
"=",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getOpenGraph",
"(",
")",
";",
"try",
"{",
"if",
"(",
"isset",
... | Check for and determine dates based on OpenGraph standards.
@return \DateTime|null
@see http://ogp.me/
@see http://ogp.me/#type_article | [
"Check",
"for",
"and",
"determine",
"dates",
"based",
"on",
"OpenGraph",
"standards",
"."
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/PublishDateExtractor.php#L167-L185 |
scotteh/php-goose | src/Modules/Extractors/PublishDateExtractor.php | PublishDateExtractor.getDateFromParsely | private function getDateFromParsely(): ?\DateTime {
$dt = null;
// JSON-LD
$nodes = $this->article()->getRawDoc()->find('script[type="application/ld+json"]');
/* @var $node Element */
foreach ($nodes as $node) {
try {
$json = json_decode($node->text());
if (isset($json->dateCreated)) {
$date = is_array($json->dateCreated)
? array_shift($json->dateCreated)
: $json->dateCreated;
$dt = new \DateTime($date);
break;
}
}
catch (\Exception $e) {
// Do nothing here in case the node has unrecognizable date information.
}
}
if (!is_null($dt)) {
return $dt;
}
// <meta> tags
$nodes = $this->article()->getRawDoc()->find('meta[name="parsely-pub-date"]');
/* @var $node Element */
foreach ($nodes as $node) {
try {
if ($node->hasAttribute('content')) {
$dt = new \DateTime($node->getAttribute('content'));
break;
}
}
catch (\Exception $e) {
// Do nothing here in case the node has unrecognizable date information.
}
}
if (!is_null($dt)) {
return $dt;
}
// parsely-page
$nodes = $this->article()->getRawDoc()->find('meta[name="parsely-page"]');
/* @var $node Element */
foreach ($nodes as $node) {
try {
if ($node->hasAttribute('content')) {
$json = json_decode($node->getAttribute('content'));
if (isset($json->pub_date)) {
$dt = new \DateTime($json->pub_date);
break;
}
}
}
catch (\Exception $e) {
// Do nothing here in case the node has unrecognizable date information.
}
}
return $dt;
} | php | private function getDateFromParsely(): ?\DateTime {
$dt = null;
// JSON-LD
$nodes = $this->article()->getRawDoc()->find('script[type="application/ld+json"]');
/* @var $node Element */
foreach ($nodes as $node) {
try {
$json = json_decode($node->text());
if (isset($json->dateCreated)) {
$date = is_array($json->dateCreated)
? array_shift($json->dateCreated)
: $json->dateCreated;
$dt = new \DateTime($date);
break;
}
}
catch (\Exception $e) {
// Do nothing here in case the node has unrecognizable date information.
}
}
if (!is_null($dt)) {
return $dt;
}
// <meta> tags
$nodes = $this->article()->getRawDoc()->find('meta[name="parsely-pub-date"]');
/* @var $node Element */
foreach ($nodes as $node) {
try {
if ($node->hasAttribute('content')) {
$dt = new \DateTime($node->getAttribute('content'));
break;
}
}
catch (\Exception $e) {
// Do nothing here in case the node has unrecognizable date information.
}
}
if (!is_null($dt)) {
return $dt;
}
// parsely-page
$nodes = $this->article()->getRawDoc()->find('meta[name="parsely-page"]');
/* @var $node Element */
foreach ($nodes as $node) {
try {
if ($node->hasAttribute('content')) {
$json = json_decode($node->getAttribute('content'));
if (isset($json->pub_date)) {
$dt = new \DateTime($json->pub_date);
break;
}
}
}
catch (\Exception $e) {
// Do nothing here in case the node has unrecognizable date information.
}
}
return $dt;
} | [
"private",
"function",
"getDateFromParsely",
"(",
")",
":",
"?",
"\\",
"DateTime",
"{",
"$",
"dt",
"=",
"null",
";",
"// JSON-LD",
"$",
"nodes",
"=",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getRawDoc",
"(",
")",
"->",
"find",
"(",
"'script[type=... | Check for and determine dates based on Parsely metadata.
Checks JSON-LD, <meta> tags and parsely-page.
@return \DateTime|null
@see https://www.parsely.com/help/integration/jsonld/
@see https://www.parsely.com/help/integration/metatags/
@see https://www.parsely.com/help/integration/ppage/ | [
"Check",
"for",
"and",
"determine",
"dates",
"based",
"on",
"Parsely",
"metadata",
"."
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/PublishDateExtractor.php#L198-L266 |
scotteh/php-goose | src/Configuration.php | Configuration.set | public function set(string $option, $value): self {
$this->options[$option] = $value;
return $this;
} | php | public function set(string $option, $value): self {
$this->options[$option] = $value;
return $this;
} | [
"public",
"function",
"set",
"(",
"string",
"$",
"option",
",",
"$",
"value",
")",
":",
"self",
"{",
"$",
"this",
"->",
"options",
"[",
"$",
"option",
"]",
"=",
"$",
"value",
";",
"return",
"$",
"this",
";",
"}"
] | @param string $option
@param mixed $value
@return self | [
"@param",
"string",
"$option",
"@param",
"mixed",
"$value"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Configuration.php#L78-L82 |
scotteh/php-goose | src/Configuration.php | Configuration.getModules | public function getModules(string $category) {
if (isset($this->modules[$category])) {
return $this->modules[$category];
}
return null;
} | php | public function getModules(string $category) {
if (isset($this->modules[$category])) {
return $this->modules[$category];
}
return null;
} | [
"public",
"function",
"getModules",
"(",
"string",
"$",
"category",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"modules",
"[",
"$",
"category",
"]",
")",
")",
"{",
"return",
"$",
"this",
"->",
"modules",
"[",
"$",
"category",
"]",
";",
"... | @param string $category
@return mixed | [
"@param",
"string",
"$category"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Configuration.php#L89-L95 |
scotteh/php-goose | src/Configuration.php | Configuration.setModules | public function setModules(string $category, array $classes): self {
if ($this->areValidModules($category, $classes)) {
$this->modules[$category] = $classes;
}
return $this;
} | php | public function setModules(string $category, array $classes): self {
if ($this->areValidModules($category, $classes)) {
$this->modules[$category] = $classes;
}
return $this;
} | [
"public",
"function",
"setModules",
"(",
"string",
"$",
"category",
",",
"array",
"$",
"classes",
")",
":",
"self",
"{",
"if",
"(",
"$",
"this",
"->",
"areValidModules",
"(",
"$",
"category",
",",
"$",
"classes",
")",
")",
"{",
"$",
"this",
"->",
"mo... | @param string $category
@param string[] $classes
@return self | [
"@param",
"string",
"$category",
"@param",
"string",
"[]",
"$classes"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Configuration.php#L103-L109 |
scotteh/php-goose | src/Configuration.php | Configuration.addModule | public function addModule(string $category, string $class): self {
if ($this->isValidModule($category, $class)) {
$this->modules[$category][] = $class;
}
return $this;
} | php | public function addModule(string $category, string $class): self {
if ($this->isValidModule($category, $class)) {
$this->modules[$category][] = $class;
}
return $this;
} | [
"public",
"function",
"addModule",
"(",
"string",
"$",
"category",
",",
"string",
"$",
"class",
")",
":",
"self",
"{",
"if",
"(",
"$",
"this",
"->",
"isValidModule",
"(",
"$",
"category",
",",
"$",
"class",
")",
")",
"{",
"$",
"this",
"->",
"modules"... | @param string $category
@param string $class
@return self | [
"@param",
"string",
"$category",
"@param",
"string",
"$class"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Configuration.php#L117-L123 |
scotteh/php-goose | src/Configuration.php | Configuration.removeModule | public function removeModule(string $category, string $class): self {
if (isset($this->modules[$category])) {
$key = array_search($class, $this->modules[$category]);
if ($key !== false) {
unset($this->modules[$category][$key]);
}
}
return $this;
} | php | public function removeModule(string $category, string $class): self {
if (isset($this->modules[$category])) {
$key = array_search($class, $this->modules[$category]);
if ($key !== false) {
unset($this->modules[$category][$key]);
}
}
return $this;
} | [
"public",
"function",
"removeModule",
"(",
"string",
"$",
"category",
",",
"string",
"$",
"class",
")",
":",
"self",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"modules",
"[",
"$",
"category",
"]",
")",
")",
"{",
"$",
"key",
"=",
"array_search"... | @param string $category
@param string $class
@return self | [
"@param",
"string",
"$category",
"@param",
"string",
"$class"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Configuration.php#L131-L141 |
scotteh/php-goose | src/Configuration.php | Configuration.isValidModule | public function isValidModule(string $category, string $class): bool {
if (isset($this->modules[$category])
&& $class instanceof ModuleInterface) {
return true;
}
return false;
} | php | public function isValidModule(string $category, string $class): bool {
if (isset($this->modules[$category])
&& $class instanceof ModuleInterface) {
return true;
}
return false;
} | [
"public",
"function",
"isValidModule",
"(",
"string",
"$",
"category",
",",
"string",
"$",
"class",
")",
":",
"bool",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"modules",
"[",
"$",
"category",
"]",
")",
"&&",
"$",
"class",
"instanceof",
"ModuleI... | @param string $category
@param string $class
@return bool | [
"@param",
"string",
"$category",
"@param",
"string",
"$class"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Configuration.php#L149-L156 |
scotteh/php-goose | src/Configuration.php | Configuration.areValidModules | public function areValidModules(string $category, array $classes): bool {
foreach ($classes as $class) {
if (!$this->isValidModule($category, $class)) {
return false;
}
}
return true;
} | php | public function areValidModules(string $category, array $classes): bool {
foreach ($classes as $class) {
if (!$this->isValidModule($category, $class)) {
return false;
}
}
return true;
} | [
"public",
"function",
"areValidModules",
"(",
"string",
"$",
"category",
",",
"array",
"$",
"classes",
")",
":",
"bool",
"{",
"foreach",
"(",
"$",
"classes",
"as",
"$",
"class",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"isValidModule",
"(",
"$",
... | @param string $category
@param string[] $classes
@return bool | [
"@param",
"string",
"$category",
"@param",
"string",
"[]",
"$classes"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Configuration.php#L164-L172 |
scotteh/php-goose | src/Configuration.php | Configuration.getStopWords | public function getStopWords(): StopWords {
if (is_null($this->stopWords)) {
$this->stopWords = new StopWords($this);
}
return $this->stopWords;
} | php | public function getStopWords(): StopWords {
if (is_null($this->stopWords)) {
$this->stopWords = new StopWords($this);
}
return $this->stopWords;
} | [
"public",
"function",
"getStopWords",
"(",
")",
":",
"StopWords",
"{",
"if",
"(",
"is_null",
"(",
"$",
"this",
"->",
"stopWords",
")",
")",
"{",
"$",
"this",
"->",
"stopWords",
"=",
"new",
"StopWords",
"(",
"$",
"this",
")",
";",
"}",
"return",
"$",
... | /*
@return StopWords | [
"/",
"*"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Configuration.php#L191-L197 |
scotteh/php-goose | src/Client.php | Client.extractContent | public function extractContent(string $url, string $rawHTML = null): ?Article {
$crawler = new Crawler($this->config);
$article = $crawler->crawl($url, $rawHTML);
return $article;
} | php | public function extractContent(string $url, string $rawHTML = null): ?Article {
$crawler = new Crawler($this->config);
$article = $crawler->crawl($url, $rawHTML);
return $article;
} | [
"public",
"function",
"extractContent",
"(",
"string",
"$",
"url",
",",
"string",
"$",
"rawHTML",
"=",
"null",
")",
":",
"?",
"Article",
"{",
"$",
"crawler",
"=",
"new",
"Crawler",
"(",
"$",
"this",
"->",
"config",
")",
";",
"$",
"article",
"=",
"$",... | @param string $url
@param string $rawHTML
@return Article | [
"@param",
"string",
"$url",
"@param",
"string",
"$rawHTML"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Client.php#L42-L47 |
scotteh/php-goose | src/Utils/Helper.php | Helper.getCleanedUrl | public static function getCleanedUrl($urlToCrawl) {
$parts = parse_url($urlToCrawl);
if ($parts === false) {
throw new MalformedURLException($urlToCrawl . ' - is a malformed URL and cannot be processed');
}
$prefix = isset($parts['query']) && $parts['query'] ? '&' : '?';
$finalUrl = str_replace('#!', $prefix . '_escaped_fragment_=', $urlToCrawl);
return (object)[
'url' => $urlToCrawl,
'parts' => (object)$parts,
'linkhash' => md5($urlToCrawl),
'finalUrl' => $finalUrl,
];
} | php | public static function getCleanedUrl($urlToCrawl) {
$parts = parse_url($urlToCrawl);
if ($parts === false) {
throw new MalformedURLException($urlToCrawl . ' - is a malformed URL and cannot be processed');
}
$prefix = isset($parts['query']) && $parts['query'] ? '&' : '?';
$finalUrl = str_replace('#!', $prefix . '_escaped_fragment_=', $urlToCrawl);
return (object)[
'url' => $urlToCrawl,
'parts' => (object)$parts,
'linkhash' => md5($urlToCrawl),
'finalUrl' => $finalUrl,
];
} | [
"public",
"static",
"function",
"getCleanedUrl",
"(",
"$",
"urlToCrawl",
")",
"{",
"$",
"parts",
"=",
"parse_url",
"(",
"$",
"urlToCrawl",
")",
";",
"if",
"(",
"$",
"parts",
"===",
"false",
")",
"{",
"throw",
"new",
"MalformedURLException",
"(",
"$",
"ur... | @todo Re-factor result into class
@param string $urlToCrawl
@return object | [
"@todo",
"Re",
"-",
"factor",
"result",
"into",
"class"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Utils/Helper.php#L21-L38 |
scotteh/php-goose | src/Article.php | Article.setRawResponse | public function setRawResponse(\Psr\Http\Message\ResponseInterface $rawResponse): self {
$this->rawResponse = $rawResponse;
return $this;
} | php | public function setRawResponse(\Psr\Http\Message\ResponseInterface $rawResponse): self {
$this->rawResponse = $rawResponse;
return $this;
} | [
"public",
"function",
"setRawResponse",
"(",
"\\",
"Psr",
"\\",
"Http",
"\\",
"Message",
"\\",
"ResponseInterface",
"$",
"rawResponse",
")",
":",
"self",
"{",
"$",
"this",
"->",
"rawResponse",
"=",
"$",
"rawResponse",
";",
"return",
"$",
"this",
";",
"}"
] | @param \Psr\Http\Message\ResponseInterface|null $rawResponse
@return self | [
"@param",
"\\",
"Psr",
"\\",
"Http",
"\\",
"Message",
"\\",
"ResponseInterface|null",
"$rawResponse"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Article.php#L490-L494 |
scotteh/php-goose | src/Images/ImageUtils.php | ImageUtils.getImageDimensions | public static function getImageDimensions(string $filePath): ?\stdClass {
list($width, $height, $type) = getimagesize($filePath);
if ($type === null) {
return null;
}
return (object)[
'width' => (int)$width,
'height' => (int)$height,
'mime' => image_type_to_mime_type($type),
];
} | php | public static function getImageDimensions(string $filePath): ?\stdClass {
list($width, $height, $type) = getimagesize($filePath);
if ($type === null) {
return null;
}
return (object)[
'width' => (int)$width,
'height' => (int)$height,
'mime' => image_type_to_mime_type($type),
];
} | [
"public",
"static",
"function",
"getImageDimensions",
"(",
"string",
"$",
"filePath",
")",
":",
"?",
"\\",
"stdClass",
"{",
"list",
"(",
"$",
"width",
",",
"$",
"height",
",",
"$",
"type",
")",
"=",
"getimagesize",
"(",
"$",
"filePath",
")",
";",
"if",... | @param string $filePath
@return object|null | [
"@param",
"string",
"$filePath"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Images/ImageUtils.php#L21-L33 |
scotteh/php-goose | src/Images/ImageUtils.php | ImageUtils.storeImagesToLocalFile | public static function storeImagesToLocalFile($imageSrcs, bool $returnAll, Configuration $config): array {
$localImages = self::handleEntity($imageSrcs, $returnAll, $config);
if (empty($localImages)) {
return [];
}
$locallyStoredImages = [];
foreach ($localImages as $localImage) {
if (empty($localImage->file) || !filesize($localImage->file)) {
continue;
}
$imageDetails = self::getImageDimensions($localImage->file);
if ($imageDetails !== null) {
$locallyStoredImages[] = new LocallyStoredImage([
'imgSrc' => $localImage->url,
'localFileName' => $localImage->file,
'bytes' => filesize($localImage->file),
'height' => $imageDetails->height,
'width' => $imageDetails->width,
'fileExtension' => self::getFileExtensionName($imageDetails),
]);
}
}
return $locallyStoredImages;
} | php | public static function storeImagesToLocalFile($imageSrcs, bool $returnAll, Configuration $config): array {
$localImages = self::handleEntity($imageSrcs, $returnAll, $config);
if (empty($localImages)) {
return [];
}
$locallyStoredImages = [];
foreach ($localImages as $localImage) {
if (empty($localImage->file) || !filesize($localImage->file)) {
continue;
}
$imageDetails = self::getImageDimensions($localImage->file);
if ($imageDetails !== null) {
$locallyStoredImages[] = new LocallyStoredImage([
'imgSrc' => $localImage->url,
'localFileName' => $localImage->file,
'bytes' => filesize($localImage->file),
'height' => $imageDetails->height,
'width' => $imageDetails->width,
'fileExtension' => self::getFileExtensionName($imageDetails),
]);
}
}
return $locallyStoredImages;
} | [
"public",
"static",
"function",
"storeImagesToLocalFile",
"(",
"$",
"imageSrcs",
",",
"bool",
"$",
"returnAll",
",",
"Configuration",
"$",
"config",
")",
":",
"array",
"{",
"$",
"localImages",
"=",
"self",
"::",
"handleEntity",
"(",
"$",
"imageSrcs",
",",
"$... | Writes an image src http string to disk as a temporary file and returns the LocallyStoredImage object that has the info you should need
on the image
@param string[] $imageSrcs
@param bool $returnAll
@param Configuration $config
@return LocallyStoredImage[] | [
"Writes",
"an",
"image",
"src",
"http",
"string",
"to",
"disk",
"as",
"a",
"temporary",
"file",
"and",
"returns",
"the",
"LocallyStoredImage",
"object",
"that",
"has",
"the",
"info",
"you",
"should",
"need",
"on",
"the",
"image"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Images/ImageUtils.php#L45-L74 |
scotteh/php-goose | src/Images/ImageUtils.php | ImageUtils.getFileExtensionName | private static function getFileExtensionName(\stdClass $imageDetails): string {
$extensions = [
'image/gif' => '.gif',
'image/jpeg' => '.jpg',
'image/png' => '.png',
];
return (
isset($extensions[$imageDetails->mime])
? $extensions[$imageDetails->mime]
: 'NA'
);
} | php | private static function getFileExtensionName(\stdClass $imageDetails): string {
$extensions = [
'image/gif' => '.gif',
'image/jpeg' => '.jpg',
'image/png' => '.png',
];
return (
isset($extensions[$imageDetails->mime])
? $extensions[$imageDetails->mime]
: 'NA'
);
} | [
"private",
"static",
"function",
"getFileExtensionName",
"(",
"\\",
"stdClass",
"$",
"imageDetails",
")",
":",
"string",
"{",
"$",
"extensions",
"=",
"[",
"'image/gif'",
"=>",
"'.gif'",
",",
"'image/jpeg'",
"=>",
"'.jpg'",
",",
"'image/png'",
"=>",
"'.png'",
"... | @param object $imageDetails
@return string | [
"@param",
"object",
"$imageDetails"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Images/ImageUtils.php#L81-L93 |
scotteh/php-goose | src/Images/ImageUtils.php | ImageUtils.handleEntity | private static function handleEntity($imageSrcs, bool $returnAll, Configuration $config): ?array {
$guzzle = new Client();
$results = [];
$requests = function($urls) use ($guzzle, &$results) {
foreach ($urls as $key => $url) {
$file = tempnam(sys_get_temp_dir(), 'goose');
$results[] = (object)[
'url' => $url,
'file' => $file,
];
yield $key => function($options) use ($guzzle, $url, $file) {
$options['sink'] = $file;
return $guzzle->sendAsync(new Request('GET', $url), $options);
};
}
};
$pool = new Pool($guzzle, $requests($imageSrcs), [
'concurrency' => 25,
'fulfilled' => function($response, $index) use (&$results, $returnAll) {
if (!$returnAll && $response->getStatusCode() != 200) {
unset($results[$index]);
}
},
'rejected' => function($reason, $index) use (&$results, $returnAll) {
if ($returnAll) {
$results[$index]->file = null;
} else {
unset($results[$index]);
}
},
'options' => $config->get('browser'),
]);
$pool->promise()->wait();
if (empty($results)) {
return null;
}
return $results;
} | php | private static function handleEntity($imageSrcs, bool $returnAll, Configuration $config): ?array {
$guzzle = new Client();
$results = [];
$requests = function($urls) use ($guzzle, &$results) {
foreach ($urls as $key => $url) {
$file = tempnam(sys_get_temp_dir(), 'goose');
$results[] = (object)[
'url' => $url,
'file' => $file,
];
yield $key => function($options) use ($guzzle, $url, $file) {
$options['sink'] = $file;
return $guzzle->sendAsync(new Request('GET', $url), $options);
};
}
};
$pool = new Pool($guzzle, $requests($imageSrcs), [
'concurrency' => 25,
'fulfilled' => function($response, $index) use (&$results, $returnAll) {
if (!$returnAll && $response->getStatusCode() != 200) {
unset($results[$index]);
}
},
'rejected' => function($reason, $index) use (&$results, $returnAll) {
if ($returnAll) {
$results[$index]->file = null;
} else {
unset($results[$index]);
}
},
'options' => $config->get('browser'),
]);
$pool->promise()->wait();
if (empty($results)) {
return null;
}
return $results;
} | [
"private",
"static",
"function",
"handleEntity",
"(",
"$",
"imageSrcs",
",",
"bool",
"$",
"returnAll",
",",
"Configuration",
"$",
"config",
")",
":",
"?",
"array",
"{",
"$",
"guzzle",
"=",
"new",
"Client",
"(",
")",
";",
"$",
"results",
"=",
"[",
"]",
... | @param string[] $imageSrcs
@param bool $returnAll
@param Configuration $config
@return array|null | [
"@param",
"string",
"[]",
"$imageSrcs",
"@param",
"bool",
"$returnAll",
"@param",
"Configuration",
"$config"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Images/ImageUtils.php#L102-L148 |
scotteh/php-goose | src/Traits/NodeCommonTrait.php | NodeCommonTrait.isHighLinkDensity | private function isHighLinkDensity(Element $node, float $limit = 1.0): bool {
$links = $node->find('a, [onclick]');
if ($links->count() == 0) {
return false;
}
$words = preg_split('@[\s]+@iu', $node->text(), -1, PREG_SPLIT_NO_EMPTY);
if (!is_array($words) || empty($words)) {
return false;
}
$sb = [];
foreach ($links as $link) {
$sb[] = Helper::textNormalise($link->text());
}
$linkText = implode('', $sb);
$linkWords = explode(' ', $linkText);
$numberOfLinkWords = count($linkWords);
$numberOfLinks = $links->count();
$linkDivisor = $numberOfLinkWords / count($words);
$score = $linkDivisor * $numberOfLinks;
if ($score >= $limit) {
return true;
}
return false;
} | php | private function isHighLinkDensity(Element $node, float $limit = 1.0): bool {
$links = $node->find('a, [onclick]');
if ($links->count() == 0) {
return false;
}
$words = preg_split('@[\s]+@iu', $node->text(), -1, PREG_SPLIT_NO_EMPTY);
if (!is_array($words) || empty($words)) {
return false;
}
$sb = [];
foreach ($links as $link) {
$sb[] = Helper::textNormalise($link->text());
}
$linkText = implode('', $sb);
$linkWords = explode(' ', $linkText);
$numberOfLinkWords = count($linkWords);
$numberOfLinks = $links->count();
$linkDivisor = $numberOfLinkWords / count($words);
$score = $linkDivisor * $numberOfLinks;
if ($score >= $limit) {
return true;
}
return false;
} | [
"private",
"function",
"isHighLinkDensity",
"(",
"Element",
"$",
"node",
",",
"float",
"$",
"limit",
"=",
"1.0",
")",
":",
"bool",
"{",
"$",
"links",
"=",
"$",
"node",
"->",
"find",
"(",
"'a, [onclick]'",
")",
";",
"if",
"(",
"$",
"links",
"->",
"cou... | Checks the density of links within a node, is there not much text and most of it contains linky shit?
if so it's no good
@param Element $node
@param float $limit
@return bool | [
"Checks",
"the",
"density",
"of",
"links",
"within",
"a",
"node",
"is",
"there",
"not",
"much",
"text",
"and",
"most",
"of",
"it",
"contains",
"linky",
"shit?",
"if",
"so",
"it",
"s",
"no",
"good"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Traits/NodeCommonTrait.php#L24-L54 |
scotteh/php-goose | src/Modules/Formatters/OutputFormatter.php | OutputFormatter.getFormattedText | private function getFormattedText(): string {
$this->removeNodesWithNegativeScores($this->article()->getTopNode());
$this->convertLinksToText($this->article()->getTopNode());
$this->replaceTagsWithText($this->article()->getTopNode());
$this->removeParagraphsWithFewWords($this->article()->getTopNode());
return $this->convertToText($this->article()->getTopNode());
} | php | private function getFormattedText(): string {
$this->removeNodesWithNegativeScores($this->article()->getTopNode());
$this->convertLinksToText($this->article()->getTopNode());
$this->replaceTagsWithText($this->article()->getTopNode());
$this->removeParagraphsWithFewWords($this->article()->getTopNode());
return $this->convertToText($this->article()->getTopNode());
} | [
"private",
"function",
"getFormattedText",
"(",
")",
":",
"string",
"{",
"$",
"this",
"->",
"removeNodesWithNegativeScores",
"(",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getTopNode",
"(",
")",
")",
";",
"$",
"this",
"->",
"convertLinksToText",
"(",
... | Removes all unnecessary elements and formats the selected text nodes
@return string Formatted string with all HTML removed | [
"Removes",
"all",
"unnecessary",
"elements",
"and",
"formats",
"the",
"selected",
"text",
"nodes"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Formatters/OutputFormatter.php#L45-L52 |
scotteh/php-goose | src/Modules/Formatters/OutputFormatter.php | OutputFormatter.convertToText | private function convertToText(Element $topNode): string {
if (empty($topNode)) {
return '';
}
$list = [];
foreach ($topNode->contents() as $child) {
$list[] = trim($child->text());
}
return implode("\n\n", $list);
} | php | private function convertToText(Element $topNode): string {
if (empty($topNode)) {
return '';
}
$list = [];
foreach ($topNode->contents() as $child) {
$list[] = trim($child->text());
}
return implode("\n\n", $list);
} | [
"private",
"function",
"convertToText",
"(",
"Element",
"$",
"topNode",
")",
":",
"string",
"{",
"if",
"(",
"empty",
"(",
"$",
"topNode",
")",
")",
"{",
"return",
"''",
";",
"}",
"$",
"list",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"topNode",
"->"... | Takes an element and turns the P tags into \n\n
@param Element $topNode The top most node to format
@return string | [
"Takes",
"an",
"element",
"and",
"turns",
"the",
"P",
"tags",
"into",
"\\",
"n",
"\\",
"n"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Formatters/OutputFormatter.php#L61-L72 |
scotteh/php-goose | src/Modules/Formatters/OutputFormatter.php | OutputFormatter.cleanupHtml | private function cleanupHtml(): string {
$topNode = $this->article()->getTopNode();
if (empty($topNode)) {
return '';
}
$this->removeParagraphsWithFewWords($topNode);
$html = $this->convertToHtml($topNode);
return str_replace(['<p></p>', '<p> </p>'], '', $html);
} | php | private function cleanupHtml(): string {
$topNode = $this->article()->getTopNode();
if (empty($topNode)) {
return '';
}
$this->removeParagraphsWithFewWords($topNode);
$html = $this->convertToHtml($topNode);
return str_replace(['<p></p>', '<p> </p>'], '', $html);
} | [
"private",
"function",
"cleanupHtml",
"(",
")",
":",
"string",
"{",
"$",
"topNode",
"=",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getTopNode",
"(",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"topNode",
")",
")",
"{",
"return",
"''",
";",
"}",
... | Scrape the node content and return the html
@return string Formatted string with all HTML | [
"Scrape",
"the",
"node",
"content",
"and",
"return",
"the",
"html"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Formatters/OutputFormatter.php#L79-L91 |
scotteh/php-goose | src/Modules/Formatters/OutputFormatter.php | OutputFormatter.convertToHtml | private function convertToHtml(Element $topNode): string {
if (empty($topNode)) {
return '';
}
return $topNode->ownerDocument->saveHTML($topNode);
} | php | private function convertToHtml(Element $topNode): string {
if (empty($topNode)) {
return '';
}
return $topNode->ownerDocument->saveHTML($topNode);
} | [
"private",
"function",
"convertToHtml",
"(",
"Element",
"$",
"topNode",
")",
":",
"string",
"{",
"if",
"(",
"empty",
"(",
"$",
"topNode",
")",
")",
"{",
"return",
"''",
";",
"}",
"return",
"$",
"topNode",
"->",
"ownerDocument",
"->",
"saveHTML",
"(",
"... | @param Element $topNode
@return string | [
"@param",
"Element",
"$topNode"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Formatters/OutputFormatter.php#L98-L104 |
scotteh/php-goose | src/Modules/Formatters/OutputFormatter.php | OutputFormatter.convertLinksToText | private function convertLinksToText(Element $topNode): self {
if (!empty($topNode)) {
$links = $topNode->find('a');
foreach ($links as $item) {
$images = $item->find('img');
if ($images->count() == 0) {
$item->replaceWith(new Text(Helper::textNormalise($item->text())));
}
}
}
return $this;
} | php | private function convertLinksToText(Element $topNode): self {
if (!empty($topNode)) {
$links = $topNode->find('a');
foreach ($links as $item) {
$images = $item->find('img');
if ($images->count() == 0) {
$item->replaceWith(new Text(Helper::textNormalise($item->text())));
}
}
}
return $this;
} | [
"private",
"function",
"convertLinksToText",
"(",
"Element",
"$",
"topNode",
")",
":",
"self",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"topNode",
")",
")",
"{",
"$",
"links",
"=",
"$",
"topNode",
"->",
"find",
"(",
"'a'",
")",
";",
"foreach",
"(",
... | cleans up and converts any nodes that should be considered text into text
@param Element $topNode
@return self | [
"cleans",
"up",
"and",
"converts",
"any",
"nodes",
"that",
"should",
"be",
"considered",
"text",
"into",
"text"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Formatters/OutputFormatter.php#L113-L127 |
scotteh/php-goose | src/Modules/Formatters/OutputFormatter.php | OutputFormatter.removeNodesWithNegativeScores | private function removeNodesWithNegativeScores(Element $topNode): self {
if (!empty($topNode)) {
$gravityItems = $topNode->find('*[gravityScore]');
foreach ($gravityItems as $item) {
$score = (int)$item->attr('gravityScore');
if ($score < 1) {
$item->remove();
}
}
}
return $this;
} | php | private function removeNodesWithNegativeScores(Element $topNode): self {
if (!empty($topNode)) {
$gravityItems = $topNode->find('*[gravityScore]');
foreach ($gravityItems as $item) {
$score = (int)$item->attr('gravityScore');
if ($score < 1) {
$item->remove();
}
}
}
return $this;
} | [
"private",
"function",
"removeNodesWithNegativeScores",
"(",
"Element",
"$",
"topNode",
")",
":",
"self",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"topNode",
")",
")",
"{",
"$",
"gravityItems",
"=",
"$",
"topNode",
"->",
"find",
"(",
"'*[gravityScore]'",
")... | if there are elements inside our top node that have a negative gravity score, let's
give em the boot
@param Element $topNode
@return self | [
"if",
"there",
"are",
"elements",
"inside",
"our",
"top",
"node",
"that",
"have",
"a",
"negative",
"gravity",
"score",
"let",
"s",
"give",
"em",
"the",
"boot"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Formatters/OutputFormatter.php#L137-L151 |
scotteh/php-goose | src/Modules/Formatters/OutputFormatter.php | OutputFormatter.replaceTagsWithText | private function replaceTagsWithText(Element $topNode): self {
if (!empty($topNode)) {
$items = $topNode->find('b, strong, i');
foreach ($items as $item) {
$item->replaceWith(new Text($this->getTagCleanedText($item)));
}
$headers = $topNode->find('h1, h2, h3, h4, h5, h6');
foreach ($headers as $header) {
$header->replaceWith(new Text("\n\n" . $this->getTagCleanedText($header) . "\n\n"));
}
}
return $this;
} | php | private function replaceTagsWithText(Element $topNode): self {
if (!empty($topNode)) {
$items = $topNode->find('b, strong, i');
foreach ($items as $item) {
$item->replaceWith(new Text($this->getTagCleanedText($item)));
}
$headers = $topNode->find('h1, h2, h3, h4, h5, h6');
foreach ($headers as $header) {
$header->replaceWith(new Text("\n\n" . $this->getTagCleanedText($header) . "\n\n"));
}
}
return $this;
} | [
"private",
"function",
"replaceTagsWithText",
"(",
"Element",
"$",
"topNode",
")",
":",
"self",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"topNode",
")",
")",
"{",
"$",
"items",
"=",
"$",
"topNode",
"->",
"find",
"(",
"'b, strong, i'",
")",
";",
"foreach... | replace common tags with just text so we don't have any crazy formatting issues
so replace <br>, <i>, <strong>, etc.... with whatever text is inside them
replaces header tags h1 ... h6 with newline padded text
@param Element $topNode
@return self | [
"replace",
"common",
"tags",
"with",
"just",
"text",
"so",
"we",
"don",
"t",
"have",
"any",
"crazy",
"formatting",
"issues",
"so",
"replace",
"<br",
">",
"<i",
">",
"<strong",
">",
"etc",
"....",
"with",
"whatever",
"text",
"is",
"inside",
"them"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Formatters/OutputFormatter.php#L163-L179 |
scotteh/php-goose | src/Modules/Formatters/OutputFormatter.php | OutputFormatter.removeParagraphsWithFewWords | private function removeParagraphsWithFewWords(Element $topNode): self {
if (!empty($topNode)) {
$nodes = $topNode->find('p');
foreach ($nodes as $node) {
$stopWords = $this->config()->getStopWords()->getStopwordCount($node->text());
if (mb_strlen(Helper::textNormalise($node->text())) < 8 && $stopWords->getStopWordCount() < 3 && $node->find('object')->count() == 0 && $node->find('embed')->count() == 0) {
$node->remove();
}
}
/** @todo Implement */
}
return $this;
} | php | private function removeParagraphsWithFewWords(Element $topNode): self {
if (!empty($topNode)) {
$nodes = $topNode->find('p');
foreach ($nodes as $node) {
$stopWords = $this->config()->getStopWords()->getStopwordCount($node->text());
if (mb_strlen(Helper::textNormalise($node->text())) < 8 && $stopWords->getStopWordCount() < 3 && $node->find('object')->count() == 0 && $node->find('embed')->count() == 0) {
$node->remove();
}
}
/** @todo Implement */
}
return $this;
} | [
"private",
"function",
"removeParagraphsWithFewWords",
"(",
"Element",
"$",
"topNode",
")",
":",
"self",
"{",
"if",
"(",
"!",
"empty",
"(",
"$",
"topNode",
")",
")",
"{",
"$",
"nodes",
"=",
"$",
"topNode",
"->",
"find",
"(",
"'p'",
")",
";",
"foreach",... | remove paragraphs that have less than x number of words, would indicate that it's some sort of link
@param Element $topNode
@return self | [
"remove",
"paragraphs",
"that",
"have",
"less",
"than",
"x",
"number",
"of",
"words",
"would",
"indicate",
"that",
"it",
"s",
"some",
"sort",
"of",
"link"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Formatters/OutputFormatter.php#L199-L215 |
scotteh/php-goose | src/Modules/Formatters/OutputFormatter.php | OutputFormatter.postExtractionCleanup | private function postExtractionCleanup(): self {
$this->addSiblings($this->article()->getTopNode());
foreach ($this->article()->getTopNode()->contents() as $node) {
if ($node->is(self::$CLEANUP_IGNORE_SELECTOR)) {
if ($this->isHighLinkDensity($node)
|| $this->isTableTagAndNoParagraphsExist($node)
|| !$this->isNodeScoreThreshholdMet($this->article()->getTopNode(), $node)) {
$node->remove();
}
}
}
return $this;
} | php | private function postExtractionCleanup(): self {
$this->addSiblings($this->article()->getTopNode());
foreach ($this->article()->getTopNode()->contents() as $node) {
if ($node->is(self::$CLEANUP_IGNORE_SELECTOR)) {
if ($this->isHighLinkDensity($node)
|| $this->isTableTagAndNoParagraphsExist($node)
|| !$this->isNodeScoreThreshholdMet($this->article()->getTopNode(), $node)) {
$node->remove();
}
}
}
return $this;
} | [
"private",
"function",
"postExtractionCleanup",
"(",
")",
":",
"self",
"{",
"$",
"this",
"->",
"addSiblings",
"(",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getTopNode",
"(",
")",
")",
";",
"foreach",
"(",
"$",
"this",
"->",
"article",
"(",
")",
... | Remove any divs that looks like non-content, clusters of links, or paras with no gusto
@return self | [
"Remove",
"any",
"divs",
"that",
"looks",
"like",
"non",
"-",
"content",
"clusters",
"of",
"links",
"or",
"paras",
"with",
"no",
"gusto"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Formatters/OutputFormatter.php#L222-L236 |
scotteh/php-goose | src/Modules/Formatters/OutputFormatter.php | OutputFormatter.removeSmallParagraphs | private function removeSmallParagraphs(Element $topNode): self {
$nodes = $topNode->find('p, strong');
foreach ($nodes as $node) {
if (mb_strlen(Helper::textNormalise($node->text())) < 25) {
$node->remove();
}
}
return $this;
} | php | private function removeSmallParagraphs(Element $topNode): self {
$nodes = $topNode->find('p, strong');
foreach ($nodes as $node) {
if (mb_strlen(Helper::textNormalise($node->text())) < 25) {
$node->remove();
}
}
return $this;
} | [
"private",
"function",
"removeSmallParagraphs",
"(",
"Element",
"$",
"topNode",
")",
":",
"self",
"{",
"$",
"nodes",
"=",
"$",
"topNode",
"->",
"find",
"(",
"'p, strong'",
")",
";",
"foreach",
"(",
"$",
"nodes",
"as",
"$",
"node",
")",
"{",
"if",
"(",
... | @param Element $topNode
@return self | [
"@param",
"Element",
"$topNode"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Formatters/OutputFormatter.php#L243-L253 |
scotteh/php-goose | src/Modules/Formatters/OutputFormatter.php | OutputFormatter.isTableTagAndNoParagraphsExist | private function isTableTagAndNoParagraphsExist(Element $topNode): bool {
$this->removeSmallParagraphs($topNode);
$nodes = $topNode->find('p');
if ($nodes->count() == 0 && $topNode->is(':not(td)')) {
if ($topNode->is('ul, ol')) {
$linkTextLength = array_sum(array_map(function($value) {
return mb_strlen(Helper::textNormalise($value->text()));
}, $topNode->find('a')->toArray()));
$elementTextLength = mb_strlen(Helper::textNormalise($topNode->text()));
if ($elementTextLength > 0 && ($linkTextLength / $elementTextLength) < 0.5) {
return false;
}
}
return true;
}
return false;
} | php | private function isTableTagAndNoParagraphsExist(Element $topNode): bool {
$this->removeSmallParagraphs($topNode);
$nodes = $topNode->find('p');
if ($nodes->count() == 0 && $topNode->is(':not(td)')) {
if ($topNode->is('ul, ol')) {
$linkTextLength = array_sum(array_map(function($value) {
return mb_strlen(Helper::textNormalise($value->text()));
}, $topNode->find('a')->toArray()));
$elementTextLength = mb_strlen(Helper::textNormalise($topNode->text()));
if ($elementTextLength > 0 && ($linkTextLength / $elementTextLength) < 0.5) {
return false;
}
}
return true;
}
return false;
} | [
"private",
"function",
"isTableTagAndNoParagraphsExist",
"(",
"Element",
"$",
"topNode",
")",
":",
"bool",
"{",
"$",
"this",
"->",
"removeSmallParagraphs",
"(",
"$",
"topNode",
")",
";",
"$",
"nodes",
"=",
"$",
"topNode",
"->",
"find",
"(",
"'p'",
")",
";"... | @param Element $topNode
@return bool | [
"@param",
"Element",
"$topNode"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Formatters/OutputFormatter.php#L260-L282 |
scotteh/php-goose | src/Modules/Formatters/OutputFormatter.php | OutputFormatter.isNodeScoreThreshholdMet | private function isNodeScoreThreshholdMet(Element $topNode, Element $node): bool {
$topNodeScore = $this->getScore($topNode);
$currentNodeScore = $this->getScore($node);
$thresholdScore = ($topNodeScore * 0.08);
if ($currentNodeScore < $thresholdScore && $node->is(':not(td)')) {
return false;
}
return true;
} | php | private function isNodeScoreThreshholdMet(Element $topNode, Element $node): bool {
$topNodeScore = $this->getScore($topNode);
$currentNodeScore = $this->getScore($node);
$thresholdScore = ($topNodeScore * 0.08);
if ($currentNodeScore < $thresholdScore && $node->is(':not(td)')) {
return false;
}
return true;
} | [
"private",
"function",
"isNodeScoreThreshholdMet",
"(",
"Element",
"$",
"topNode",
",",
"Element",
"$",
"node",
")",
":",
"bool",
"{",
"$",
"topNodeScore",
"=",
"$",
"this",
"->",
"getScore",
"(",
"$",
"topNode",
")",
";",
"$",
"currentNodeScore",
"=",
"$"... | @param Element $topNode
@param Element $node
@return bool | [
"@param",
"Element",
"$topNode",
"@param",
"Element",
"$node"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Formatters/OutputFormatter.php#L290-L300 |
scotteh/php-goose | src/Modules/Formatters/OutputFormatter.php | OutputFormatter.getSiblingContent | private function getSiblingContent(Element $currentSibling, float $baselineScoreForSiblingParagraphs): array {
$text = trim($currentSibling->text());
if ($currentSibling->is('p, strong') && !empty($text)) {
return [$currentSibling];
}
$results = [];
$nodes = $currentSibling->find('p, strong');
foreach ($nodes as $node) {
$text = trim($node->text());
if (!empty($text)) {
$wordStats = $this->config()->getStopWords()->getStopwordCount($text);
if (($baselineScoreForSiblingParagraphs * self::$SIBLING_BASE_LINE_SCORE) < $wordStats->getStopWordCount()) {
$results[] = $node->document()->createElement('p', $text);
}
}
}
return $results;
} | php | private function getSiblingContent(Element $currentSibling, float $baselineScoreForSiblingParagraphs): array {
$text = trim($currentSibling->text());
if ($currentSibling->is('p, strong') && !empty($text)) {
return [$currentSibling];
}
$results = [];
$nodes = $currentSibling->find('p, strong');
foreach ($nodes as $node) {
$text = trim($node->text());
if (!empty($text)) {
$wordStats = $this->config()->getStopWords()->getStopwordCount($text);
if (($baselineScoreForSiblingParagraphs * self::$SIBLING_BASE_LINE_SCORE) < $wordStats->getStopWordCount()) {
$results[] = $node->document()->createElement('p', $text);
}
}
}
return $results;
} | [
"private",
"function",
"getSiblingContent",
"(",
"Element",
"$",
"currentSibling",
",",
"float",
"$",
"baselineScoreForSiblingParagraphs",
")",
":",
"array",
"{",
"$",
"text",
"=",
"trim",
"(",
"$",
"currentSibling",
"->",
"text",
"(",
")",
")",
";",
"if",
"... | Adds any siblings that may have a decent score to this node
@param Element $currentSibling
@param float $baselineScoreForSiblingParagraphs
@return Element[] | [
"Adds",
"any",
"siblings",
"that",
"may",
"have",
"a",
"decent",
"score",
"to",
"this",
"node"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Formatters/OutputFormatter.php#L310-L334 |
scotteh/php-goose | src/Modules/Formatters/OutputFormatter.php | OutputFormatter.addSiblings | private function addSiblings(Element $topNode): self {
$baselineScoreForSiblingParagraphs = $this->getBaselineScoreForSiblings($topNode);
$previousSiblings = $topNode->precedingAll(function($node) {
return $node instanceof Element;
});
// Find all previous sibling element nodes
foreach ($previousSiblings as $siblingNode) {
$results = $this->getSiblingContent($siblingNode, $baselineScoreForSiblingParagraphs);
foreach ($results as $result) {
$topNode->insertBefore($result, $topNode->firstChild);
}
}
return $this;
} | php | private function addSiblings(Element $topNode): self {
$baselineScoreForSiblingParagraphs = $this->getBaselineScoreForSiblings($topNode);
$previousSiblings = $topNode->precedingAll(function($node) {
return $node instanceof Element;
});
// Find all previous sibling element nodes
foreach ($previousSiblings as $siblingNode) {
$results = $this->getSiblingContent($siblingNode, $baselineScoreForSiblingParagraphs);
foreach ($results as $result) {
$topNode->insertBefore($result, $topNode->firstChild);
}
}
return $this;
} | [
"private",
"function",
"addSiblings",
"(",
"Element",
"$",
"topNode",
")",
":",
"self",
"{",
"$",
"baselineScoreForSiblingParagraphs",
"=",
"$",
"this",
"->",
"getBaselineScoreForSiblings",
"(",
"$",
"topNode",
")",
";",
"$",
"previousSiblings",
"=",
"$",
"topNo... | @param Element $topNode
@return self | [
"@param",
"Element",
"$topNode"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Formatters/OutputFormatter.php#L341-L358 |
scotteh/php-goose | src/Modules/Formatters/OutputFormatter.php | OutputFormatter.getBaselineScoreForSiblings | private function getBaselineScoreForSiblings(Element $topNode): float {
$base = 100000;
$numberOfParagraphs = 0;
$scoreOfParagraphs = 0;
$nodesToCheck = $topNode->find('p, strong');
foreach ($nodesToCheck as $node) {
$nodeText = $node->text();
$wordStats = $this->config()->getStopWords()->getStopwordCount($nodeText);
$highLinkDensity = $this->isHighLinkDensity($node);
if ($wordStats->getStopWordCount() > 2 && !$highLinkDensity) {
$numberOfParagraphs += 1;
$scoreOfParagraphs += $wordStats->getStopWordCount();
}
}
if ($numberOfParagraphs > 0) {
$base = $scoreOfParagraphs / $numberOfParagraphs;
}
return $base;
} | php | private function getBaselineScoreForSiblings(Element $topNode): float {
$base = 100000;
$numberOfParagraphs = 0;
$scoreOfParagraphs = 0;
$nodesToCheck = $topNode->find('p, strong');
foreach ($nodesToCheck as $node) {
$nodeText = $node->text();
$wordStats = $this->config()->getStopWords()->getStopwordCount($nodeText);
$highLinkDensity = $this->isHighLinkDensity($node);
if ($wordStats->getStopWordCount() > 2 && !$highLinkDensity) {
$numberOfParagraphs += 1;
$scoreOfParagraphs += $wordStats->getStopWordCount();
}
}
if ($numberOfParagraphs > 0) {
$base = $scoreOfParagraphs / $numberOfParagraphs;
}
return $base;
} | [
"private",
"function",
"getBaselineScoreForSiblings",
"(",
"Element",
"$",
"topNode",
")",
":",
"float",
"{",
"$",
"base",
"=",
"100000",
";",
"$",
"numberOfParagraphs",
"=",
"0",
";",
"$",
"scoreOfParagraphs",
"=",
"0",
";",
"$",
"nodesToCheck",
"=",
"$",
... | we could have long articles that have tons of paragraphs so if we tried to calculate the base score against
the total text score of those paragraphs it would be unfair. So we need to normalize the score based on the average scoring
of the paragraphs within the top node. For example if our total score of 10 paragraphs was 1000 but each had an average value of
100 then 100 should be our base.
@param Element $topNode
@return float | [
"we",
"could",
"have",
"long",
"articles",
"that",
"have",
"tons",
"of",
"paragraphs",
"so",
"if",
"we",
"tried",
"to",
"calculate",
"the",
"base",
"score",
"against",
"the",
"total",
"text",
"score",
"of",
"those",
"paragraphs",
"it",
"would",
"be",
"unfa... | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Formatters/OutputFormatter.php#L370-L392 |
scotteh/php-goose | src/Modules/Extractors/ImageExtractor.php | ImageExtractor.checkForMetaTag | private function checkForMetaTag(): ?Image {
$image = $this->checkForTwitterTag();
if ($image) {
return $image;
}
$image = $this->checkForOpenGraphTag();
if ($image) {
return $image;
}
$image = $this->checkForLinkTag();
if ($image) {
return $image;
}
return null;
} | php | private function checkForMetaTag(): ?Image {
$image = $this->checkForTwitterTag();
if ($image) {
return $image;
}
$image = $this->checkForOpenGraphTag();
if ($image) {
return $image;
}
$image = $this->checkForLinkTag();
if ($image) {
return $image;
}
return null;
} | [
"private",
"function",
"checkForMetaTag",
"(",
")",
":",
"?",
"Image",
"{",
"$",
"image",
"=",
"$",
"this",
"->",
"checkForTwitterTag",
"(",
")",
";",
"if",
"(",
"$",
"image",
")",
"{",
"return",
"$",
"image",
";",
"}",
"$",
"image",
"=",
"$",
"thi... | Prefer Twitter images (as they tend to have the right size for us), then Open Graph images
(which seem to be smaller), and finally linked images.
@return Image|null | [
"Prefer",
"Twitter",
"images",
"(",
"as",
"they",
"tend",
"to",
"have",
"the",
"right",
"size",
"for",
"us",
")",
"then",
"Open",
"Graph",
"images",
"(",
"which",
"seem",
"to",
"be",
"smaller",
")",
"and",
"finally",
"linked",
"images",
"."
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ImageExtractor.php#L92-L112 |
scotteh/php-goose | src/Modules/Extractors/ImageExtractor.php | ImageExtractor.checkForLargeImages | private function checkForLargeImages(Element $node, int $parentDepthLevel, int $siblingDepthLevel): ?Image {
$goodLocalImages = $this->getImageCandidates($node);
$scoredLocalImages = $this->scoreLocalImages($goodLocalImages);
ksort($scoredLocalImages);
if (!empty($scoredLocalImages)) {
foreach ($scoredLocalImages as $imageScore => $scoredLocalImage) {
$mainImage = new Image();
$mainImage->setImageSrc($scoredLocalImage->getImgSrc());
$mainImage->setImageExtractionType('bigimage');
$mainImage->setConfidenceScore(100 / count($scoredLocalImages));
$mainImage->setImageScore($imageScore);
$mainImage->setBytes($scoredLocalImage->getBytes());
$mainImage->setHeight($scoredLocalImage->getHeight());
$mainImage->setWidth($scoredLocalImage->getWidth());
return $mainImage;
}
} else {
$depthObj = $this->getDepthLevel($node, $parentDepthLevel, $siblingDepthLevel);
if ($depthObj && NULL !== $depthObj->node) {
return $this->checkForLargeImages($depthObj->node, $depthObj->parentDepth, $depthObj->siblingDepth);
}
}
return null;
} | php | private function checkForLargeImages(Element $node, int $parentDepthLevel, int $siblingDepthLevel): ?Image {
$goodLocalImages = $this->getImageCandidates($node);
$scoredLocalImages = $this->scoreLocalImages($goodLocalImages);
ksort($scoredLocalImages);
if (!empty($scoredLocalImages)) {
foreach ($scoredLocalImages as $imageScore => $scoredLocalImage) {
$mainImage = new Image();
$mainImage->setImageSrc($scoredLocalImage->getImgSrc());
$mainImage->setImageExtractionType('bigimage');
$mainImage->setConfidenceScore(100 / count($scoredLocalImages));
$mainImage->setImageScore($imageScore);
$mainImage->setBytes($scoredLocalImage->getBytes());
$mainImage->setHeight($scoredLocalImage->getHeight());
$mainImage->setWidth($scoredLocalImage->getWidth());
return $mainImage;
}
} else {
$depthObj = $this->getDepthLevel($node, $parentDepthLevel, $siblingDepthLevel);
if ($depthObj && NULL !== $depthObj->node) {
return $this->checkForLargeImages($depthObj->node, $depthObj->parentDepth, $depthObj->siblingDepth);
}
}
return null;
} | [
"private",
"function",
"checkForLargeImages",
"(",
"Element",
"$",
"node",
",",
"int",
"$",
"parentDepthLevel",
",",
"int",
"$",
"siblingDepthLevel",
")",
":",
"?",
"Image",
"{",
"$",
"goodLocalImages",
"=",
"$",
"this",
"->",
"getImageCandidates",
"(",
"$",
... | although slow the best way to determine the best image is to download them and check the actual dimensions of the image when on disk
so we'll go through a phased approach...
1. get a list of ALL images from the parent node
2. filter out any bad image names that we know of (gifs, ads, etc..)
3. do a head request on each file to make sure it meets our bare requirements
4. any images left over let's do a full GET request, download em to disk and check their dimensions
5. Score images based on different factors like height/width and possibly things like color density
@param Element $node
@param int $parentDepthLevel
@param int $siblingDepthLevel
@return Image|null | [
"although",
"slow",
"the",
"best",
"way",
"to",
"determine",
"the",
"best",
"image",
"is",
"to",
"download",
"them",
"and",
"check",
"the",
"actual",
"dimensions",
"of",
"the",
"image",
"when",
"on",
"disk",
"so",
"we",
"ll",
"go",
"through",
"a",
"phase... | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ImageExtractor.php#L129-L158 |
scotteh/php-goose | src/Modules/Extractors/ImageExtractor.php | ImageExtractor.getDepthLevel | private function getDepthLevel(Element $node, int $parentDepth, int $siblingDepth): ?\stdClass {
if (is_null($node) || !($node->parent() instanceof Element)) {
return null;
}
if ($parentDepth > self::$MAX_PARENT_DEPTH) {
return null;
}
// Find previous sibling element node
$siblingNode = $node->preceding(function($node) {
return $node instanceof Element;
});
if (is_null($siblingNode)) {
return (object)[
'node' => $node->parent(),
'parentDepth' => $parentDepth + 1,
'siblingDepth' => 0,
];
}
return (object)[
'node' => $siblingNode,
'parentDepth' => $parentDepth,
'siblingDepth' => $siblingDepth + 1,
];
} | php | private function getDepthLevel(Element $node, int $parentDepth, int $siblingDepth): ?\stdClass {
if (is_null($node) || !($node->parent() instanceof Element)) {
return null;
}
if ($parentDepth > self::$MAX_PARENT_DEPTH) {
return null;
}
// Find previous sibling element node
$siblingNode = $node->preceding(function($node) {
return $node instanceof Element;
});
if (is_null($siblingNode)) {
return (object)[
'node' => $node->parent(),
'parentDepth' => $parentDepth + 1,
'siblingDepth' => 0,
];
}
return (object)[
'node' => $siblingNode,
'parentDepth' => $parentDepth,
'siblingDepth' => $siblingDepth + 1,
];
} | [
"private",
"function",
"getDepthLevel",
"(",
"Element",
"$",
"node",
",",
"int",
"$",
"parentDepth",
",",
"int",
"$",
"siblingDepth",
")",
":",
"?",
"\\",
"stdClass",
"{",
"if",
"(",
"is_null",
"(",
"$",
"node",
")",
"||",
"!",
"(",
"$",
"node",
"->"... | @param Element $node
@param int $parentDepth
@param int $siblingDepth
@return object|null | [
"@param",
"Element",
"$node",
"@param",
"int",
"$parentDepth",
"@param",
"int",
"$siblingDepth"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ImageExtractor.php#L167-L194 |
scotteh/php-goose | src/Modules/Extractors/ImageExtractor.php | ImageExtractor.scoreLocalImages | private function scoreLocalImages($locallyStoredImages): array {
$results = [];
$i = 1;
$initialArea = 0;
// Limit to the first 30 images
$locallyStoredImages = array_slice($locallyStoredImages, 0, 30);
foreach ($locallyStoredImages as $locallyStoredImage) {
$sequenceScore = 1 / $i;
$area = $locallyStoredImage->getWidth() * $locallyStoredImage->getHeight();
if ($initialArea == 0) {
$initialArea = $area * 1.48;
$totalScore = 1;
} else {
$areaDifference = $area * $initialArea;
$totalScore = $sequenceScore * $areaDifference;
}
$i++;
$results[$totalScore] = $locallyStoredImage;
}
return $results;
} | php | private function scoreLocalImages($locallyStoredImages): array {
$results = [];
$i = 1;
$initialArea = 0;
// Limit to the first 30 images
$locallyStoredImages = array_slice($locallyStoredImages, 0, 30);
foreach ($locallyStoredImages as $locallyStoredImage) {
$sequenceScore = 1 / $i;
$area = $locallyStoredImage->getWidth() * $locallyStoredImage->getHeight();
if ($initialArea == 0) {
$initialArea = $area * 1.48;
$totalScore = 1;
} else {
$areaDifference = $area * $initialArea;
$totalScore = $sequenceScore * $areaDifference;
}
$i++;
$results[$totalScore] = $locallyStoredImage;
}
return $results;
} | [
"private",
"function",
"scoreLocalImages",
"(",
"$",
"locallyStoredImages",
")",
":",
"array",
"{",
"$",
"results",
"=",
"[",
"]",
";",
"$",
"i",
"=",
"1",
";",
"$",
"initialArea",
"=",
"0",
";",
"// Limit to the first 30 images",
"$",
"locallyStoredImages",
... | Set image score and on locally downloaded images
we're going to score the images in the order in which they appear so images higher up will have more importance,
we'll count the area of the 1st image as a score of 1 and then calculate how much larger or small each image after it is
we'll also make sure to try and weed out banner type ad blocks that have big widths and small heights or vice versa
so if the image is 3rd found in the dom it's sequence score would be 1 / 3 = .33 * diff in area from the first image
@param LocallyStoredImage[] $locallyStoredImages
@return LocallyStoredImage[] | [
"Set",
"image",
"score",
"and",
"on",
"locally",
"downloaded",
"images"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ImageExtractor.php#L208-L234 |
scotteh/php-goose | src/Modules/Extractors/ImageExtractor.php | ImageExtractor.filterBadNames | private function filterBadNames(NodeList $images): array {
$goodImages = [];
foreach ($images as $image) {
if ($this->isOkImageFileName($image)) {
$goodImages[] = $image;
} else {
$image->remove();
}
}
return $goodImages;
} | php | private function filterBadNames(NodeList $images): array {
$goodImages = [];
foreach ($images as $image) {
if ($this->isOkImageFileName($image)) {
$goodImages[] = $image;
} else {
$image->remove();
}
}
return $goodImages;
} | [
"private",
"function",
"filterBadNames",
"(",
"NodeList",
"$",
"images",
")",
":",
"array",
"{",
"$",
"goodImages",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"images",
"as",
"$",
"image",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"isOkImageFileName",
"(",... | takes a list of image elements and filters out the ones with bad names
@param \DOMWrap\NodeList $images
@return Element[] | [
"takes",
"a",
"list",
"of",
"image",
"elements",
"and",
"filters",
"out",
"the",
"ones",
"with",
"bad",
"names"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ImageExtractor.php#L273-L285 |
scotteh/php-goose | src/Modules/Extractors/ImageExtractor.php | ImageExtractor.isOkImageFileName | private function isOkImageFileName(Element $imageNode): bool {
$imgSrc = $imageNode->attr('src');
if (empty($imgSrc)) {
return false;
}
$regex = '@' . implode('|', $this->badFileNames) . '@i';
if (preg_match($regex, $imgSrc)) {
return false;
}
return true;
} | php | private function isOkImageFileName(Element $imageNode): bool {
$imgSrc = $imageNode->attr('src');
if (empty($imgSrc)) {
return false;
}
$regex = '@' . implode('|', $this->badFileNames) . '@i';
if (preg_match($regex, $imgSrc)) {
return false;
}
return true;
} | [
"private",
"function",
"isOkImageFileName",
"(",
"Element",
"$",
"imageNode",
")",
":",
"bool",
"{",
"$",
"imgSrc",
"=",
"$",
"imageNode",
"->",
"attr",
"(",
"'src'",
")",
";",
"if",
"(",
"empty",
"(",
"$",
"imgSrc",
")",
")",
"{",
"return",
"false",
... | will check the image src against a list of bad image files we know of like buttons, etc...
@param Element $imageNode
@return bool | [
"will",
"check",
"the",
"image",
"src",
"against",
"a",
"list",
"of",
"bad",
"image",
"files",
"we",
"know",
"of",
"like",
"buttons",
"etc",
"..."
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ImageExtractor.php#L294-L308 |
scotteh/php-goose | src/Modules/Extractors/ImageExtractor.php | ImageExtractor.getImageCandidates | private function getImageCandidates(Element $node): array {
$images = $node->find('img');
$filteredImages = $this->filterBadNames($images);
$goodImages = $this->findImagesThatPassByteSizeTest($filteredImages);
return $goodImages;
} | php | private function getImageCandidates(Element $node): array {
$images = $node->find('img');
$filteredImages = $this->filterBadNames($images);
$goodImages = $this->findImagesThatPassByteSizeTest($filteredImages);
return $goodImages;
} | [
"private",
"function",
"getImageCandidates",
"(",
"Element",
"$",
"node",
")",
":",
"array",
"{",
"$",
"images",
"=",
"$",
"node",
"->",
"find",
"(",
"'img'",
")",
";",
"$",
"filteredImages",
"=",
"$",
"this",
"->",
"filterBadNames",
"(",
"$",
"images",
... | @param Element $node
@return LocallyStoredImage[] | [
"@param",
"Element",
"$node"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ImageExtractor.php#L315-L321 |
scotteh/php-goose | src/Modules/Extractors/ImageExtractor.php | ImageExtractor.checkForTag | private function checkForTag(string $selector, string $attr, string $type): ?Image {
$meta = $this->article()->getRawDoc()->find($selector);
if (!$meta->count()) {
return null;
}
$node = $meta->first();
if (!($node instanceof Element)) {
return null;
}
if (!$node->hasAttribute($attr) || !$node->attr($attr)) {
return null;
}
$imagePath = $this->buildImagePath($node->attr($attr));
$mainImage = new Image();
$mainImage->setImageSrc($imagePath);
$mainImage->setImageExtractionType($type);
$mainImage->setConfidenceScore(100);
$locallyStoredImage = $this->getLocallyStoredImage($mainImage->getImageSrc());
if (!empty($locallyStoredImage)) {
$mainImage->setBytes($locallyStoredImage->getBytes());
$mainImage->setHeight($locallyStoredImage->getHeight());
$mainImage->setWidth($locallyStoredImage->getWidth());
}
return $this->ensureMinimumImageSize($mainImage);
} | php | private function checkForTag(string $selector, string $attr, string $type): ?Image {
$meta = $this->article()->getRawDoc()->find($selector);
if (!$meta->count()) {
return null;
}
$node = $meta->first();
if (!($node instanceof Element)) {
return null;
}
if (!$node->hasAttribute($attr) || !$node->attr($attr)) {
return null;
}
$imagePath = $this->buildImagePath($node->attr($attr));
$mainImage = new Image();
$mainImage->setImageSrc($imagePath);
$mainImage->setImageExtractionType($type);
$mainImage->setConfidenceScore(100);
$locallyStoredImage = $this->getLocallyStoredImage($mainImage->getImageSrc());
if (!empty($locallyStoredImage)) {
$mainImage->setBytes($locallyStoredImage->getBytes());
$mainImage->setHeight($locallyStoredImage->getHeight());
$mainImage->setWidth($locallyStoredImage->getWidth());
}
return $this->ensureMinimumImageSize($mainImage);
} | [
"private",
"function",
"checkForTag",
"(",
"string",
"$",
"selector",
",",
"string",
"$",
"attr",
",",
"string",
"$",
"type",
")",
":",
"?",
"Image",
"{",
"$",
"meta",
"=",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getRawDoc",
"(",
")",
"->",
... | @param string $selector
@param string $attr
@param string $type
@return Image|null | [
"@param",
"string",
"$selector",
"@param",
"string",
"$attr",
"@param",
"string",
"$type"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ImageExtractor.php#L394-L426 |
scotteh/php-goose | src/Modules/Extractors/ImageExtractor.php | ImageExtractor.ensureMinimumImageSize | private function ensureMinimumImageSize(Image $mainImage): ?Image {
if ($mainImage->getWidth() >= $this->config()->get('image_min_width')
&& $mainImage->getHeight() >= $this->config()->get('image_min_height')) {
return $mainImage;
}
return null;
} | php | private function ensureMinimumImageSize(Image $mainImage): ?Image {
if ($mainImage->getWidth() >= $this->config()->get('image_min_width')
&& $mainImage->getHeight() >= $this->config()->get('image_min_height')) {
return $mainImage;
}
return null;
} | [
"private",
"function",
"ensureMinimumImageSize",
"(",
"Image",
"$",
"mainImage",
")",
":",
"?",
"Image",
"{",
"if",
"(",
"$",
"mainImage",
"->",
"getWidth",
"(",
")",
">=",
"$",
"this",
"->",
"config",
"(",
")",
"->",
"get",
"(",
"'image_min_width'",
")"... | @param Image $mainImage
@return Image|null | [
"@param",
"Image",
"$mainImage"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ImageExtractor.php#L433-L440 |
scotteh/php-goose | src/Modules/Extractors/ImageExtractor.php | ImageExtractor.getLocallyStoredImage | private function getLocallyStoredImage(string $imageSrc, bool $returnAll = false): ?LocallyStoredImage {
$locallyStoredImages = ImageUtils::storeImagesToLocalFile([$imageSrc], $returnAll, $this->config());
return array_shift($locallyStoredImages);
} | php | private function getLocallyStoredImage(string $imageSrc, bool $returnAll = false): ?LocallyStoredImage {
$locallyStoredImages = ImageUtils::storeImagesToLocalFile([$imageSrc], $returnAll, $this->config());
return array_shift($locallyStoredImages);
} | [
"private",
"function",
"getLocallyStoredImage",
"(",
"string",
"$",
"imageSrc",
",",
"bool",
"$",
"returnAll",
"=",
"false",
")",
":",
"?",
"LocallyStoredImage",
"{",
"$",
"locallyStoredImages",
"=",
"ImageUtils",
"::",
"storeImagesToLocalFile",
"(",
"[",
"$",
"... | @param string $imageSrc
@param bool $returnAll
@return LocallyStoredImage|null | [
"@param",
"string",
"$imageSrc",
"@param",
"bool",
"$returnAll"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ImageExtractor.php#L448-L452 |
scotteh/php-goose | src/Modules/Extractors/ImageExtractor.php | ImageExtractor.getLocallyStoredImages | private function getLocallyStoredImages($imageSrcs, bool $returnAll = false): array {
return ImageUtils::storeImagesToLocalFile($imageSrcs, $returnAll, $this->config());
} | php | private function getLocallyStoredImages($imageSrcs, bool $returnAll = false): array {
return ImageUtils::storeImagesToLocalFile($imageSrcs, $returnAll, $this->config());
} | [
"private",
"function",
"getLocallyStoredImages",
"(",
"$",
"imageSrcs",
",",
"bool",
"$",
"returnAll",
"=",
"false",
")",
":",
"array",
"{",
"return",
"ImageUtils",
"::",
"storeImagesToLocalFile",
"(",
"$",
"imageSrcs",
",",
"$",
"returnAll",
",",
"$",
"this",... | @param string[] $imageSrcs
@param bool $returnAll
@return LocallyStoredImage[] | [
"@param",
"string",
"[]",
"$imageSrcs",
"@param",
"bool",
"$returnAll"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ImageExtractor.php#L460-L462 |
scotteh/php-goose | src/Modules/Extractors/ImageExtractor.php | ImageExtractor.checkForKnownElements | private function checkForKnownElements(): ?Image {
if (!$this->article()->getRawDoc()) {
return null;
}
$knownImgDomNames = self::$KNOWN_IMG_DOM_NAMES;
$domain = $this->getCleanDomain();
$customSiteMapping = $this->customSiteMapping();
if (isset($customSiteMapping[$domain])) {
foreach (explode('|', $customSiteMapping[$domain]) as $class) {
$knownImgDomNames[] = $class;
}
}
$knownImage = null;
foreach ($knownImgDomNames as $knownName) {
$known = $this->article()->getRawDoc()->find('#' . $knownName);
if (!$known->count()) {
$known = $this->article()->getRawDoc()->find('.' . $knownName);
}
if ($known->count()) {
$mainImage = $known->first()->find('img');
if ($mainImage->count()) {
$knownImage = $mainImage->first();
}
}
}
if (is_null($knownImage)) {
return null;
}
$knownImgSrc = $knownImage->attr('src');
$mainImage = new Image();
$mainImage->setImageSrc($this->buildImagePath($knownImgSrc));
$mainImage->setImageExtractionType('known');
$mainImage->setConfidenceScore(90);
$locallyStoredImage = $this->getLocallyStoredImage($mainImage->getImageSrc());
if (!empty($locallyStoredImage)) {
$mainImage->setBytes($locallyStoredImage->getBytes());
$mainImage->setHeight($locallyStoredImage->getHeight());
$mainImage->setWidth($locallyStoredImage->getWidth());
}
return $this->ensureMinimumImageSize($mainImage);
} | php | private function checkForKnownElements(): ?Image {
if (!$this->article()->getRawDoc()) {
return null;
}
$knownImgDomNames = self::$KNOWN_IMG_DOM_NAMES;
$domain = $this->getCleanDomain();
$customSiteMapping = $this->customSiteMapping();
if (isset($customSiteMapping[$domain])) {
foreach (explode('|', $customSiteMapping[$domain]) as $class) {
$knownImgDomNames[] = $class;
}
}
$knownImage = null;
foreach ($knownImgDomNames as $knownName) {
$known = $this->article()->getRawDoc()->find('#' . $knownName);
if (!$known->count()) {
$known = $this->article()->getRawDoc()->find('.' . $knownName);
}
if ($known->count()) {
$mainImage = $known->first()->find('img');
if ($mainImage->count()) {
$knownImage = $mainImage->first();
}
}
}
if (is_null($knownImage)) {
return null;
}
$knownImgSrc = $knownImage->attr('src');
$mainImage = new Image();
$mainImage->setImageSrc($this->buildImagePath($knownImgSrc));
$mainImage->setImageExtractionType('known');
$mainImage->setConfidenceScore(90);
$locallyStoredImage = $this->getLocallyStoredImage($mainImage->getImageSrc());
if (!empty($locallyStoredImage)) {
$mainImage->setBytes($locallyStoredImage->getBytes());
$mainImage->setHeight($locallyStoredImage->getHeight());
$mainImage->setWidth($locallyStoredImage->getWidth());
}
return $this->ensureMinimumImageSize($mainImage);
} | [
"private",
"function",
"checkForKnownElements",
"(",
")",
":",
"?",
"Image",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"article",
"(",
")",
"->",
"getRawDoc",
"(",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"knownImgDomNames",
"=",
"self",
"::",
"... | In here we check for known image contains from sites we've checked out like yahoo, techcrunch, etc... that have
known places to look for good images.
@todo enable this to use a series of settings files so people can define what the image ids/classes are on specific sites
@return Image|null | [
"In",
"here",
"we",
"check",
"for",
"known",
"image",
"contains",
"from",
"sites",
"we",
"ve",
"checked",
"out",
"like",
"yahoo",
"techcrunch",
"etc",
"...",
"that",
"have",
"known",
"places",
"to",
"look",
"for",
"good",
"images",
"."
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ImageExtractor.php#L479-L534 |
scotteh/php-goose | src/Modules/Extractors/ImageExtractor.php | ImageExtractor.buildImagePath | private function buildImagePath(string $imageSrc): string {
$parts = array(
'scheme',
'host',
'port',
'path',
'query',
);
$imageUrlParts = parse_url($imageSrc);
$articleUrlParts = parse_url($this->article()->getFinalUrl());
if (isset($imageUrlParts['path'], $articleUrlParts['path']) && $imageUrlParts['path'] && $imageUrlParts['path']{0} !== '/') {
$articleUrlDir = dirname($articleUrlParts['path']);
$imageUrlParts['path'] = $articleUrlDir . '/' . $imageUrlParts['path'];
}
foreach ($parts as $part) {
if (!isset($imageUrlParts[$part]) && isset($articleUrlParts[$part])) {
$imageUrlParts[$part] = $articleUrlParts[$part];
} else if (isset($imageUrlParts[$part]) && !isset($articleUrlParts[$part])) {
break;
}
}
return http_build_url($imageUrlParts, array());
} | php | private function buildImagePath(string $imageSrc): string {
$parts = array(
'scheme',
'host',
'port',
'path',
'query',
);
$imageUrlParts = parse_url($imageSrc);
$articleUrlParts = parse_url($this->article()->getFinalUrl());
if (isset($imageUrlParts['path'], $articleUrlParts['path']) && $imageUrlParts['path'] && $imageUrlParts['path']{0} !== '/') {
$articleUrlDir = dirname($articleUrlParts['path']);
$imageUrlParts['path'] = $articleUrlDir . '/' . $imageUrlParts['path'];
}
foreach ($parts as $part) {
if (!isset($imageUrlParts[$part]) && isset($articleUrlParts[$part])) {
$imageUrlParts[$part] = $articleUrlParts[$part];
} else if (isset($imageUrlParts[$part]) && !isset($articleUrlParts[$part])) {
break;
}
}
return http_build_url($imageUrlParts, array());
} | [
"private",
"function",
"buildImagePath",
"(",
"string",
"$",
"imageSrc",
")",
":",
"string",
"{",
"$",
"parts",
"=",
"array",
"(",
"'scheme'",
",",
"'host'",
",",
"'port'",
",",
"'path'",
",",
"'query'",
",",
")",
";",
"$",
"imageUrlParts",
"=",
"parse_u... | This method will take an image path and build out the absolute path to that image
using the initial url we crawled so we can find a link to the image if they use relative urls like ../myimage.jpg
@param string $imageSrc
@return string | [
"This",
"method",
"will",
"take",
"an",
"image",
"path",
"and",
"build",
"out",
"the",
"absolute",
"path",
"to",
"that",
"image",
"using",
"the",
"initial",
"url",
"we",
"crawled",
"so",
"we",
"can",
"find",
"a",
"link",
"to",
"the",
"image",
"if",
"th... | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ImageExtractor.php#L544-L570 |
scotteh/php-goose | src/Modules/Extractors/ImageExtractor.php | ImageExtractor.customSiteMapping | private function customSiteMapping(): array {
if (empty(self::$CUSTOM_SITE_MAPPING)) {
$file = __DIR__ . '/../../../resources/images/known-image-css.txt';
$lines = explode("\n", str_replace(["\r\n", "\r"], "\n", file_get_contents($file)));
foreach ($lines as $line) {
list($domain, $css) = explode('^', $line);
self::$CUSTOM_SITE_MAPPING[$domain] = $css;
}
}
return self::$CUSTOM_SITE_MAPPING;
} | php | private function customSiteMapping(): array {
if (empty(self::$CUSTOM_SITE_MAPPING)) {
$file = __DIR__ . '/../../../resources/images/known-image-css.txt';
$lines = explode("\n", str_replace(["\r\n", "\r"], "\n", file_get_contents($file)));
foreach ($lines as $line) {
list($domain, $css) = explode('^', $line);
self::$CUSTOM_SITE_MAPPING[$domain] = $css;
}
}
return self::$CUSTOM_SITE_MAPPING;
} | [
"private",
"function",
"customSiteMapping",
"(",
")",
":",
"array",
"{",
"if",
"(",
"empty",
"(",
"self",
"::",
"$",
"CUSTOM_SITE_MAPPING",
")",
")",
"{",
"$",
"file",
"=",
"__DIR__",
".",
"'/../../../resources/images/known-image-css.txt'",
";",
"$",
"lines",
... | @param string[]
@return array | [
"@param",
"string",
"[]"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Extractors/ImageExtractor.php#L577-L591 |
scotteh/php-goose | src/Modules/Cleaners/DocumentCleaner.php | DocumentCleaner.run | public function run(Article $article): self {
$this->document($article->getDoc());
$this->removeXPath('//comment()');
$this->replace('em, strong, b, i, strike, del, ins', function($node) {
return !$node->find('img')->count();
});
$this->replace('span[class~=dropcap], span[class~=drop_cap]');
$this->remove('script, style');
$this->remove('header, footer, input, form, button, aside');
$this->removeBadTags();
$this->remove("[id='caption'],[class='caption']");
$this->remove("[id*=' google '],[class*=' google ']");
$this->remove("[id*='more']:not([id^=entry-]),[class*='more']:not([class^=entry-])");
$this->remove("[id*='facebook']:not([id*='-facebook']),[class*='facebook']:not([class*='-facebook'])");
$this->remove("[id*='facebook-broadcasting'],[class*='facebook-broadcasting']");
$this->remove("[id*='twitter']:not([id*='-twitter']),[class*='twitter']:not([class*='-twitter'])");
$this->replace('span', function($node) {
if (is_null($node->parent())) {
return false;
}
return $node->parent()->is('p');
});
$this->convertToParagraph('div, span, article');
return $this;
} | php | public function run(Article $article): self {
$this->document($article->getDoc());
$this->removeXPath('//comment()');
$this->replace('em, strong, b, i, strike, del, ins', function($node) {
return !$node->find('img')->count();
});
$this->replace('span[class~=dropcap], span[class~=drop_cap]');
$this->remove('script, style');
$this->remove('header, footer, input, form, button, aside');
$this->removeBadTags();
$this->remove("[id='caption'],[class='caption']");
$this->remove("[id*=' google '],[class*=' google ']");
$this->remove("[id*='more']:not([id^=entry-]),[class*='more']:not([class^=entry-])");
$this->remove("[id*='facebook']:not([id*='-facebook']),[class*='facebook']:not([class*='-facebook'])");
$this->remove("[id*='facebook-broadcasting'],[class*='facebook-broadcasting']");
$this->remove("[id*='twitter']:not([id*='-twitter']),[class*='twitter']:not([class*='-twitter'])");
$this->replace('span', function($node) {
if (is_null($node->parent())) {
return false;
}
return $node->parent()->is('p');
});
$this->convertToParagraph('div, span, article');
return $this;
} | [
"public",
"function",
"run",
"(",
"Article",
"$",
"article",
")",
":",
"self",
"{",
"$",
"this",
"->",
"document",
"(",
"$",
"article",
"->",
"getDoc",
"(",
")",
")",
";",
"$",
"this",
"->",
"removeXPath",
"(",
"'//comment()'",
")",
";",
"$",
"this",... | Clean the contents of the supplied article document
@inheritdoc | [
"Clean",
"the",
"contents",
"of",
"the",
"supplied",
"article",
"document"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Cleaners/DocumentCleaner.php#L61-L88 |
scotteh/php-goose | src/Modules/Cleaners/DocumentCleaner.php | DocumentCleaner.remove | private function remove(string $selector, callable $callback = null): self {
$nodes = $this->document()->find($selector);
foreach ($nodes as $node) {
if (is_null($callback) || $callback($node)) {
$node->remove();
}
}
return $this;
} | php | private function remove(string $selector, callable $callback = null): self {
$nodes = $this->document()->find($selector);
foreach ($nodes as $node) {
if (is_null($callback) || $callback($node)) {
$node->remove();
}
}
return $this;
} | [
"private",
"function",
"remove",
"(",
"string",
"$",
"selector",
",",
"callable",
"$",
"callback",
"=",
"null",
")",
":",
"self",
"{",
"$",
"nodes",
"=",
"$",
"this",
"->",
"document",
"(",
")",
"->",
"find",
"(",
"$",
"selector",
")",
";",
"foreach"... | Remove via CSS selectors
@param string $selector
@param callable $callback
@return self | [
"Remove",
"via",
"CSS",
"selectors"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Cleaners/DocumentCleaner.php#L98-L108 |
scotteh/php-goose | src/Modules/Cleaners/DocumentCleaner.php | DocumentCleaner.removeXPath | private function removeXPath(string $expression, callable $callback = null): self {
$nodes = $this->document()->findXPath($expression);
foreach ($nodes as $node) {
if (is_null($callback) || $callback($node)) {
$node->remove();
}
}
return $this;
} | php | private function removeXPath(string $expression, callable $callback = null): self {
$nodes = $this->document()->findXPath($expression);
foreach ($nodes as $node) {
if (is_null($callback) || $callback($node)) {
$node->remove();
}
}
return $this;
} | [
"private",
"function",
"removeXPath",
"(",
"string",
"$",
"expression",
",",
"callable",
"$",
"callback",
"=",
"null",
")",
":",
"self",
"{",
"$",
"nodes",
"=",
"$",
"this",
"->",
"document",
"(",
")",
"->",
"findXPath",
"(",
"$",
"expression",
")",
";... | Remove using via XPath expressions
@param string $expression
@param callable $callback
@return self | [
"Remove",
"using",
"via",
"XPath",
"expressions"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Cleaners/DocumentCleaner.php#L118-L128 |
scotteh/php-goose | src/Modules/Cleaners/DocumentCleaner.php | DocumentCleaner.replace | private function replace(string $selector, callable $callback = null): self {
$nodes = $this->document()->find($selector);
foreach ($nodes as $node) {
if (is_null($callback) || $callback($node)) {
$node->replaceWith(new Text((string)$node->text()));
}
}
return $this;
} | php | private function replace(string $selector, callable $callback = null): self {
$nodes = $this->document()->find($selector);
foreach ($nodes as $node) {
if (is_null($callback) || $callback($node)) {
$node->replaceWith(new Text((string)$node->text()));
}
}
return $this;
} | [
"private",
"function",
"replace",
"(",
"string",
"$",
"selector",
",",
"callable",
"$",
"callback",
"=",
"null",
")",
":",
"self",
"{",
"$",
"nodes",
"=",
"$",
"this",
"->",
"document",
"(",
")",
"->",
"find",
"(",
"$",
"selector",
")",
";",
"foreach... | Replace node with its textual contents via CSS selectors
@param string $selector
@param callable $callback
@return self | [
"Replace",
"node",
"with",
"its",
"textual",
"contents",
"via",
"CSS",
"selectors"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Cleaners/DocumentCleaner.php#L138-L148 |
scotteh/php-goose | src/Modules/Cleaners/DocumentCleaner.php | DocumentCleaner.removeBadTags | private function removeBadTags(): self {
$lists = [
"[%s^='%s']" => $this->startsWithNodes,
"[%s*='%s']" => $this->searchNodes,
"[%s$='%s']" => $this->endsWithNodes,
"[%s='%s']" => $this->equalsNodes,
];
$attrs = [
'id',
'class',
'name',
];
$exceptions = array_map(function($value) {
return ':not(' . $value . ')';
}, $this->exceptionSelectors);
$exceptions = implode('', $exceptions);
foreach ($lists as $expr => $list) {
foreach ($list as $value) {
foreach ($attrs as $attr) {
$selector = sprintf($expr, $attr, $value) . $exceptions;
foreach ($this->document()->find($selector) as $node) {
$node->remove();
}
}
}
}
return $this;
} | php | private function removeBadTags(): self {
$lists = [
"[%s^='%s']" => $this->startsWithNodes,
"[%s*='%s']" => $this->searchNodes,
"[%s$='%s']" => $this->endsWithNodes,
"[%s='%s']" => $this->equalsNodes,
];
$attrs = [
'id',
'class',
'name',
];
$exceptions = array_map(function($value) {
return ':not(' . $value . ')';
}, $this->exceptionSelectors);
$exceptions = implode('', $exceptions);
foreach ($lists as $expr => $list) {
foreach ($list as $value) {
foreach ($attrs as $attr) {
$selector = sprintf($expr, $attr, $value) . $exceptions;
foreach ($this->document()->find($selector) as $node) {
$node->remove();
}
}
}
}
return $this;
} | [
"private",
"function",
"removeBadTags",
"(",
")",
":",
"self",
"{",
"$",
"lists",
"=",
"[",
"\"[%s^='%s']\"",
"=>",
"$",
"this",
"->",
"startsWithNodes",
",",
"\"[%s*='%s']\"",
"=>",
"$",
"this",
"->",
"searchNodes",
",",
"\"[%s$='%s']\"",
"=>",
"$",
"this",... | Remove unwanted junk elements based on pre-defined CSS selectors
@return self | [
"Remove",
"unwanted",
"junk",
"elements",
"based",
"on",
"pre",
"-",
"defined",
"CSS",
"selectors"
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Cleaners/DocumentCleaner.php#L155-L188 |
scotteh/php-goose | src/Modules/Cleaners/DocumentCleaner.php | DocumentCleaner.replaceElementsWithPara | private function replaceElementsWithPara(Element $node): ?self {
// Check to see if the node no longer exist.
// 'Ghost' nodes have their ownerDocument property set to null - will throw a warning on access.
// Use another common property with isset() - won't throw any warnings.
if (!isset($node->nodeName)) {
return null;
}
$newEl = $this->document()->createElement('p');
$newEl->append($node->contents()->detach());
foreach ($node->attributes as $attr) {
$newEl->attr($attr->localName, $attr->nodeValue);
}
$node->replaceWith($newEl);
return $this;
} | php | private function replaceElementsWithPara(Element $node): ?self {
// Check to see if the node no longer exist.
// 'Ghost' nodes have their ownerDocument property set to null - will throw a warning on access.
// Use another common property with isset() - won't throw any warnings.
if (!isset($node->nodeName)) {
return null;
}
$newEl = $this->document()->createElement('p');
$newEl->append($node->contents()->detach());
foreach ($node->attributes as $attr) {
$newEl->attr($attr->localName, $attr->nodeValue);
}
$node->replaceWith($newEl);
return $this;
} | [
"private",
"function",
"replaceElementsWithPara",
"(",
"Element",
"$",
"node",
")",
":",
"?",
"self",
"{",
"// Check to see if the node no longer exist.",
"// 'Ghost' nodes have their ownerDocument property set to null - will throw a warning on access.",
"// Use another common property w... | Replace supplied element with <p> new element.
@param Element $node
@return self|null | [
"Replace",
"supplied",
"element",
"with",
"<p",
">",
"new",
"element",
"."
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Cleaners/DocumentCleaner.php#L197-L216 |
scotteh/php-goose | src/Modules/Cleaners/DocumentCleaner.php | DocumentCleaner.convertToParagraph | private function convertToParagraph(string $selector): self {
$nodes = $this->document()->find($selector);
foreach ($nodes as $node) {
$tagNodes = $node->find('a, blockquote, dl, div, img, ol, p, pre, table, ul');
if (!$tagNodes->count()) {
$this->replaceElementsWithPara($node);
} else {
$replacements = $this->getReplacementNodes($node);
$node->contents()->remove();
$node->append($replacements);
}
}
return $this;
} | php | private function convertToParagraph(string $selector): self {
$nodes = $this->document()->find($selector);
foreach ($nodes as $node) {
$tagNodes = $node->find('a, blockquote, dl, div, img, ol, p, pre, table, ul');
if (!$tagNodes->count()) {
$this->replaceElementsWithPara($node);
} else {
$replacements = $this->getReplacementNodes($node);
$node->contents()->remove();
$node->append($replacements);
}
}
return $this;
} | [
"private",
"function",
"convertToParagraph",
"(",
"string",
"$",
"selector",
")",
":",
"self",
"{",
"$",
"nodes",
"=",
"$",
"this",
"->",
"document",
"(",
")",
"->",
"find",
"(",
"$",
"selector",
")",
";",
"foreach",
"(",
"$",
"nodes",
"as",
"$",
"no... | Convert wanted elements to <p> elements.
@param string $selector
@return self | [
"Convert",
"wanted",
"elements",
"to",
"<p",
">",
"elements",
"."
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Cleaners/DocumentCleaner.php#L225-L242 |
scotteh/php-goose | src/Modules/Cleaners/DocumentCleaner.php | DocumentCleaner.getFlushedBuffer | private function getFlushedBuffer(NodeList $replacementNodes): Element {
$newEl = $this->document()->createElement('p');
$newEl->append($replacementNodes);
return $newEl;
} | php | private function getFlushedBuffer(NodeList $replacementNodes): Element {
$newEl = $this->document()->createElement('p');
$newEl->append($replacementNodes);
return $newEl;
} | [
"private",
"function",
"getFlushedBuffer",
"(",
"NodeList",
"$",
"replacementNodes",
")",
":",
"Element",
"{",
"$",
"newEl",
"=",
"$",
"this",
"->",
"document",
"(",
")",
"->",
"createElement",
"(",
"'p'",
")",
";",
"$",
"newEl",
"->",
"append",
"(",
"$"... | Generate new <p> element with supplied content.
@param NodeList $replacementNodes
@return Element | [
"Generate",
"new",
"<p",
">",
"element",
"with",
"supplied",
"content",
"."
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Cleaners/DocumentCleaner.php#L251-L256 |
scotteh/php-goose | src/Modules/Cleaners/DocumentCleaner.php | DocumentCleaner.getReplacementNodes | private function getReplacementNodes(Element $node): NodeList {
$nodesToReturn = $node->newNodeList();
$nodesToRemove = $node->newNodeList();
$replacementNodes = $node->newNodeList();
$fnCompareSiblingNodes = function($node) {
if ($node->is(':not(a)') || $node->nodeType == XML_TEXT_NODE) {
return true;
}
};
foreach ($node->contents() as $child) {
if ($child->is('p') && $replacementNodes->count()) {
$nodesToReturn[] = $this->getFlushedBuffer($replacementNodes);
$replacementNodes->fromArray([]);
$nodesToReturn[] = $child;
} else if ($child->nodeType == XML_TEXT_NODE) {
$replaceText = $child->text();
if (!empty($replaceText)) {
// Get all previous sibling <a> nodes, the current text node, and all next sibling <a> nodes.
$siblings = $child
->precedingUntil($fnCompareSiblingNodes, 'a')
->merge([$child])
->merge($child->followingUntil($fnCompareSiblingNodes, 'a'));
foreach ($siblings as $sibling) {
// Place current nodes textual contents in-between previous and next nodes.
if ($sibling->isSameNode($child)) {
$replacementNodes[] = new Text($replaceText);
// Grab the contents of any unprocessed <a> siblings and flag them for removal.
} else if ($sibling->getAttribute('grv-usedalready') != 'yes') {
$sibling->setAttribute('grv-usedalready', 'yes');
$replacementNodes[] = $sibling->cloneNode(true);
$nodesToRemove[] = $sibling;
}
}
}
$nodesToRemove[] = $child;
} else {
if ($replacementNodes->count()) {
$nodesToReturn[] = $this->getFlushedBuffer($replacementNodes);
$replacementNodes->fromArray([]);
}
$nodesToReturn[] = $child;
}
}
// Flush any remaining replacementNodes left over from text nodes.
if ($replacementNodes->count()) {
$nodesToReturn[] = $this->getFlushedBuffer($replacementNodes);
}
// Remove potential duplicate <a> tags.
foreach ($nodesToReturn as $key => $return) {
if ($nodesToRemove->exists($return)) {
unset($nodesToReturn[$key]);
}
}
$nodesToRemove->remove();
return $nodesToReturn;
} | php | private function getReplacementNodes(Element $node): NodeList {
$nodesToReturn = $node->newNodeList();
$nodesToRemove = $node->newNodeList();
$replacementNodes = $node->newNodeList();
$fnCompareSiblingNodes = function($node) {
if ($node->is(':not(a)') || $node->nodeType == XML_TEXT_NODE) {
return true;
}
};
foreach ($node->contents() as $child) {
if ($child->is('p') && $replacementNodes->count()) {
$nodesToReturn[] = $this->getFlushedBuffer($replacementNodes);
$replacementNodes->fromArray([]);
$nodesToReturn[] = $child;
} else if ($child->nodeType == XML_TEXT_NODE) {
$replaceText = $child->text();
if (!empty($replaceText)) {
// Get all previous sibling <a> nodes, the current text node, and all next sibling <a> nodes.
$siblings = $child
->precedingUntil($fnCompareSiblingNodes, 'a')
->merge([$child])
->merge($child->followingUntil($fnCompareSiblingNodes, 'a'));
foreach ($siblings as $sibling) {
// Place current nodes textual contents in-between previous and next nodes.
if ($sibling->isSameNode($child)) {
$replacementNodes[] = new Text($replaceText);
// Grab the contents of any unprocessed <a> siblings and flag them for removal.
} else if ($sibling->getAttribute('grv-usedalready') != 'yes') {
$sibling->setAttribute('grv-usedalready', 'yes');
$replacementNodes[] = $sibling->cloneNode(true);
$nodesToRemove[] = $sibling;
}
}
}
$nodesToRemove[] = $child;
} else {
if ($replacementNodes->count()) {
$nodesToReturn[] = $this->getFlushedBuffer($replacementNodes);
$replacementNodes->fromArray([]);
}
$nodesToReturn[] = $child;
}
}
// Flush any remaining replacementNodes left over from text nodes.
if ($replacementNodes->count()) {
$nodesToReturn[] = $this->getFlushedBuffer($replacementNodes);
}
// Remove potential duplicate <a> tags.
foreach ($nodesToReturn as $key => $return) {
if ($nodesToRemove->exists($return)) {
unset($nodesToReturn[$key]);
}
}
$nodesToRemove->remove();
return $nodesToReturn;
} | [
"private",
"function",
"getReplacementNodes",
"(",
"Element",
"$",
"node",
")",
":",
"NodeList",
"{",
"$",
"nodesToReturn",
"=",
"$",
"node",
"->",
"newNodeList",
"(",
")",
";",
"$",
"nodesToRemove",
"=",
"$",
"node",
"->",
"newNodeList",
"(",
")",
";",
... | Generate <p> element replacements for supplied elements child nodes as required.
@param Element $node
@return NodeList $nodesToReturn Replacement elements | [
"Generate",
"<p",
">",
"element",
"replacements",
"for",
"supplied",
"elements",
"child",
"nodes",
"as",
"required",
"."
] | train | https://github.com/scotteh/php-goose/blob/67a3f5e3804281e890d269a81614ee86c9d8a92f/src/Modules/Cleaners/DocumentCleaner.php#L265-L333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.