<commit_before># --
# Copyright (C) 2001-2016 OTRS AG, http://otrs.com/
# --
# This software comes with ABSOLUTELY NO WARRANTY. For details, see
# the enclosed file COPYING for license information (AGPL). If you
# did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
# --

package Kernel::System::ObjectManager;
## nofilter(TidyAll::Plugin::OTRS::Perl::PodSpelling)
## nofilter(TidyAll::Plugin::OTRS::Perl::Require)
## nofilter(TidyAll::Plugin::OTRS::Perl::SyntaxCheck)

use strict;
use warnings;

use Carp qw(carp confess);
use Scalar::Util qw(weaken);

# use the "standard" modules directly, so that persistent environments
# like mod_perl and FastCGI pre-load them at startup

use Kernel::Config;
use Kernel::Output::HTML::Layout;
use Kernel::System::Auth;
use Kernel::System::AuthSession;
use Kernel::System::Cache;
use Kernel::System::DB;
use Kernel::System::Encode;
use Kernel::System::Group;
use Kernel::System::Log;
use Kernel::System::Main;
use Kernel::System::Time;
use Kernel::System::Web::Request;
use Kernel::System::User;

=head1 NAME

Kernel::System::ObjectManager - Central singleton manager and object instance generator

=head1 SYNOPSIS

    # In toplevel scripts only!
    local $Kernel::OM = Kernel::System::ObjectManager->new();

    # Everywhere: get a singleton instance (and create it, if needed).
    my $ConfigObject = $Kernel::OM->Get('Kernel::Config');

    # Remove singleton objects and all their dependencies.
    $Kernel::OM->ObjectsDiscard(
        Objects            => ['Kernel::System::Ticket', 'Kernel::System::Queue'],
    );

=head1 DESCRIPTION

The ObjectManager is the central place to create and access singleton OTRS objects (via C<L</Get()>>)
as well as create regular (unmanaged) object instances (via C<L</Create()>>).

=head2 How does singleton management work?

It creates objects as late as possible and keeps references to them. Upon destruction the objects
are destroyed in the correct order, based on their dependencies (see below).

=head2 How to use it?

The ObjectManager must always be provided to OTRS by the toplevel script like this:

    use Kernel::System::ObjectManager;
    local $Kernel::OM = Kernel::System::ObjectManager->new(
        # possible options for module constructors here
        LogObject {
            LogPrefix => 'OTRS-MyTestScript',
        },
    );

Then in the code any singleton object can be retrieved that the ObjectManager can handle,
like Kernel::System::DB:

    return if !$Kernel::OM->Get('Kernel::System::DB')->Prepare('SELECT 1');

=head2 Which objects can be loaded?

The ObjectManager can load every object that declares its dependencies like this in the Perl package:

    package Kernel::System::Valid;

    use strict;
    use warnings;

    our @ObjectDependencies = (
        'Kernel::System::Cache',
        'Kernel::System::DB',
        'Kernel::System::Log',
    );

The C<@ObjectDependencies> is the list of objects that the current object will depend on. They will
be destroyed only after this object is destroyed (only for singletons).

If you want to signal that a package can NOT be loaded by the ObjectManager, you can use the
C<$ObjectManagerDisabled> flag:

    package Kernel::System::MyBaseClass;

    use strict;
    use warnings;

    our $ObjectManagerDisabled = 1;

There are a few flags available to convey meta data about the packages to the object manager.

To indicate that a certain package can ONLY be loaded as a singleton, you can use the
C<IsSingleton> flag. Similarly, you can indicate that a certain package can ONLY be created as unmanaged instance,
and NOT as a singleton via the C<NonSingleton> flag.
By default, the ObjectManager will die if a constructor does not return an object. To suppress this in the C<L</Create()>> method, you can use the C<AllowConstructorFailure> flag (this will not work with C<L</Get()>>).

    package Kernel::System::MyPackage;

    use strict;
    use warnings;

    our %ObjectManagerFlags = (
        IsSingleton             => 1,  # default 0
        NonSingleton            => 0,  # default 0
        AllowConstructorFailure => 0,  # default 0
    );

=head1 PUBLIC INTERFACE

=head2 new()

