-
Notifications
You must be signed in to change notification settings - Fork 0
/
Importer.cs
87 lines (73 loc) · 1.84 KB
/
Importer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace Tiler.Importers
{
public abstract class Importer
{
public virtual bool CanLoad(string filePath)
{
return CanLoadExtension(Path.GetExtension(filePath));
}
public abstract bool CanLoadExtension(string extension);
}
public abstract class Importer<T> : Importer
{
public abstract T Load(string filePath);
}
public static class Importers
{
private static List<Importer> AllImporters = new List<Importer>();
static Importers()
{
// @todo ship the engine with an `Application`/`Program` class that does this.
RegisterAll(Assembly.GetExecutingAssembly());
}
public static void Register(Type importerType)
{
foreach (var importer in AllImporters)
{
if (importer.GetType() == importerType)
throw new Exception($"Importer type already exists ({importerType})");
}
AllImporters.Add((Importer)Activator.CreateInstance(importerType));
}
public static void RegisterAll()
{
RegisterAll(Assembly.GetExecutingAssembly());
}
public static void RegisterAll(Assembly assembly)
{
foreach (var type in assembly.GetTypes())
{
if (!type.IsAbstract && !type.IsInterface && type.IsSubclassOf(typeof(Importer)))
{
Register(type);
}
}
}
public static Importer<T> Get<T>(string filePath)
{
foreach (var importer in GetAll<T>())
{
if (importer.CanLoad(filePath))
return importer;
}
throw new Exception($"No Importer has been registed for filepath: {filePath}");
}
public static IEnumerable<Importer<T>> GetAll<T>()
{
foreach (var importer in AllImporters)
{
var casted = importer as Importer<T>;
if (!(casted is null))
yield return casted;
}
}
public static T Load<T>(string filePath)
{
return Get<T>(filePath).Load(filePath);
}
}
}