/** * Function to create a new FluentDOM instance and loads data into it if * a valid $source is provided. * * @param mixed $source * @param string $contentType optional, default value 'text/xml' * @return FluentDOM */ function FluentDOM($source = NULL, $contentType = 'text/xml') { $result = new FluentDOM(); if (isset($source)) { return $result->load($source, $contentType); } else { return $result; } }
/** * @group TraversingFilter */ public function testMap() { $fd = $this->getFixtureFromFile(__FUNCTION__); $fd->find('//p')->append(implode(', ', $fd->find('//input')->map(function ($node, $index) { $nodeFd = new FluentDOM(); return $nodeFd->load($node)->attr("value"); }))); $this->assertFluentDOMEqualsXMLFile(__FUNCTION__, $fd); }
/** * @param string $string * @return FluentDOM */ protected function getFixtureFromString($string) { $dom = new DOMDocument(); $dom->loadXML($string); $loader = $this->getMock('FluentDOMLoader'); $loader->expects($this->once())->method('load')->with($this->equalTo(''))->will($this->returnValue($dom)); $fd = new FluentDOM(); $fd->setLoaders(array($loader)); return $fd->load(''); }
/** * Create a dom element. Cast to string to get the HTML. * * @param $name * @param array $attrs * * @return \FluentDOM\Element */ protected function createElement($name, $attrs = []) { $el = \FluentDOM::create()->element($name); foreach ($attrs as $k => $v) { $el->setAttribute($k, $v); } return $el; }
/** * Allow write access to "css" as a dynamic property. * Call inherited method for other properties. * * This allows to set css style properties using an array. * * @see FluentDOM::__get() * @param string $name * @param mixed $value */ public function __set($name, $value) { switch ($name) { case 'css': $this->css($value); return; } parent::__set($name, $value); }
/** * @group CoreFunctions * @covers FluentDOMCore::namespaces */ public function testNamespacesWithChaining() { $fd = new FluentDOM(); $fd->namespaces(array('test' => 'http://test.only/')); $fdChild = $fd->spawn(); $this->assertAttributeEquals(array('test' => 'http://test.only/'), '_namespaces', $fdChild); }
<?php namespace FluentDOM\Symfony\CssSelector; \FluentDOM::registerXpathTransformer(function () { return new Transformer(); });
<?php require '../../FluentDOM.php'; $xmlFile = 'hello.xml'; // create object $fd = new FluentDOM(); // load file $fd->load($xmlFile); echo $fd->find('/message')->text('Hello World!');
/** * @group Attributes * @covers FluentDOM::removeAttr */ public function testRemoveAttrWithInvalidParameter() { $fd = new FluentDOM(); try { $fd->removeAttr(1); $this->fail('An expected exception has not been raised.'); } catch (InvalidArgumentException $expected) { } }
<?php require '../../src/FluentDOM.php'; $fd = new FluentDOM(); $fd->contentType = 'html'; $menu = $fd->append('<ul/>'); // first menu item $menu->append('<li/>')->append('<a/>')->attr('href', '/sample.php')->text('Sample'); // second menu item $menu->append('<li/>')->append('<a/>')->attr('href', 'http://fluentdom.org')->addClass('externalLink')->text('FluentDOM'); // third menu item $menu->append('<li/>')->append('<a/>')->attr('id', 'alertSample')->attr('onclick', "alert('Hi');")->text('Alert Sample'); echo $fd;
<?php /** * Sample how to use the JSON loader * * It loads the FluentDOM twitter timeline. This is only an example, Twitter provides XML, too. * * @version $Id: jsonToXml.php 414 2010-03-26 17:27:03Z subjective $ * @package FluentDOM * @subpackage examples */ require_once dirname(__FILE__) . '/../../FluentDOM.php'; require_once dirname(__FILE__) . '/../../FluentDOM/Loader/StringJSON.php'; // get the loader object $jsonLoader = new FluentDOMLoaderStringJSON(); // activate type attributes $jsonLoader->typeAttributes = TRUE; // get a FluentDOM $fd = new FluentDOM(); // inject the loader object $fd->setLoaders(array($jsonLoader)); $url = 'http://twitter.com/status/user_timeline/FluentDOM.json?count=10'; $json = file_get_contents($url); header('Content-type: text/xml'); echo $fd->load($json)->formatOutput();
/** * @param string|callable|FluentDOM\Xpath\Transformer $transformer */ public static function registerXpathTransformer($transformer, $reset = FALSE) { if ($reset) { self::$_xpathTransformers = []; } array_unshift(self::$_xpathTransformers, $transformer); }
/** * Apply Highlight to FluentDOM selection * * @return FluentDOM */ public function highlight(FluentDOM $fd) { $fd->find('descendant-or-self::text()')->each(array($this, 'replace')); return $fd->spawn(); }
<?php require '../../src/FluentDOM.php'; $fd = new FluentDOM(); $fd->contentType = 'html'; $menu = $fd->append('<ul/>'); $menu->append('<li/>')->append('<a/>')->attr('href', '/sample.php')->text('Sample'); $menu->append('<li/>')->append('<a/>')->attr('href', 'http://fluentdom.org')->addClass('externalLink')->text('FluentDOM'); $menu->append('<li/>')->append('<a/>')->attr('id', 'alertSample')->attr('onclick', "alert('Hi');")->text('Alert Sample'); // mark first siblings $fd->find('//li[1]')->addClass('first'); // mark last siblings $fd->find('//li[position() = last()]')->addClass('last'); echo $fd;
/** * Remove the attribute(s) on all selected element nodes * * @see ArrayAccess::offsetUnset() * @see FluentDOM::removeAttr() * @example properties/attr-unset.php Usage: Remove attribute properties * @param string|array $name */ public function offsetUnset($name) { $this->_fd->removeAttr($name); }
<?php require '../../src/FluentDOM.php'; $xmlFile = 'hello.xml'; // create object $fd = new FluentDOM(); // use document attribute $fd->document->load($xmlFile); echo $fd->find('/message')->text('Hello World!');
/** * Allow to use array syntax to change a css property value on all matched nodes. * * @see ArrayAccess::offsetSet() * @param string $name * @param string $value */ public function offsetSet($name, $value) { $this->_fd->css($name, $value); }
<?php require '../../src/FluentDOM.php'; // create a FluentDOM $fd = new FluentDOM(); // we generate html $fd->contentType = 'html'; //add the base menu node $menu = $fd->append($fd->document->createElement('ul')); // output the created document echo $fd;
function getDoc($fullURL, $classname, $method) { $client = new \Artax\Client(); $request = new \Artax\Request(); $client->setOption('transfertimeout', 25); echo "{$fullURL} \n"; $request->setUri($fullURL); $request->setHeader('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'); $request->setHeader('Accept-Encoding', 'gzip,deflate,sdch'); $request->setHeader('Accept-Language', 'en-US,en;q=0.8'); $request->setHeader('Host', 'svn.php.net'); $request->setHeader('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36'); //Cache-Control:max-age=0 //Connection:keep-alive //Cookie:MYPHPNET=%2C%2CNONE%2C0%2C; uvts=1nfuEIFstwB6CP0; LAST_NEWS=1401284942; COUNTRY=GBR%2C89.242.230.142; LAST_LANG=en //If-Modified-Since:Thu, 12 Jan 2012 05:08:38 GMT //If-None-Match:"322115//phpdoc/en/trunk/reference/imagick/imagick/annotateimage.xml" ///User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36 $response = $client->request($request); if ($response->getStatus() != 200) { echo "Failed to read URL"; echo $response->getBody(); return null; } $contentTypeHeaders = $response->getHeader('Content-Type'); if (array_key_exists(0, $contentTypeHeaders) == false) { throw new Exception("Content-type header not set."); } $contentType = $contentTypeHeaders[0]; $colonPosition = strpos($contentType, ';'); if ($colonPosition !== false) { $contentType = substr($contentType, 0, $colonPosition); } // if ($contentType !== 'text/html') { // echo "Unknown content type $contentType"; // return; // } $SR = ['&reftitle.errors' => 'errors', '&example.outputs.similar' => 'similar', '&reftitle.returnvalues' => 'returnvalues', '&reftitle.examples' => 'examples', '&reftitle.seealso' => 'examples', '&reftitle.description' => 'description', '&reftitle.parameters' => 'parameters', '&reftitle.changelog' => 'changelog', '&Version' => 'Version', '&Description' => 'Description', '&true' => 'True', '&false' => 'False', '&return.success' => 'Return success', '&return.void' => 'return void', '&example.outputs' => 'Output', '&float' => 'float', '&reftitle.notes' => 'Notes', '&warn.undocumented.func' => 'Undocumented', '&no.function.parameters' => 'no.function.parameters', '&url.imagemagick.usage.transform.function' => 'transform.function', '&url.imagemagick' => 'ImageMagick URL']; $body = $response->getBody(); $body = str_replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" . $GLOBALS['entityBlock'], $body); $body = str_replace(array_keys($SR), array_values($SR), $body); $fluentDOM = new FluentDOM(); $fluentDOM->namespaces(['ref' => 'http://docbook.org/ns/docbook']); $manualEntry = new ManualEntry($classname, $method); //echo $body; $dom = $fluentDOM->load($body, 'text/xml'); $methodParam = function (DOMElement $element) use($manualEntry) { $name = null; $type = null; foreach ($element->childNodes as $childNode) { if ($childNode instanceof DOMElement) { if ($childNode->nodeName === 'type') { $type = $childNode->textContent; } if ($childNode->nodeName === 'parameter') { $name = $childNode->textContent; } } } $manualEntry->addParam(new Parameter($type, $name)); }; $dom->find('//ref:methodparam')->each($methodParam); $description = function (DOMElement $element) use($manualEntry) { $manualEntry->setDescription($element->textContent); }; $dom->find('//ref:refsect1[@role="description"]/ref:para')->each($description); $paramDescriptionBlock = $dom->find('//ref:refsect1[@role="parameters"]/ref:para/ref:variablelist/ref:varlistentry'); foreach ($paramDescriptionBlock as $element) { /** @var DOMElement $element */ //echo "Found entry \n"; $paramName = null; $paramDescription = null; $subDOM = new FluentDOM(); $subDOM->load($element); $subDOM->namespaces(['ref' => 'http://docbook.org/ns/docbook']); $termBlock = $subDOM->find("child::ref:term/ref:parameter"); foreach ($termBlock as $term) { /** @var DOMElement $term */ //echo $term->textContent."\n"; $paramName .= trim($term->textContent); } $descriptionBlock = $subDOM->find("child::ref:listitem/ref:para"); foreach ($descriptionBlock as $description) { /** @var DOMElement $term */ $paramDescription .= trim($description->textContent); } $manualEntry->addParamDescription($paramName, $paramDescription); } $nameBlock = $dom->find('//ref:refnamediv/ref:refname'); if ($nameBlock->count()) { foreach ($nameBlock as $nameElement) { /** @var DOMElement $term */ $manualEntry->setFunctionName($nameElement->textContent); } } if ($nameBlock->count()) { $methodDescriptionBlock = $dom->find('//ref:refnamediv/ref:refpurpose'); foreach ($methodDescriptionBlock as $methodDescriptionElement) { /** @var DOMElement $term */ $manualEntry->setMethodDescription($methodDescriptionElement->textContent); } } $returnTypeBlock = $dom->find('//ref:refsect1[@role="returnvalues"]/ref:para'); foreach ($returnTypeBlock as $returnTypeElement) { /** @var DOMElement $term */ $manualEntry->setReturnType($returnTypeElement->textContent); } $this->manualEntries[] = $manualEntry; return $manualEntry; }
/** * getDom method * @return \FluentDOM\Query */ public function getDom() { return \FluentDOM::Query($this->getContent(), 'text/html'); }
<?php namespace FluentDOM\ContentLines; if (class_exists('\\FluentDOM')) { \FluentDOM::registerLoader(new \FluentDOM\Loader\Lazy(['text/calendar' => function () { return new Loader\ICalendar(); }, 'text/vcard' => function () { return new Loader\VCard(); }])); }
<?php namespace FluentDOM\YAML\Dipper; if (class_exists('\\FluentDOM')) { \FluentDOM::registerLoader(new \FluentDOM\Loader\Lazy(['text/yaml' => function () { return new Loader(); }, 'yaml' => function () { return new Loader(); }])); }
<?php /** * Sample how to use a custom FluentDOMLoader * * @version $Id: iniToXml.php 429 2010-03-29 08:05:32Z subjective $ * @package FluentDOM * @subpackage examples */ require_once dirname(__FILE__) . '/../../FluentDOM.php'; require_once dirname(__FILE__) . '/FluentDOMIniLoader.php'; $iniFile = dirname(__FILE__) . '/sample.ini'; $fd = new FluentDOM(); $fd->setLoaders(array(new FluentDOMIniLoader())); header('Content-type: text/plain'); echo $fd->load($iniFile, 'text/ini')->formatOutput(); echo "\n\n"; echo 'URL: ', $fd->find('//URL')->text();
/** * @param Serializer\Factory\Group|NULL $factories * @return Serializer\Factory\Group */ public function serializerFactories(Serializer\Factory\Group $factories = NULL) { if (isset($factories)) { $this->_serializerFactories = $factories; } elseif (NULL === $this->_serializerFactories) { $this->_serializerFactories = \FluentDOM::getSerializerFactories(); } return $this->_serializerFactories; }
<?php require '../../FluentDOM.php'; $xmlFile = 'hello.xml'; class ExampleLoader implements FluentDOMLoader { // this could implement checks, error handling, ... public function load($source, $type) { $dom = new DOMDocument(); $dom->load($source); return $dom; } } $fd = new FluentDOM(); // set loader(s) $fd->setLoaders(array(new ExampleLoader())); // load data using custom loader $fd->load($xmlFile); echo $fd->find('/message')->text('Hello World!');
/** * @param URLToCheck $urlToCheck * @param $body */ function analyzeBody(URLToCheck $urlToCheck, $body) { $ok = false; $path = $urlToCheck->getUrl(); try { $fluentDOM = new FluentDOM(); $dom = $fluentDOM->load($body, 'text/html'); $linkClosure = function (DOMElement $element) use($urlToCheck) { $this->parseLinkResult($element, $urlToCheck->getUrl()); }; $imgClosure = function (DOMElement $element) use($urlToCheck) { $this->parseImgResult($element, $urlToCheck->getUrl()); }; $dom->find('//a')->each($linkClosure); $dom->find('//img')->each($imgClosure); $ok = true; } catch (SocketException $se) { $this->urlsChecked[] = new URLResult($path, 500, "Artax\\SocketException on {$path} - " . $se->getMessage() . " Exception type is " . get_class($se)); } catch (InvalidArgumentException $iae) { //echo "Fluent dom exception on $path - ".$iae->getMessage(). " Exception type is ".get_class($iae)." \n"; $this->urlsChecked[] = new URLResult($path, 500, "Fluent dom exception on {$path} - " . $iae->getMessage() . " Exception type is " . get_class($iae)); } catch (Exception $e) { //echo "Error getting $path - ".$e->getMessage(). " Exception type is ".get_class($e)." \n"; $this->urlsChecked[] = new URLResult($path, 500, "Error getting {$path} - " . $e->getMessage() . " Exception type is " . get_class($e)); } if ($ok != true) { $this->errors++; } }
/** * Put the current node into a FluentDOM\Query * and call find() on it. * * @param string $expression * @return Query */ public function find($expression) { return \FluentDOM::Query($this)->find($expression); }