Lines
80.00%
16 / 20
Methods
33.33%
1 / 3
Classes
0.00%
0 / 1
| Name | Lines | Methods | CRAP | ||||
|---|---|---|---|---|---|---|---|
| create | 100.00% | 9 / 9 | 100.00% | 1 / 1 | 3 | ||
| instantiate | 66.66% | 2 / 3 | 0.00% | 0 / 1 | 3.33 | ||
| resolveDatabaseType | 62.50% | 5 / 8 | 0.00% | 0 / 1 | 7.90 | ||
| 30 | class SearchFactory | |
| 31 | { | |
| 32 | /** | |
| 33 | * Factory for generating search instances. | |
| 34 | * | |
| 35 | * @param string[] $searchHandler Array with search handlers, e.g., array ('database' => 'mysqli') | |
| 36 | */ | |
| 37 | public static function create(Configuration $configuration, array $searchHandler): SearchDatabase | |
| 38 | { | |
| 39 | $type = (string) current($searchHandler); | |
| 40 | $connector = ucfirst((string) key($searchHandler)); | |
| 41 | if ($type === '') { | |
| 42 | $type = self::resolveDatabaseType($configuration->getDb()); | |
| 43 | } | |
| 44 | ||
| 45 | if (str_starts_with($type, 'pdo_')) { | |
| 46 | $searchClass = sprintf('\phpMyFAQ\Search\%s\Pdo%s', $connector, ucfirst(substr(string: $type, offset: 4))); | |
| 47 | ||
| 48 | return self::instantiate($searchClass, $configuration); | |
| 49 | } | |
| 50 | ||
| 51 | $searchClass = sprintf('\phpMyFAQ\Search\%s\%s', $connector, ucfirst($type)); | |
| 52 | ||
| 53 | return self::instantiate($searchClass, $configuration); | |
| 54 | } | |
| 55 | ||
| 56 | private static function instantiate(string $searchClass, Configuration $configuration): SearchDatabase | |
| 57 | { | |
| 58 | if (!class_exists($searchClass) || !is_subclass_of($searchClass, SearchDatabase::class)) { | |
| 59 | throw new \RuntimeException('Unknown search backend: ' . $searchClass); | |
| 60 | } | |
| 61 | ||
| 62 | return new $searchClass($configuration); | |
| 63 | } | |
| 64 | ||
| 65 | private static function resolveDatabaseType(DatabaseDriver $databaseDriver): string | |
| 66 | { | |
| 67 | $classNameParts = explode('\\', $databaseDriver::class); | |
| 68 | $driverClass = strtolower((string) end($classNameParts)); | |
| 69 | ||
| 70 | return match ($driverClass) { | |
| 71 | 'pdomysql' => 'pdo_mysql', | |
| 72 | 'pdopgsql' => 'pdo_pgsql', | |
| 73 | 'pdosqlite' => 'pdo_sqlite', | |
| 74 | 'pdosqlsrv' => 'pdo_sqlsrv', | |
| 75 | default => $driverClass, | |
| 76 | }; | |
| 77 | } | |
| 78 | } |