Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
Container
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
4 / 4
7
100.00% covered (success)
100.00%
1 / 1
 set
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 has
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 get
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 remove
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2declare(strict_types=1);
3/**
4 * Pop PHP Framework (https://www.popphp.org/)
5 *
6 * @link       https://github.com/popphp/popphp-framework
7 * @author     Nick Sagona, III <nick@popphp.org>
8 * @copyright  Copyright (c) 2009-2026 Nick Sagona, III
9 * @license    https://www.popphp.org/license     New BSD License
10 */
11
12/**
13 * @namespace
14 */
15namespace Pop\Service;
16
17/**
18 * Service container class
19 *
20 * @category   Pop
21 * @package    Pop\Service
22 * @author     Nick Sagona, III <nick@popphp.org>
23 * @copyright  Copyright (c) 2009-2026 Nick Sagona, III
24 * @license    https://www.popphp.org/license     New BSD License
25 * @version    5.0.0
26 */
27class Container
28{
29
30    /**
31     * Array service locators
32     * @var array
33     */
34    private static array $locators = ['default' => null];
35
36    /**
37     * Set a service locator
38     *
39     * @param  string  $name
40     * @param  Locator $locator
41     * @return void
42     */
43    public static function set(string $name, Locator $locator): void
44    {
45        self::$locators[$name] = $locator;
46    }
47
48    /**
49     * Determine if a service locator has been set
50     *
51     * @param  string $name
52     * @return bool
53     */
54    public static function has(string $name): bool
55    {
56        return (!empty(self::$locators[$name]) && (self::$locators[$name] instanceof Locator));
57    }
58
59    /**
60     * Get a service locator
61     *
62     * @param  string $name
63     * @throws Exception
64     * @return Locator
65     */
66    public static function get(string $name = 'default'): Locator
67    {
68        if (empty(self::$locators[$name])) {
69            throw new Exception("Error: The service locator '" . $name . "' has not been added");
70        }
71        return self::$locators[$name];
72    }
73
74    /**
75     * Remove a service locator
76     *
77     * @param  string $name
78     * @return void
79     */
80    public static function remove(string $name): void
81    {
82        if (isset(self::$locators[$name])) {
83            unset(self::$locators[$name]);
84        }
85    }
86
87}