Skip to content

Commit

Permalink
Merge pull request doctrine#190 from doctrine/feature/doctrine#154-st…
Browse files Browse the repository at this point in the history
…ore-anything-in-the-php-file-cache

Feature - doctrine#154 - store anything in the PhpFileCache
  • Loading branch information
Ocramius authored Oct 26, 2016
2 parents a25f538 + 87ef27c commit f56795d
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 12 deletions.
17 changes: 7 additions & 10 deletions lib/Doctrine/Common/Cache/PhpFileCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,23 +78,20 @@ protected function doSave($id, $data, $lifeTime = 0)
$lifeTime = time() + $lifeTime;
}

if (is_object($data) && ! method_exists($data, '__set_state')) {
throw new \InvalidArgumentException(
"Invalid argument given, PhpFileCache only allows objects that implement __set_state() " .
"and fully support var_export(). You can use the FilesystemCache to save arbitrary object " .
"graphs using serialize()/deserialize()."
);
}

$filename = $this->getFilename($id);

$value = [
'lifetime' => $lifeTime,
'data' => $data
];

$value = var_export($value, true);
$code = sprintf('<?php return %s;', $value);
if (is_object($data) && method_exists($data, '__set_state')) {
$value = var_export($value, true);
$code = sprintf('<?php return %s;', $value);
} else {
$value = var_export(serialize($value), true);
$code = sprintf('<?php return unserialize(%s);', $value);
}

return $this->writeFile($filename, $code);
}
Expand Down
19 changes: 17 additions & 2 deletions tests/Doctrine/Tests/Common/Cache/PhpFileCacheTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,27 @@ public function testImplementsSetState()
$this->assertTrue($cache->contains('test_set_state'));
}

/**
* @group 154
*/
public function testNotImplementsSetState()
{
$cache = $this->_getCacheDriver();

$this->setExpectedException('InvalidArgumentException');
$cache->save('test_not_set_state', new NotSetStateClass([1,2,3]));
$cache->save('test_not_set_state', new NotSetStateClass([5,6,7]));
$this->assertEquals(new NotSetStateClass([5,6,7]), $cache->fetch('test_not_set_state'));
}

/**
* @group 154
*/
public function testNotImplementsSetStateInArray()
{
$cache = $this->_getCacheDriver();

$cache->save('test_not_set_state_in_array', [new NotSetStateClass([4,3,2])]);
$this->assertEquals([new NotSetStateClass([4,3,2])], $cache->fetch('test_not_set_state_in_array'));
$this->assertTrue($cache->contains('test_not_set_state_in_array'));
}

public function testGetStats()
Expand Down

0 comments on commit f56795d

Please sign in to comment.