AbstractWriter.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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-2014 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(
  38. sprintf('Error writing to "%s": %s', $filename, $message),
  39. $error
  40. );
  41. },
  42. E_WARNING
  43. );
  44. try {
  45. file_put_contents($filename, $this->toString($config), $flags);
  46. } catch (\Exception $e) {
  47. restore_error_handler();
  48. throw $e;
  49. }
  50. restore_error_handler();
  51. }
  52. /**
  53. * toString(): defined by Writer interface.
  54. *
  55. * @see WriterInterface::toString()
  56. * @param mixed $config
  57. * @return string
  58. * @throws Exception\InvalidArgumentException
  59. */
  60. public function toString($config)
  61. {
  62. if ($config instanceof Traversable) {
  63. $config = ArrayUtils::iteratorToArray($config);
  64. } elseif (!is_array($config)) {
  65. throw new Exception\InvalidArgumentException(__METHOD__ . ' expects an array or Traversable config');
  66. }
  67. return $this->processConfig($config);
  68. }
  69. /**
  70. * @param array $config
  71. * @return string
  72. */
  73. abstract protected function processConfig(array $config);
  74. }