Creates a new instance of Kernel::System::ObjectManager.

This is typically B<only> needed in toplevel (bin/) scripts! All parts of the OTRS API assume
the ObjectManager to be present in C<$Kernel::OM> and use it.

Sometimes objects need parameters to be sent to their constructors,
these can also be passed to the ObjectManager's constructor like in the following example.
The hash reference will be flattened and passed to the constructor of the object(s).

    local $Kernel::OM = Kernel::System::ObjectManager->new(
        Kernel::System::Log => {
            LogPrefix => 'OTRS-MyTestScript',
        },
    );

Alternatively, C<L</ObjectParamAdd()>> can be used to set these parameters at runtime (but this
must happen before the object was created).

If the C<< Debug => 1 >> option is present, destruction of objects
is checked, and a warning is emitted if objects persist after the
attempt to destroy them.

=cut

sub new {
    my ( $Type, %Param ) = @_;
    my $Self = bless {}, $Type;

    $Self->{Debug} = delete $Param{Debug};

    for my $Parameter ( sort keys %Param ) {
        $Self->{Param}->{$Parameter} = $Param{$Parameter};
    }

    # Kernel::System::Encode->new() initializes the environment, so we need to
    #   already create an instance here to make sure it is always done and done
    #   at the beginning of things.
    $Self->Get('Kernel::System::Encode');

    return $Self;
}

=head2 Get()

Retrieves a singleton object, and if it not yet exists, implicitly creates one for you.

    my $ConfigObject = $Kernel::OM->Get('Kernel::Config');

    # On the second call, this returns the same ConfigObject as above.
    my $ConfigObject2 = $Kernel::OM->Get('Kernel::Config');

=cut

sub Get {

    # No param unpacking for increased performance
    if ( $_[1] && $_[0]->{Objects}->{ $_[1] } ) {
        return $_[0]->{Objects}->{ $_[1] };
    }

    if ( !$_[1] ) {
        $_[0]->_DieWithError(
            Error => "Error: Missing parameter (object name)",
        );
    }

    return $_[0]->_ObjectBuild( Package => $_[1] );
}

=head2 Create()

Creates a new object instance. This instance will not be managed by the object manager later on.

    my $DateTimeObject = $Kernel::OM->Create('Kernel::System::DateTime');

    # On the second call, this creates a new independent instance.
    my $DateTimeObject2 = $Kernel::OM->Create('Kernel::System::DateTime');

It is also possible to pass in constructor parameters:

    my $DateTimeObject = $Kernel::OM->Create(
        'Kernel::System::DateTime',
        ObjectParams => {
            Param1 => 'Value1',
        },
    );

By default, this method will C<die>, if the package cannot be instantiated or the constructor returns undef.
You can suppress this with C<< Silent => 1 >>, for example to not cause exceptions when trying
to load modules based on user configuration.

    my $CustomObject = $Kernel::OM->Create(
        'Kernel::System::CustomObject',
        Silent => 1,
    );

=cut

sub Create {
    my ( $Self, $Package, %Param ) = @_;

    if ( !$Package ) {
        $Self->_DieWithError(
            Error => "Error: Missing parameter (object name)",
        );
    }

    return $Self->_ObjectBuild(
        %Param,
        Package     => $Package,
        NoSingleton => 1,
    );
}

