1 /**
2     Value tranformer.
3 **/
4 module automapper.value.transformer;
5 
6 import std.meta;
7 
8 
9 ///
10 template ValueTransformer(T) if (isValueTransformer!T)
11 {
12     alias ValueTransformer = T;
13 }
14 
15 ///
16 class ValueTransformer(T, alias D) : IValueTransformer if (isCallable!D)
17 {
18     static assert((Parameters!D.length == 1) && is(Parameters!D[0] == T) && is(ReturnType!D == T),
19         "the delegate must take a " ~ T.stringof ~ " and return a " ~ T.stringof);
20 
21     ///
22     T transform(in T value)
23     {
24         return D(value);
25     }
26 }
27 
28 ///
29 template isValueTransformer(T)
30 {
31     enum bool isValueTransformer = (is(T: IValueTransformer!(T), T));
32 }
33 
34 ///
35 template isValueTransformerFor(For, T)
36 {
37     enum bool isValueTransformer = (is(T: IValueTransformer!(For)));
38 }
39 
40 ///
41 interface IValueTransformer(T)
42 {
43     ///
44     T transform(in T value);
45 }
46 
47 ///
48 unittest
49 {
50     import automapper : MapperConfiguration, CreateMap;
51 
52     static class A {
53         string foo;
54     }
55 
56     static class B {
57         string foo;
58     }
59 
60     static class StringTransformer : IValueTransformer!string
61     {
62         string transform(in string value)
63         {
64             return value ~ "!!!";
65         }
66     }
67 
68     auto am = MapperConfiguration!(
69         CreateMap!(A, B),
70         ValueTransformer!StringTransformer)
71             .createMapper();
72 
73     A a = new A();
74     const B b = am.map!B(a);
75     assert(b.foo == "!!!");
76 }