1 /*
2  * Hunt - A high-level D Programming Language Web framework that encourages rapid development and clean, pragmatic design.
3  *
4  * Copyright (C) 2015-2019, HuntLabs
5  *
6  * Website: https://www.huntlabs.net/
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11 
12 module hunt.framework.view.algo.Filters;
13 
14 private
15 {
16     import hunt.framework.view.algo.Wrapper;
17     import hunt.framework.view.Uninode;
18 }
19 
20 // dfmt off
21 Function[string] globalFilters()
22 {
23     return cast(immutable)
24         [
25             "default": wrapper!defaultVal,
26             "d":       wrapper!defaultVal,
27             "escape":  wrapper!escape,
28             "e":       wrapper!escape,
29             "upper":   wrapper!upper,
30             "lower":   wrapper!lower, 
31             "sort":    wrapper!sort,
32             "keys":    wrapper!keys,
33         ];
34 }
35 // dfmt on
36 
37 UniNode defaultVal(UniNode value, UniNode default_value = UniNode(""), bool boolean = false)
38 {
39     if (value.kind == UniNode.Kind.nil)
40         return default_value;
41 
42     if (!boolean)
43         return value;
44 
45     value.toBoolType;
46     if (!value.get!bool)
47         return default_value;
48 
49     return value;
50 }
51 
52 
53 string escape(string s)
54 {
55     import std.array : appender;
56 
57     auto w = appender!string;
58     w.reserve(s.length);
59 
60     foreach (char ch; s)
61         switch (ch)
62         {
63             case '&':  w.put("&");  break;
64             case '\"': w.put("""); break;
65             case '\'': w.put("'"); break;
66             case '<':  w.put("&lt;");   break;
67             case '>':  w.put("&gt;");   break;
68             default:   w.put(ch);       break;
69         }
70 
71     return w.data;
72 }
73 
74 
75 string upper(string str)
76 {
77     import std.uni : toUpper;
78     return str.toUpper;
79 }
80 
81 string lower(string str)
82 {
83     import std.uni : toLower;
84     return str.toLower;
85 }
86 
87 UniNode sort(UniNode value)
88 {
89     import std.algorithm : sort;
90 
91     switch (value.kind) with (UniNode.Kind)
92     {
93         case array:
94             auto arr = value.get!(UniNode[]);
95             sort!((a, b) => a.getAsString < b.getAsString)(arr);
96             return UniNode(arr);
97 
98         case object:
99             UniNode[] arr;
100             foreach (string key, val; value)
101                 arr ~= UniNode([UniNode(key), val]);
102             sort!"a[0].get!string < b[0].get!string"(arr);
103             return UniNode(arr);
104 
105         default:
106             return value;
107     }
108 }
109 
110 
111 UniNode keys(UniNode value)
112 {
113     if (value.kind != UniNode.Kind.object)
114         return UniNode(null);
115 
116     UniNode[] arr;
117     foreach (string key, val; value)
118         arr ~= UniNode(key);
119     return UniNode(arr);
120 }