~ubuntu-branches/debian/stretch/assetic/stretch

« back to all changes in this revision

Viewing changes to src/Assetic/Util/VarUtils.php

  • Committer: Package Import Robot
  • Author(s): David Prévot
  • Date: 2014-04-21 12:48:05 UTC
  • Revision ID: package-import@ubuntu.com-20140421124805-y9ri97838g33fo9z
Tags: upstream-1.1.2
Import upstream version 1.1.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<?php
 
2
 
 
3
/*
 
4
 * This file is part of the Assetic package, an OpenSky project.
 
5
 *
 
6
 * (c) 2010-2013 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
 
 
12
namespace Assetic\Util;
 
13
 
 
14
/**
 
15
 * Variable utilities.
 
16
 *
 
17
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 
18
 */
 
19
abstract class VarUtils
 
20
{
 
21
    /**
 
22
     * Resolves variable placeholders.
 
23
     *
 
24
     * @param string $template A template string
 
25
     * @param array  $vars     Variable names
 
26
     * @param array  $values   Variable values
 
27
     *
 
28
     * @return string The resolved string
 
29
     *
 
30
     * @throws \InvalidArgumentException If there is a variable with no value
 
31
     */
 
32
    public static function resolve($template, array $vars, array $values)
 
33
    {
 
34
        $map = array();
 
35
        foreach ($vars as $var) {
 
36
            if (false === strpos($template, '{'.$var.'}')) {
 
37
                continue;
 
38
            }
 
39
 
 
40
            if (!isset($values[$var])) {
 
41
                throw new \InvalidArgumentException(sprintf('The template "%s" contains the variable "%s", but was not given any value for it.', $template, $var));
 
42
            }
 
43
 
 
44
            $map['{'.$var.'}'] = $values[$var];
 
45
        }
 
46
 
 
47
        return strtr($template, $map);
 
48
    }
 
49
 
 
50
    public static function getCombinations(array $vars, array $values)
 
51
    {
 
52
        if (!$vars) {
 
53
            return array(array());
 
54
        }
 
55
 
 
56
        $combinations = array();
 
57
        $nbValues = array();
 
58
        foreach ($values as $var => $vals) {
 
59
            if (!in_array($var, $vars, true)) {
 
60
                continue;
 
61
            }
 
62
 
 
63
            $nbValues[$var] = count($vals);
 
64
        }
 
65
 
 
66
        for ($i = array_product($nbValues), $c = $i * 2; $i < $c; $i++) {
 
67
            $k = $i;
 
68
            $combination = array();
 
69
 
 
70
            foreach ($vars as $var) {
 
71
                $combination[$var] = $values[$var][$k % $nbValues[$var]];
 
72
                $k = intval($k / $nbValues[$var]);
 
73
            }
 
74
 
 
75
            $combinations[] = $combination;
 
76
        }
 
77
 
 
78
        return $combinations;
 
79
    }
 
80
 
 
81
    final private function __construct() { }
 
82
}