CacheItemTest.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Cache\Tests;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\Cache\CacheItem;
  13. class CacheItemTest extends TestCase
  14. {
  15. public function testValidKey()
  16. {
  17. $this->assertSame('foo', CacheItem::validateKey('foo'));
  18. }
  19. /**
  20. * @dataProvider provideInvalidKey
  21. */
  22. public function testInvalidKey($key)
  23. {
  24. $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
  25. $this->expectExceptionMessage('Cache key');
  26. CacheItem::validateKey($key);
  27. }
  28. public function provideInvalidKey()
  29. {
  30. return [
  31. [''],
  32. ['{'],
  33. ['}'],
  34. ['('],
  35. [')'],
  36. ['/'],
  37. ['\\'],
  38. ['@'],
  39. [':'],
  40. [true],
  41. [null],
  42. [1],
  43. [1.1],
  44. [[[]]],
  45. [new \Exception('foo')],
  46. ];
  47. }
  48. public function testTag()
  49. {
  50. $item = new CacheItem();
  51. $r = new \ReflectionProperty($item, 'isTaggable');
  52. $r->setAccessible(true);
  53. $r->setValue($item, true);
  54. $this->assertSame($item, $item->tag('foo'));
  55. $this->assertSame($item, $item->tag(['bar', 'baz']));
  56. (\Closure::bind(function () use ($item) {
  57. $this->assertSame(['foo' => 'foo', 'bar' => 'bar', 'baz' => 'baz'], $item->newMetadata[CacheItem::METADATA_TAGS]);
  58. }, $this, CacheItem::class))();
  59. }
  60. /**
  61. * @dataProvider provideInvalidKey
  62. */
  63. public function testInvalidTag($tag)
  64. {
  65. $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException');
  66. $this->expectExceptionMessage('Cache tag');
  67. $item = new CacheItem();
  68. $r = new \ReflectionProperty($item, 'isTaggable');
  69. $r->setAccessible(true);
  70. $r->setValue($item, true);
  71. $item->tag($tag);
  72. }
  73. public function testNonTaggableItem()
  74. {
  75. $this->expectException('Symfony\Component\Cache\Exception\LogicException');
  76. $this->expectExceptionMessage('Cache item "foo" comes from a non tag-aware pool: you cannot tag it.');
  77. $item = new CacheItem();
  78. $r = new \ReflectionProperty($item, 'key');
  79. $r->setAccessible(true);
  80. $r->setValue($item, 'foo');
  81. $item->tag([]);
  82. }
  83. }