sub _ObjectBuild {
    my ( $Self, %Param ) = @_;

    my $Package  = $Param{Package};
    my $FileName = $Package;
    $FileName =~ s{::}{/}g;
    $FileName .= '.pm';
    eval {
        require $FileName;
    };
    if ($@) {
        if ( $Param{Silent} ) {
            return;    # don't throw
        }
        $Self->_DieWithError(
            Error => "$Package could not be loaded: $@",
        );
    }

    # Kernel::Config does not declare its dependencies (they would have to be in
    #   Kernel::Config::Defaults), so assume [] in this case.
    my $Dependencies = [];

    no strict 'refs';    ## no critic
    my %ObjectManagerFlags = %{ $Package . '::ObjectManagerFlags' };
    use strict 'refs';

    if ( $Package ne 'Kernel::Config' ) {
        no strict 'refs';    ## no critic
        if ( !exists ${ $Package . '::' }{ObjectDependencies} ) {
            $Self->_DieWithError( Error => "$Package does not declare its object dependencies!" );
        }
        $Dependencies = \@{ $Package . '::ObjectDependencies' };

        if ( ${ $Package . '::ObjectManagerDisabled' } ) {
            $Self->_DieWithError( Error => "$Package cannot be loaded via ObjectManager!" );
        }

        if ( $Param{NoSingleton} ) {
            if ( $ObjectManagerFlags{IsSingleton} ) {
                $Self->_DieWithError(
                    Error =>
                        "$Package cannot be created as a new instance via ObjectManager! Use Get() instead of Create() to fetch the singleton."
                );
            }
        }
        else {
            if ( $ObjectManagerFlags{NonSingleton} ) {
                $Self->_DieWithError(
                    Error =>
                        "$Package cannot be loaded as a singleton via ObjectManager! Use Create() instead of Get() to create new instances."
                );
            }
        }

        use strict 'refs';
    }
    $Self->{ObjectDependencies}->{$Package} = $Dependencies;

    my $NewObject = $Package->new(
        %{ $Param{ObjectParams} // $Self->{Param}->{$Package} // {} }
    );

    if ( !defined $NewObject ) {
        if ( $Param{Silent} || $ObjectManagerFlags{AllowConstructorFailure} ) {
            return;    # don't throw
        }
        $Self->_DieWithError(
            Error => "The constructor of $Package returned undef.",
        );
    }

    return $NewObject if ( $Param{NoSingleton} );

    $Self->{Objects}->{$Package} = $NewObject;

    return $NewObject;
}

=head2 ObjectInstanceRegister()

Adds an existing object instance to the ObjectManager so that it can be accessed by other objects.

This should B<only> be used on special circumstances, e. g. in the unit tests to pass $Self to the
ObjectManager so that it is also available from there as 'Kernel::System::UnitTest'.
<commit_msg>Improved ObjectManager POD.<commit_after># --
# Copyright (C) 2001-2016 OTRS AG, http://otrs.com/
# --
# This software comes with ABSOLUTELY NO WARRANTY. For details, see
# the enclosed file COPYING for license information (AGPL). If you
# did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
# --

package Kernel::System::ObjectManager;
## nofilter(TidyAll::Plugin::OTRS::Perl::PodSpelling)
## nofilter(TidyAll::Plugin::OTRS::Perl::Require)
## nofilter(TidyAll::Plugin::OTRS::Perl::SyntaxCheck)

use strict;
use warnings;

use Carp qw(carp confess);
use Scalar::Util qw(weaken);

# use the "standard" modules directly, so that persistent environments
# like mod_perl and FastCGI pre-load them at startup

use Kernel::Config;
use Kernel::Output::HTML::Layout;
use Kernel::System::Auth;
use Kernel::System::AuthSession;
use Kernel::System::Cache;
use Kernel::System::DB;
use Kernel::System::Encode;
use Kernel::System::Group;
use Kernel::System::Log;
use Kernel::System::Main;
use Kernel::System::Time;
use Kernel::System::Web::Request;
use Kernel::System::User;

=head1 NAME

Kernel::System::ObjectManager - Central singleton manager and object instance generator

=head1 SYNOPSIS

    # In toplevel scripts only!
    local $Kernel::OM = Kernel::System::ObjectManager->new();

    # Everywhere: get a singleton instance (and create it, if needed).
    my $ConfigObject = $Kernel::OM->Get('Kernel::Config');

    # Remove singleton objects and all their dependencies.
    $Kernel::OM->ObjectsDiscard(
        Objects            => ['Kernel::System::Ticket', 'Kernel::System::Queue'],
    );

=head1 DESCRIPTION

The ObjectManager is the central place to create and access singleton OTRS objects (via C<L</Get()>>)
as well as create regular (unmanaged) object instances (via C<L</Create()>>).

=head2 How does singleton management work?

It creates objects as late as possible and keeps references to them. Upon destruction the objects
are destroyed in the correct order, based on their dependencies (see below).

=head2 How to use it?

The ObjectManager must always be provided to OTRS by the toplevel script like this:

    use Kernel::System::ObjectManager;
    local $Kernel::OM = Kernel::System::ObjectManager->new(
        # possible options for module constructors here
        LogObject {
            LogPrefix => 'OTRS-MyTestScript',
        },
    );

Then in the code any singleton object can be retrieved that the ObjectManager can handle,
like Kernel::System::DB:

    return if !$Kernel::OM->Get('Kernel::System::DB')->Prepare('SELECT 1');

=head2 Which objects can be loaded?

The ObjectManager can load every object that declares its dependencies like this in the Perl package:

    package Kernel::System::Valid;

    use strict;
    use warnings;

    our @ObjectDependencies = (
        'Kernel::System::Cache',
        'Kernel::System::DB',
        'Kernel::System::Log',
    );

The C<@ObjectDependencies> is the list of objects that the current object will depend on. They will
be destroyed only after this object is destroyed (only for singletons).

If you want to signal that a package can NOT be loaded by the ObjectManager, you can use the
C<$ObjectManagerDisabled> flag:

    package Kernel::System::MyBaseClass;

    use strict;
    use warnings;

    our $ObjectManagerDisabled = 1;

There are a few flags available to convey meta data about the packages to the object manager.

To indicate that a certain package can B<only> be loaded as a singleton, you can use the
C<IsSingleton> flag. Similarly, you can indicate that a certain package can B<only> be
created as unmanaged instance, and B<not> as a singleton via the C<NonSingleton> flag.
By default, the ObjectManager will die if a constructor does not return an object.
To suppress this in the C<L</Create()>> method, you can use the C<AllowConstructorFailure>
flag (this will not work with C<L</Get()>>).

    package Kernel::System::MyPackage;

    use strict;
    use warnings;

    our %ObjectManagerFlags = (
        IsSingleton             => 1,  # default 0
        NonSingleton            => 0,  # default 0
        AllowConstructorFailure => 0,  # default 0
    );

=head1 PUBLIC INTERFACE

=head2 new()

Creates a new instance of Kernel::System::ObjectManager.

This is typically B<only> needed in toplevel (bin/) scripts! All parts of the OTRS API assume
the ObjectManager to be present in C<$Kernel::OM> and use it.

Sometimes objects need parameters to be sent to their constructors,
these can also be passed to the ObjectManager's constructor like in the following example.
The hash reference will be flattened and passed to the constructor of the object(s).

    local $Kernel::OM = Kernel::System::ObjectManager->new(
        Kernel::System::Log => {
            LogPrefix => 'OTRS-MyTestScript',
        },
    );

Alternatively, C<L</ObjectParamAdd()>> can be used to set these parameters at runtime (but this
must happen before the object was created).

If the C<< Debug => 1 >> option is present, destruction of objects
is checked, and a warning is emitted if objects persist after the
attempt to destroy them.

=cut

sub new {
    my ( $Type, %Param ) = @_;
    my $Self = bless {}, $Type;

    $Self->{Debug} = delete $Param{Debug};

    for my $Parameter ( sort keys %Param ) {
        $Self->{Param}->{$Parameter} = $Param{$Parameter};
    }

    # Kernel::System::Encode->new() initializes the environment, so we need to
    #   already create an instance here to make sure it is always done and done
    #   at the beginning of things.
    $Self->Get('Kernel::System::Encode');

    return $Self;
}

=head2 Get()

Retrieves a singleton object, and if it not yet exists, implicitly creates one for you.

    my $ConfigObject = $Kernel::OM->Get('Kernel::Config');

    # On the second call, this returns the same ConfigObject as above.
    my $ConfigObject2 = $Kernel::OM->Get('Kernel::Config');

=cut

sub Get {

    # No param unpacking for increased performance
    if ( $_[1] && $_[0]->{Objects}->{ $_[1] } ) {
        return $_[0]->{Objects}->{ $_[1] };
    }

    if ( !$_[1] ) {
        $_[0]->_DieWithError(
            Error => "Error: Missing parameter (object name)",
        );
    }

    return $_[0]->_ObjectBuild( Package => $_[1] );
}

=head2 Create()

Creates a new object instance. This instance will not be managed by the object manager later on.

    my $DateTimeObject = $Kernel::OM->Create('Kernel::System::DateTime');

    # On the second call, this creates a new independent instance.
    my $DateTimeObject2 = $Kernel::OM->Create('Kernel::System::DateTime');

It is also possible to pass in constructor parameters:

    my $DateTimeObject = $Kernel::OM->Create(
        'Kernel::System::DateTime',
        ObjectParams => {
            Param1 => 'Value1',
        },
    );

By default, this method will C<die>, if the package cannot be instantiated or the constructor returns undef.
You can suppress this with C<< Silent => 1 >>, for example to not cause exceptions when trying
to load modules based on user configuration.

    my $CustomObject = $Kernel::OM->Create(
        'Kernel::System::CustomObject',
        Silent => 1,
    );

=cut

sub Create {
    my ( $Self, $Package, %Param ) = @_;

    if ( !$Package ) {
        $Self->_DieWithError(
            Error => "Error: Missing parameter (object name)",
        );
    }

    return $Self->_ObjectBuild(
        %Param,
        Package     => $Package,
        NoSingleton => 1,
    );
}

sub _ObjectBuild {
    my ( $Self, %Param ) = @_;

    my $Package  = $Param{Package};
    my $FileName = $Package;
    $FileName =~ s{::}{/}g;
    $FileName .= '.pm';
    eval {
        require $FileName;
    };
    if ($@) {
        if ( $Param{Silent} ) {
            return;    # don't throw
        }
        $Self->_DieWithError(
            Error => "$Package could not be loaded: $@",
        );
    }

    # Kernel::Config does not declare its dependencies (they would have to be in
    #   Kernel::Config::Defaults), so assume [] in this case.
    my $Dependencies = [];

    no strict 'refs';    ## no critic
    my %ObjectManagerFlags = %{ $Package . '::ObjectManagerFlags' };
    use strict 'refs';

    if ( $Package ne 'Kernel::Config' ) {
        no strict 'refs';    ## no critic
        if ( !exists ${ $Package . '::' }{ObjectDependencies} ) {
            $Self->_DieWithError( Error => "$Package does not declare its object dependencies!" );
        }
        $Dependencies = \@{ $Package . '::ObjectDependencies' };

        if ( ${ $Package . '::ObjectManagerDisabled' } ) {
            $Self->_DieWithError( Error => "$Package cannot be loaded via ObjectManager!" );
        }

        if ( $Param{NoSingleton} ) {
            if ( $ObjectManagerFlags{IsSingleton} ) {
                $Self->_DieWithError(
                    Error =>
                        "$Package cannot be created as a new instance via ObjectManager! Use Get() instead of Create() to fetch the singleton."
                );
            }
        }
        else {
            if ( $ObjectManagerFlags{NonSingleton} ) {
                $Self->_DieWithError(
                    Error =>
                        "$Package cannot be loaded as a singleton via ObjectManager! Use Create() instead of Get() to create new instances."
                );
            }
        }

        use strict 'refs';
    }
    $Self->{ObjectDependencies}->{$Package} = $Dependencies;

    my $NewObject = $Package->new(
        %{ $Param{ObjectParams} // $Self->{Param}->{$Package} // {} }
    );

    if ( !defined $NewObject ) {
        if ( $Param{Silent} || $ObjectManagerFlags{AllowConstructorFailure} ) {
            return;    # don't throw
        }
        $Self->_DieWithError(
            Error => "The constructor of $Package returned undef.",
        );
    }

    return $NewObject if ( $Param{NoSingleton} );

    $Self->{Objects}->{$Package} = $NewObject;

    return $NewObject;
}

=head2 ObjectInstanceRegister()

Adds an existing object instance to the ObjectManager so that it can be accessed by other objects.

This should B<only> be used on special circumstances, e. g. in the unit tests to pass C<$Self> to the
ObjectManager so that it is also available from there as 'Kernel::System::UnitTest'.

{'fraction_non_alphanumeric': 0.11920046688065364, 'fraction_numerical': 0.004279739324968388, 'mean_word_length': 3.0036993769470404, 'pattern_counts': {'":': 0, '<': 53, '<?xml version=': 0, '>': 177, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4713778', 'n_tokens_mistral': 5939, 'n_tokens_neox': 5665, 'n_words': 2104}