This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Component/DomCrawler/Link.php

102 lines
2.6 KiB
PHP
Raw Normal View History

2010-04-15 13:41:42 +01:00
<?php
/*
2010-04-24 00:22:16 +01:00
* This file is part of the Symfony package.
2010-04-15 13:41:42 +01:00
*
* (c) Fabien Potencier <fabien@symfony.com>
2010-04-15 13:41:42 +01:00
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\DomCrawler;
2010-04-15 13:41:42 +01:00
/**
* Link represents an HTML link (an HTML a tag).
*
* @author Fabien Potencier <fabien@symfony.com>
2010-04-15 13:41:42 +01:00
*/
class Link
{
protected $node;
protected $method;
protected $host;
protected $path;
protected $base;
2010-04-15 13:41:42 +01:00
/**
* Constructor.
*
* @param \DOMNode $node A \DOMNode instance
* @param string $method The method to use for the link (get by default)
* @param string $host The base URI to use for absolute links (like http://localhost)
* @param string $path The base path for relative links (/ by default)
* @param strin $base An optional base href for generating the uri
*
* @throws \LogicException if the node is not a link
*/
public function __construct(\DOMNode $node, $method = 'get', $host = null, $path = '/', $base = null)
2010-04-15 13:41:42 +01:00
{
if ('a' != $node->nodeName) {
throw new \LogicException(sprintf('Unable to click on a "%s" tag.', $node->nodeName));
}
$this->node = $node;
$this->method = $method;
$this->host = $host;
$this->path = empty($path) ? '/' : $path;
$this->base = $base;
}
/**
* Gets the node associated with this link.
*
* @return \DOMNode A \DOMNode instance
*/
public function getNode()
{
return $this->node;
2010-04-15 13:41:42 +01:00
}
/**
* Gets the URI associated with this link.
*
* @param Boolean $absolute Whether to return an absolute URI or not (this only works if a base URI has been provided)
*
* @return string The URI
*/
public function getUri($absolute = true)
{
$uri = $this->node->getAttribute('href');
$urlHaveScheme = 'http' === substr($uri, 0, 4);
2010-04-15 13:41:42 +01:00
$path = $this->path;
if ('?' !== substr($uri, 0, 1) && '/' !== substr($path, -1)) {
$path = substr($path, 0, strrpos($path, '/') + 1);
}
if (!$this->base && $uri && '/' !== $uri[0] && !$urlHaveScheme) {
$uri = $path.$uri;
} elseif ($this->base) {
$uri = $this->base.$uri;
}
2010-04-15 13:41:42 +01:00
if (!$this->base && $absolute && null !== $this->host && !$urlHaveScheme) {
return $this->host.$uri;
}
2010-04-15 13:41:42 +01:00
return $uri;
2010-04-15 13:41:42 +01:00
}
/**
* Gets the method associated with this link.
*
* @return string The method
*/
public function getMethod()
2010-04-15 13:41:42 +01:00
{
return $this->method;
2010-04-15 13:41:42 +01:00
}
}