Plop
A simple logging library for PHP
Percent.php
1 <?php
2 /*
3  This file is part of Plop, a simple logging library for PHP.
4 
5  Copyright © 2014 François Poirotte
6 
7  Plop is free software: you can redistribute it and/or modify
8  it under the terms of the GNU General Public License as published by
9  the Free Software Foundation, either version 3 of the License, or
10  (at your option) any later version.
11 
12  Plop is distributed in the hope that it will be useful,
13  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  GNU General Public License for more details.
16 
17  You should have received a copy of the GNU General Public License
18  along with Plop. If not, see <http://www.gnu.org/licenses/>.
19 */
20 
21 namespace Plop\Interpolator;
22 
29 {
31  public function interpolate($msg, array $args = array())
32  {
33  preg_match_all('/(?<!%)(?:%%)*%\\(([^\\)]*)\\)/', $msg, $matches);
34  // Only define the variables if there are any.
35  if (isset($matches[1][0])) {
36  $args += array_combine(
37  $matches[1],
38  array_fill(0, count($matches[1]), null)
39  );
40  }
41 
42  if (!count($args)) {
43  return $msg;
44  }
45 
46  // Mapping = array(name => index)
47  $keys = array_keys($args);
48  $mapping = array_flip($keys);
49  $keys = array_map(
50  function ($key) {
51  return "%($key)";
52  },
53  $keys
54  );
55  $values = array_map(
56  function ($val) {
57  return '%'.($val + 1).'$';
58  },
59  $mapping
60  );
61  $mapping = array_combine($keys, $values);
62  $msg = strtr($msg, $mapping);
63  return vsprintf($msg, array_values($args));
64  }
65 }
An interpolator that uses a syntax similar to Python&#39;s old formatting syntax: %(value)s.
Definition: Percent.php:28
interpolate($msg, array $args=array())
Definition: Percent.php:31