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\I18n\Translator\Loader;
11
12/**
13 * Abstract file loader implementation; provides facilities around resolving
14 * files via the include_path.
15 */
16abstract class AbstractFileLoader implements FileLoaderInterface
17{
18    /**
19     * Whether or not to consult the include_path when locating files
20     *
21     * @var bool
22     */
23    protected $useIncludePath = false;
24
25    /**
26     * Indicate whether or not to use the include_path to resolve translation files
27     *
28     * @param bool $flag
29     * @return self
30     */
31    public function setUseIncludePath($flag = true)
32    {
33        $this->useIncludePath = (bool) $flag;
34        return $this;
35    }
36
37    /**
38     * Are we using the include_path to resolve translation files?
39     *
40     * @return bool
41     */
42    public function useIncludePath()
43    {
44        return $this->useIncludePath;
45    }
46
47    /**
48     * Resolve a translation file
49     *
50     * Checks if the file exists and is readable, returning a boolean false if not; if the "useIncludePath"
51     * flag is enabled, it will attempt to resolve the file from the
52     * include_path if the file does not exist on the current working path.
53     *
54     * @param string $filename
55     * @return string|false
56     */
57    protected function resolveFile($filename)
58    {
59        if (!is_file($filename) || !is_readable($filename)) {
60            if (!$this->useIncludePath()) {
61                return false;
62            }
63            return $this->resolveViaIncludePath($filename);
64        }
65        return $filename;
66    }
67
68    /**
69     * Resolve a translation file via the include_path
70     *
71     * @param string $filename
72     * @return string|false
73     */
74    protected function resolveViaIncludePath($filename)
75    {
76        $resolvedIncludePath = stream_resolve_include_path($filename);
77        if (!$resolvedIncludePath || !is_file($resolvedIncludePath) || !is_readable($resolvedIncludePath)) {
78            return false;
79        }
80        return $resolvedIncludePath;
81    }
82}
83