Skip to main content

transporter/php/
alias.rs

1use crate::{error::Result, php::php_type::PhpType, schema::Type, CodeGenerator, FileCreator};
2use std::{io::Write, path::PathBuf};
3
4pub(crate) struct Alias<'v, 'd, 'ns, 'n, 't> {
5    pub(crate) version: &'v str,
6    pub(crate) dir: &'d PathBuf,
7    pub(crate) namespace: &'ns str,
8    pub(crate) name: &'n str,
9    pub(crate) type_: &'t Type,
10}
11
12impl<'v, 'd, 'ns, 'n, 't> CodeGenerator for Alias<'v, 'd, 'ns, 'n, 't> {
13    fn build<C>(&self, fc: &mut C) -> Result<()>
14    where
15        C: FileCreator,
16    {
17        let mut path = self.dir.clone();
18        path.push(format!("{}.php", self.name));
19        let mut file = fc.create(&path)?;
20
21        let content = format!(
22            "<?php namespace {namespace};
23
24class {name} implements \\JsonSerializable, TransportType {{
25    const TYPE_VERSION = \"{name}@{version}\";
26    const CONTENT_TYPE = \"application/json; ttype={name}@{version}\";
27
28    /* @var {doctype} */
29    private $value;
30
31    /**
32     * @param {doctype} $value
33     */
34    public function __construct({type_} $value)
35    {{
36        $this->value = $value;
37    }}
38
39    /**
40     * @param {doctype} $value
41     */
42    public function set({type_} $value)
43    {{
44        $this->value = $value;
45    }}
46
47    /**
48     * @return {doctype}
49     */
50    public function get() : {type_}
51    {{
52        return $this->value;
53    }}
54
55    /**
56     * @return mixed
57     */
58    public function jsonSerialize()
59    {{
60        return $this->value;
61    }}
62
63    /**
64     * @param mixed $input
65     * @return TransportType
66     */
67    public static function deserialize($input) : TransportType
68    {{
69        return new Self({constructor});
70    }}
71}}
72",
73            namespace = self.namespace,
74            name = self.name,
75            version = self.version,
76            type_ = self.type_.to_php(self.namespace),
77            doctype = self.type_.to_doctype(self.namespace),
78            constructor = self.type_.constructor(self.namespace, "$input"),
79        );
80
81        file.write_all(&content.into_bytes())?;
82
83        Ok(())
84    }
85}