|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Laravel\BrowserKitTesting\Constraints\Concerns; |
| 4 | + |
| 5 | +use Symfony\Component\DomCrawler\Crawler; |
| 6 | + |
| 7 | +trait FormFieldConstraint |
| 8 | +{ |
| 9 | + /** |
| 10 | + * The name or ID of the element. |
| 11 | + * |
| 12 | + * @var string |
| 13 | + */ |
| 14 | + protected readonly string $selector; |
| 15 | + |
| 16 | + /** |
| 17 | + * The expected value. |
| 18 | + * |
| 19 | + * @var string |
| 20 | + */ |
| 21 | + protected readonly string $value; |
| 22 | + |
| 23 | + /** |
| 24 | + * Create a new constraint instance. |
| 25 | + * |
| 26 | + * @param string $selector |
| 27 | + * @param mixed $value |
| 28 | + * @return void |
| 29 | + */ |
| 30 | + public function __construct($selector, $value) |
| 31 | + { |
| 32 | + $this->selector = $selector; |
| 33 | + $this->value = (string) $value; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Get the valid elements. |
| 38 | + * |
| 39 | + * Multiple elements should be separated by commas without spaces. |
| 40 | + * |
| 41 | + * @return string |
| 42 | + */ |
| 43 | + abstract protected function validElements(); |
| 44 | + |
| 45 | + /** |
| 46 | + * Get the form field. |
| 47 | + * |
| 48 | + * @param \Symfony\Component\DomCrawler\Crawler $crawler |
| 49 | + * @return \Symfony\Component\DomCrawler\Crawler |
| 50 | + * |
| 51 | + * @throws \PHPUnit\Framework\ExpectationFailedException |
| 52 | + */ |
| 53 | + protected function field(Crawler $crawler) |
| 54 | + { |
| 55 | + $field = $crawler->filter(implode(', ', $this->getElements())); |
| 56 | + |
| 57 | + if ($field->count() > 0) { |
| 58 | + return $field; |
| 59 | + } |
| 60 | + |
| 61 | + $this->fail($crawler, sprintf( |
| 62 | + 'There is no %s with the name or ID [%s]', |
| 63 | + $this->validElements(), $this->selector |
| 64 | + )); |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * Get the elements relevant to the selector. |
| 69 | + * |
| 70 | + * @return array |
| 71 | + */ |
| 72 | + protected function getElements() |
| 73 | + { |
| 74 | + $name = str_replace('#', '', $this->selector); |
| 75 | + |
| 76 | + $id = str_replace(['[', ']'], ['\\[', '\\]'], $name); |
| 77 | + |
| 78 | + return collect(explode(',', $this->validElements()))->map(function ($element) use ($name, $id) { |
| 79 | + return "{$element}#{$id}, {$element}[name='{$name}']"; |
| 80 | + })->all(); |
| 81 | + } |
| 82 | +} |
0 commit comments