Skip to content

Commit

Permalink
Merge pull request #602 from WordPress/feature/iri-add-input-validation
Browse files Browse the repository at this point in the history
  • Loading branch information
schlessera authored Nov 8, 2021
2 parents 883127f + 809edff commit 980de57
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/Iri.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
namespace WpOrg\Requests;

use WpOrg\Requests\Exception;
use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Ipv6;
use WpOrg\Requests\Port;

Expand Down Expand Up @@ -247,8 +248,14 @@ public function __unset($name) {
* Create a new IRI object, from a specified string
*
* @param string|null $iri
*
* @throws \WpOrg\Requests\Exception\InvalidArgument When the passed $iri argument is not a string nor null.
*/
public function __construct($iri = null) {
if ($iri !== null && is_string($iri) === false) {
throw InvalidArgument::create(1, '$iri', 'string|null', gettype($iri));
}

$this->set_iri($iri);
}

Expand Down
33 changes: 33 additions & 0 deletions tests/IriTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@

namespace WpOrg\Requests\Tests;

use WpOrg\Requests\Exception\InvalidArgument;
use WpOrg\Requests\Iri;
use WpOrg\Requests\Tests\Fixtures\StringableObject;
use WpOrg\Requests\Tests\TestCase;

final class IriTest extends TestCase
Expand Down Expand Up @@ -413,4 +415,35 @@ public function testBadPort()

$this->assertNull($iri->port);
}

/**
* Tests receiving an exception when an invalid input type is passed to the constructor.
*
* @dataProvider dataConstructorInvalidInput
*
* @covers \WpOrg\Requests\Iri::__construct
*
* @param mixed $iri Invalid input.
*
* @return void
*/
public function testConstructorInvalidInput($iri) {
$this->expectException(InvalidArgument::class);
$this->expectExceptionMessage('Argument #1 ($iri) must be of type string|null');

new Iri($iri);
}

/**
* Data Provider.
*
* @return array
*/
public function dataConstructorInvalidInput() {
return array(
'boolean false' => array(false),
'float' => array(1.1),
'stringable object' => array(new StringableObject('value')),
);
}
}

0 comments on commit 980de57

Please sign in to comment.