xref: /plugin/struct/types/Date.php (revision 22dd50e765070a50b0001178d33cfd7b5224de3a)
1<?php
2namespace plugin\struct\types;
3
4use plugin\struct\meta\ValidationException;
5
6class Date extends AbstractBaseType {
7
8    protected $config = array(
9        'prefix' => '',
10        'postfix' => '',
11        'format' => 'Y/m/d'
12    );
13
14    /**
15     * Output the stored data
16     *
17     * @param string|int $value the value stored in the database
18     * @param \Doku_Renderer $R the renderer currently used to render the data
19     * @param string $mode The mode the output is rendered in (eg. XHTML)
20     * @return bool true if $mode could be satisfied
21     */
22    public function renderValue($value, \Doku_Renderer $R, $mode) {
23        $date = date_create($value);
24        $R->cdata($this->config['prefix'] . date_format($date, $this->config['format']) . $this->config['postfix']);
25        return true;
26    }
27
28    /**
29     * Return the editor to edit a single value
30     *
31     * @param string $name the form name where this has to be stored
32     * @param string $value the current value
33     * @return string html
34     */
35    public function valueEditor($name, $value) {
36        $name = hsc($name);
37        $value = hsc($value);
38        $html = "<input class=\"struct_date\" name=\"$name\" value=\"$value\" />";
39        return "$html";
40    }
41
42    /**
43     * Validate a single value
44     *
45     * This function needs to throw a validation exception when validation fails.
46     * The exception message will be prefixed by the appropriate field on output
47     *
48     * @param string|int $value
49     * @throws ValidationException
50     */
51    public function validate($value) {
52        list($year, $month, $day) = explode('-',$value, 3);
53        if (!checkdate($month, $day, $year)) {
54            throw new ValidationException('invalid date format');
55        }
56    }
57
58}
59