Passed
Push — master ( 8e8232...484b96 )
by Jean Paul
01:15
created

StepLoader::getInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 7
rs 10
1
<?php
2
3
namespace Coco\SourceWatcher\Core;
4
5
use Coco\SourceWatcher\Utils\TextUtils;
6
use ReflectionClass;
7
use ReflectionException;
8
9
/**
10
 * Class StepLoader
11
 * @package Coco\SourceWatcher\Core
12
 */
13
class StepLoader
14
{
15
    /**
16
     * @var StepLoader
17
     */
18
    private static StepLoader $instance;
19
20
    /**
21
     * @return StepLoader
22
     */
23
    public static function getInstance () : StepLoader
24
    {
25
        if ( is_null( static::$instance ) ) {
0 ignored issues
show
Bug introduced by
Since $instance is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $instance to at least protected.
Loading history...
26
            static::$instance = new static;
27
        }
28
29
        return static::$instance;
30
    }
31
32
    /**
33
     * @param string $parentClassName
34
     * @param string $stepName
35
     * @return Step
36
     * @throws SourceWatcherException
37
     */
38
    public function getStep ( string $parentClassName, string $stepName ) : ?Step
39
    {
40
        if ( empty( $parentClassName ) ) {
41
            throw new SourceWatcherException( "The parent class name must be provided." );
42
        }
43
44
        if ( empty( $stepName ) ) {
45
            throw new SourceWatcherException( "The step name must be provided." );
46
        }
47
48
        try {
49
            $reflection = new ReflectionClass( $parentClassName );
50
51
            $parentClassShortName = $reflection->getShortName();
52
        } catch ( ReflectionException $reflectionException ) {
53
            $errorMessage = sprintf( "Something went wrong while trying to get the short class name: %s", $reflectionException->getMessage() );
54
            throw new SourceWatcherException( $errorMessage );
55
        }
56
57
        $baseNameSpace = "Coco\\SourceWatcher\\Core";
58
59
        $packages = [ "Extractor" => sprintf( "%s\\%s", $baseNameSpace, "Extractors" ), "Transformer" => sprintf( "%s\\%s", $baseNameSpace, "Transformers" ), "Loader" => sprintf( "%s\\%s", $baseNameSpace, "Loaders" ) ];
60
61
        $step = null;
62
63
        $textUtils = new TextUtils();
64
65
        $fullyQualifiedClassName = sprintf( "%s\\%s", $packages[$parentClassShortName], $textUtils->textToPascalCase( sprintf( "%s_%s", $stepName, $parentClassShortName ) ) );
66
67
        if ( class_exists( $fullyQualifiedClassName ) ) {
68
            $step = new $fullyQualifiedClassName();
69
        }
70
71
        return $step;
72
    }
73
}
74