1<?php
2
3/*
4 * This file is part of the Assetic package, an OpenSky project.
5 *
6 * (c) 2010-2014 OpenSky Project Inc
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Assetic\Factory\Worker;
13
14use Assetic\Asset\AssetInterface;
15use Assetic\Factory\AssetFactory;
16use Assetic\Filter\FilterInterface;
17
18/**
19 * Applies a filter to an asset based on a source and/or target path match.
20 *
21 * @author Kris Wallsmith <kris.wallsmith@gmail.com>
22 * @todo A better asset-matcher mechanism
23 */
24class EnsureFilterWorker implements WorkerInterface
25{
26    const CHECK_SOURCE = 1;
27    const CHECK_TARGET = 2;
28
29    private $pattern;
30    private $filter;
31    private $flags;
32
33    /**
34     * Constructor.
35     *
36     * @param string          $pattern A regex for checking the asset's target URL
37     * @param FilterInterface $filter  A filter to apply if the regex matches
38     * @param integer         $flags   Flags for what to check
39     */
40    public function __construct($pattern, FilterInterface $filter, $flags = null)
41    {
42        if (null === $flags) {
43            $flags = self::CHECK_SOURCE | self::CHECK_TARGET;
44        }
45
46        $this->pattern = $pattern;
47        $this->filter = $filter;
48        $this->flags = $flags;
49    }
50
51    public function process(AssetInterface $asset, AssetFactory $factory)
52    {
53        if (
54            (self::CHECK_SOURCE === (self::CHECK_SOURCE & $this->flags) && preg_match($this->pattern, $asset->getSourcePath()))
55            ||
56            (self::CHECK_TARGET === (self::CHECK_TARGET & $this->flags) && preg_match($this->pattern, $asset->getTargetPath()))
57        ) {
58            $asset->ensureFilter($this->filter);
59        }
60    }
61}
62