AbstractWriter.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * Zend Framework (http://framework.zend.com/)
  4. *
  5. * @link http://github.com/zendframework/zf2 for the canonical source repository
  6. * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
  7. * @license http://framework.zend.com/license/new-bsd New BSD License
  8. */
  9. namespace Zend\Config\Writer;
  10. use Traversable;
  11. use Zend\Config\Exception;
  12. use Zend\Stdlib\ArrayUtils;
  13. abstract class AbstractWriter implements WriterInterface
  14. {
  15. /**
  16. * toFile(): defined by Writer interface.
  17. *
  18. * @see WriterInterface::toFile()
  19. * @param string $filename
  20. * @param mixed $config
  21. * @param bool $exclusiveLock
  22. * @return void
  23. * @throws Exception\InvalidArgumentException
  24. * @throws Exception\RuntimeException
  25. */
  26. public function toFile($filename, $config, $exclusiveLock = true)
  27. {
  28. if (empty($filename)) {
  29. throw new Exception\InvalidArgumentException('No file name specified');
  30. }
  31. $flags = 0;
  32. if ($exclusiveLock) {
  33. $flags |= LOCK_EX;
  34. }
  35. set_error_handler(
  36. function ($error, $message = '', $file = '', $line = 0) use ($filename) {
  37. throw new Exception\RuntimeException(sprintf(
  38. 'Error writing to "%s": %s',
  39. $filename, $message
  40. ), $error);
  41. }, E_WARNING
  42. );
  43. try {
  44. file_put_contents($filename, $this->toString($config), $flags);
  45. } catch (\Exception $e) {
  46. restore_error_handler();
  47. throw $e;
  48. }
  49. restore_error_handler();
  50. }
  51. /**
  52. * toString(): defined by Writer interface.
  53. *
  54. * @see WriterInterface::toString()
  55. * @param mixed $config
  56. * @return string
  57. * @throws Exception\InvalidArgumentException
  58. */
  59. public function toString($config)
  60. {
  61. if ($config instanceof Traversable) {
  62. $config = ArrayUtils::iteratorToArray($config);
  63. } elseif (!is_array($config)) {
  64. throw new Exception\InvalidArgumentException(__METHOD__ . ' expects an array or Traversable config');
  65. }
  66. return $this->processConfig($config);
  67. }
  68. /**
  69. * @param array $config
  70. * @return string
  71. */
  72. abstract protected function processConfig(array $config);
  73. }