Skip to content
This repository has been archived by the owner on Jun 16, 2021. It is now read-only.

Adds an every call that can be chained in expectations for traversable #7

Merged
merged 1 commit into from
May 13, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions src/Every.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

declare(strict_types=1);

namespace Pest\Expectations;

use BadMethodCallException;

/**
* @internal
*
* @mixin Expectation
*/
class Every
{

/**
* @var Expectation
*/
private $original;

/**
* Creates a new iterable expectation.
*/
public function __construct(Expectation $original)
{
$this->original = $original;

if (!is_iterable($this->original->value)) {
throw new BadMethodCallException("The `every` call only support iterable types.");
}
}

public function and($value)
{
return new Expectation($value);
}

public function not()
{
return $this->original->not();
}

public function __call(string $name, array $arguments)
{
foreach ($this->original->value as $item) {
(new Expectation($item))->$name(...$arguments);
}

return $this;
}

}
8 changes: 8 additions & 0 deletions src/Expectation.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,14 @@ public function not(): OppositeExpectation
return new OppositeExpectation($this);
}

/**
* Allows for expectations to be run over Iterables.
*/
public function every()
{
return new Every($this);
}

/**
* Asserts that two variables have the same type and
* value. Used on objects, it asserts that two
Expand Down
46 changes: 46 additions & 0 deletions tests/Expect/every.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

test('an exception is thrown if the the type is not iterable', function() {
$this->expectException(BadMethodCallException::class);

expect('Foobar')
->every()
->toEqual('Foobar');
});

test('it maps over each iterable', function () {
expect([1, 1, 1])
->every()
->toEqual(1);
});

test('it accepts chained expectations', function() {
expect([1, 1, 1])
->every()
->toBeInt()
->toEqual(1);
});

test('it works with the not operator', function() {
expect([1, 2, 3])
->every()
->not()->toEqual(4);
});

test('it works with the and operator', function() {
expect([1, 2, 3])
->every()
->not()->toEqual(4)
->and([4, 5, 6])
->every()
->toBeLessThan(7)
->toBeGreaterThan(3)
->and('Hello World')
->toBeString()
->toEqual('Hello World');
});

test('it can be called as a higher order function', function () {
expect([1, 1, 1])
->every->toEqual(1);
});