Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
CRAP
100.00% covered (success)
100.00%
1 / 1
HtmlSafeJsonEncode
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
1 / 1
 __invoke
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3/**
4 * HTML-safe JSON encoding.
5 *
6 * This helper is used to ensure that we consistently escape JSON data when
7 * embedding it directly into HTML (typically via data attributes).
8 *
9 * PHP version 8
10 *
11 * Copyright (C) Villanova University 2023.
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License version 2,
15 * as published by the Free Software Foundation.
16 *
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
25 *
26 * @category VuFind
27 * @package  View_Helpers
28 * @author   Demian Katz <demian.katz@villanova.edu>
29 * @license  http://opensource.org/licenses/gpl-2.0.php GNU General Public License
30 * @link     https://vufind.org/wiki/development Wiki
31 */
32
33namespace VuFind\View\Helper\Root;
34
35use Laminas\View\Helper\AbstractHelper;
36
37/**
38 * HTML-safe JSON encoding.
39 *
40 * @category VuFind
41 * @package  View_Helpers
42 * @author   Demian Katz <demian.katz@villanova.edu>
43 * @license  http://opensource.org/licenses/gpl-2.0.php GNU General Public License
44 * @link     https://vufind.org/wiki/development Wiki
45 */
46class HtmlSafeJsonEncode extends AbstractHelper
47{
48    /**
49     * JSON-encode $value in an HTML-safe manner.
50     *
51     * @param mixed   $value        Data to encode
52     * @param ?string $outerEscaper Name of a view helper to use to escape the JSON
53     * (null/empty value for no extra escaping). Defaults to escapeHtmlAttr.
54     *
55     * @return string
56     */
57    public function __invoke($value, ?string $outerEscaper = 'escapeHtmlAttr')
58    {
59        $json = json_encode(
60            $value,
61            JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP
62        );
63        return $outerEscaper
64            ? ($this->getView()->plugin($outerEscaper))($json)
65            : $json;
66    }
67}