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-2015 Zend Technologies USA Inc. (http://www.zend.com)
7 * @license   http://framework.zend.com/license/new-bsd New BSD License
8 */
9
10namespace Zend\Config\Writer;
11
12use Zend\Config\Exception;
13
14class Yaml extends AbstractWriter
15{
16    /**
17     * YAML encoder callback
18     *
19     * @var callable
20     */
21    protected $yamlEncoder;
22
23    /**
24     * Constructor
25     *
26     * @param callable|string|null $yamlEncoder
27     */
28    public function __construct($yamlEncoder = null)
29    {
30        if ($yamlEncoder !== null) {
31            $this->setYamlEncoder($yamlEncoder);
32        } else {
33            if (function_exists('yaml_emit')) {
34                $this->setYamlEncoder('yaml_emit');
35            }
36        }
37    }
38
39    /**
40     * Get callback for decoding YAML
41     *
42     * @return callable
43     */
44    public function getYamlEncoder()
45    {
46        return $this->yamlEncoder;
47    }
48
49    /**
50     * Set callback for decoding YAML
51     *
52     * @param  callable $yamlEncoder the decoder to set
53     * @return Yaml
54     * @throws Exception\InvalidArgumentException
55     */
56    public function setYamlEncoder($yamlEncoder)
57    {
58        if (!is_callable($yamlEncoder)) {
59            throw new Exception\InvalidArgumentException('Invalid parameter to setYamlEncoder() - must be callable');
60        }
61        $this->yamlEncoder = $yamlEncoder;
62        return $this;
63    }
64
65    /**
66     * processConfig(): defined by AbstractWriter.
67     *
68     * @param  array $config
69     * @return string
70     * @throws Exception\RuntimeException
71     */
72    public function processConfig(array $config)
73    {
74        if (null === $this->getYamlEncoder()) {
75            throw new Exception\RuntimeException("You didn't specify a Yaml callback encoder");
76        }
77
78        $config = call_user_func($this->getYamlEncoder(), $config);
79        if (null === $config) {
80            throw new Exception\RuntimeException("Error generating YAML data");
81        }
82
83        return $config;
84    }
85}
86