SproutCMS

This is the code documentation for the SproutCMS project

source of /sprout/tests/validiatorTest.php

  1. <?php
  2. /*
  3.  * Copyright (C) 2017 Karmabunny Pty Ltd.
  4.  *
  5.  * This file is a part of SproutCMS.
  6.  *
  7.  * SproutCMS is free software: you can redistribute it and/or modify it under the terms
  8.  * of the GNU General Public License as published by the Free Software Foundation, either
  9.  * version 2 of the License, or (at your option) any later version.
  10.  *
  11.  * For more information, visit <http://getsproutcms.com>.
  12.  */
  13.  
  14. use Sprout\Helpers\Validator;
  15.  
  16.  
  17. class validatorTest extends PHPUnit_Framework_TestCase
  18. {
  19.  
  20. public function dataCheckFailures() {
  21. return [
  22. ['aa', 'Validity::email'],
  23. ['@example.com', 'Validity::email'],
  24. ['test@', 'Validity::email'],
  25. ['A', 'Validity::length', 2],
  26. ['A', 'Validity::length', 2, 3],
  27. ['A', 'Validity::positiveInt'],
  28. ];
  29. }
  30.  
  31. /**
  32.   * @dataProvider dataCheckFailures
  33.   */
  34. public function testCheckFailures($value, $func)
  35. {
  36. $validator = new Validator(['field' => $value]);
  37.  
  38. // Awful hack to pass through varargs to the Validator::check method
  39. $args = func_get_args();
  40. $args[0] = 'field';
  41. call_user_func_array([$validator, 'check'], $args);
  42.  
  43. $this->assertTrue($validator->hasErrors());
  44. $this->assertCount(1, $validator->getFieldErrors());
  45. $this->assertArrayHasKey('field', $validator->getFieldErrors());
  46. $errs = $validator->getFieldErrors();
  47. $this->assertCount(1, $errs['field']);
  48. }
  49.  
  50. public function testArrayCheck()
  51. {
  52. $data = ['vals' => [1, 2, 'A', 'B', 5]];
  53. $validator = new Validator($data);
  54.  
  55. $results = $validator->arrayCheck('vals', 'Validity::positiveInt');
  56.  
  57. $this->assertCount(count($data['vals']), $results);
  58. $this->assertTrue($results[0]);
  59. $this->assertTrue($results[1]);
  60. $this->assertFalse($results[2]);
  61. $this->assertFalse($results[3]);
  62. $this->assertTrue($results[4]);
  63.  
  64. $this->assertTrue($validator->hasErrors());
  65. $this->assertCount(1, $validator->getFieldErrors());
  66. $this->assertArrayHasKey('vals', $validator->getFieldErrors());
  67.  
  68. $errs = $validator->getFieldErrors();
  69. $this->assertCount(2, $errs['vals']);
  70. $this->assertArrayHasKey(2, $errs['vals']);
  71. $this->assertCount(1, $errs['vals'][2]);
  72. $this->assertArrayHasKey(3, $errs['vals']);
  73. $this->assertCount(1, $errs['vals'][3]);
  74. }
  75.  
  76. }
  77.