HasInDatabase.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Testing\Constraint;
  12. use Hyperf\Database\ConnectionInterface;
  13. use Hyperf\Database\Query\Builder;
  14. use PHPUnit\Framework\Constraint\Constraint;
  15. class HasInDatabase extends Constraint
  16. {
  17. protected ConnectionInterface $connection;
  18. protected string $table;
  19. public function __construct(ConnectionInterface $connection, string $table)
  20. {
  21. $this->table = $table;
  22. $this->connection = $connection;
  23. }
  24. public function matches($data): bool
  25. {
  26. return $this->query($data)->count() > 0;
  27. }
  28. public function failureDescription($data): string
  29. {
  30. return sprintf(
  31. 'a row in the table [%s] matches the attributes %s',
  32. $this->table,
  33. json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
  34. );
  35. }
  36. public function toString(): string
  37. {
  38. return sprintf('There is a record of table %s with the specified data', $this->table);
  39. }
  40. private function query(array $data): Builder
  41. {
  42. /** @var Builder $query */
  43. $query = $this->connection->table($this->table);
  44. foreach ($data as $index => $value) {
  45. if (is_array($value)) {
  46. [$column, $operator, $expected] = $value;
  47. $query->where($column, $operator, $expected);
  48. continue;
  49. }
  50. $query->where($index, $value);
  51. }
  52. return $query;
  53. }
  54. }