Add unit tests for cion module
[platform/core/appfw/event-system.git] / src / lib / method_broker.hh
1 /*
2  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef EVENTSYSTEM_LIB_METHOD_BROKER_HH_
18 #define EVENTSYSTEM_LIB_METHOD_BROKER_HH_
19
20 #include <functional>
21 #include <map>
22 #include <memory>
23 #include <string>
24
25 namespace esd::api {
26
27 class ParamsBase {
28  public:
29   virtual ~ParamsBase() = default;
30 };
31
32 template <class... ArgTypes>
33 class Params : public ParamsBase {
34  public:
35   using FuncType = std::function<void(ArgTypes...)>;
36
37   Params() {};
38   Params(FuncType f) : func_(f) {}
39
40   void operator()(ArgTypes... args) {
41     if (func_)
42       func_(args...);
43   }
44
45  private:
46   FuncType func_;
47 };
48
49 class MethodBroker {
50  public:
51   template <class T>
52   void Register(std::string name, const T& cmd) {
53     fmap_.insert(std::pair<std::string,
54       std::shared_ptr<ParamsBase>>(name, std::make_shared<T>(cmd)));
55   }
56
57   void Unregister(std::string name) {
58     fmap_.erase(std::move(name));
59   }
60
61   template <class... ArgTypes>
62   bool Invoke(std::string name, ArgTypes... args) {
63     using ParamsType = Params<ArgTypes...>;
64
65     auto it = fmap_.find(name);
66     if (it != fmap_.end()) {
67       auto* p = dynamic_cast<ParamsType*>(it->second.get());
68       if (p) {
69         (*p)(args...);
70         return true;
71       }
72     }
73
74     return false;
75   }
76
77  private:
78   std::map<std::string, std::shared_ptr<ParamsBase>> fmap_;
79 };
80
81 }  // namespace esd::api
82
83 #endif  // EVENTSYSTEM_LIB_METHOD_BROKER_HH_