public function send()
    {
        $allowed_methods = ['POST', 'GET', 'PUT', 'PATCH', 'DELETE'];
        if (! in_array($this->method, $allowed_methods)) {
            throw new \Exception("Unknown method $this->method.");
        }
        $_SERVER['REQUEST_METHOD'] = $this->method;
        $this->injectParams();

        list($status, $value, $headers) = $this->execute();

        drupal_add_http_header('Content-Type', null);

        return new TestResponseMock([
            'status' => $status,
            'body' => $value,
            'headers' => [
                    'Cache-Control' => 'no-cache, must-revalidate',
                    'Connection' => 'Keep-Alive',
                    'Content-Language' => 'en',
                    'Content-Type' => 'text/html; charset=utf-8',
                    'Date' => gmdate('D, d M Y H:is e'),
                    'Expires' => gmdate('D, d M Y H:is e'),
                    'Keep-Alive' => 'timeout=5, max=100',
                    'Server' => 'Apache/2.4.29 (Unix) PHP/'.phpversion(),
                    'Transfer-Encoding' => 'chunked',
                    'X-Content-Type-Options' => 'nosniff',
                    'X-Frame-Options' => 'SAMEORIGIN',
                    'X-Generator' => 'Drupal 7 (http://drupal.org)',
                ] + $headers,
        ]);
    }

public
function
send
(
)
{
$
allowed_methods
=
[
'POST'
,
'GET'
,
'PUT'
,
'PATCH'
,
'DELETE'
]
;
if
(
!
in_array
(
$
this
->
method
,
$
allowed_methods
)
)
{
throw
new
\
Exception
(
"Unknown method $this->method."
)
;
}
$
_SERVER
[
'REQUEST_METHOD'
]
=
$
this
->
method
;
$
this
->
injectParams
(
)
;
list
(
$
status
,
$
value
,
$
headers
)
=
$
this
->
execute
(
)
;
drupal_add_http_header
(
'Content-Type'
,
)
;
return
new
TestResponseMock
(
[
'status'
=>
$
status
,
'body'
=>
$
value
,
'headers'
=>
[
'Cache-Control'
=>
'no-cache, must-revalidate'
,
'Connection'
=>
'Keep-Alive'
,
'Content-Language'
=>
'en'
,
'Content-Type'
=>
'text/html; charset=utf-8'
,
'Date'
=>
gmdate
(
'D, d M Y H:is e'
)
,
'Expires'
=>
gmdate
(
'D, d M Y H:is e'
)
,
'Keep-Alive'
=>
'timeout=5, max=100'
,
'Server'
=>
'Apache/2.4.29 (Unix) PHP/'
.
phpversion
(
)
,
'Transfer-Encoding'
=>
'chunked'
,
'X-Content-Type-Options'
=>
'nosniff'
,
'X-Frame-Options'
=>
'SAMEORIGIN'
,
'X-Generator'
=>
'Drupal 7 (http://drupal.org)'
,
]
+
$
headers
,
]
)
;
}

Creates a mock HTTP response.

@return \StatonLab\TripalTestSuite\Mocks\TestResponseMock
@throws \Exception


protected function execute()
    {
        $this->resetHeaders();
        $this->resetStaticCache();

        // Move to drupal root where the index.php is
        $current_dir = getcwd();
        chdir(DRUPAL_ROOT);

        $value = '';
        ob_start(function ($str) use (&$value) {
            $value .= $str;
        });
        $buffer = menu_execute_active_handler($this->path, false);
        ob_end_clean();

        $status = 200;
        if ($buffer === MENU_NOT_FOUND) {
            $status = 404;
            $value = '';
            ob_start(function ($str) use (&$value) {
                $value .= $str;
            });
            drupal_not_found();
            ob_end_clean();
        } elseif ($buffer === MENU_ACCESS_DENIED) {
            $status = 403;
            $value = '';
            ob_start(function ($str) use (&$value) {
                $value .= $str;
            });
            drupal_access_denied();
            ob_end_clean();
        } elseif (empty($value)) {
            $value = drupal_render_page($buffer);
        }

        // Go back to the test directory
        chdir($current_dir);

        return [
            $status,
            $value,
            drupal_get_http_header(),
        ];
    }

Execute the menu handler and construct the response.

@return array

Execute the menu handler and construct the response .


protected function injectParams()
    {
        $_GET['q'] = $this->path;
        $_SERVER['REQUEST_URI'] = $this->path;

        if (in_array($this->method, ['GET', 'DELETE'])) {
            foreach ($this->params as $key => $param) {
                $_GET[$key] = $param;
            }

            return;
        }

        $menu_item = menu_get_item($this->path);
        $_POST['form_id'] = isset($menu_item['page_arguments']) ? $menu_item['page_arguments'][0] : '';
        foreach ($this->params as $key => $param) {
            $_POST[$key] = $param;
        }
    }

protected function injectParams ( ) { $ _GET [ 'q' ] = $ this -> path ; $ _SERVER [ 'REQUEST_URI' ] = $ this -> path ; if ( in_array ( $ this -> method , [ 'GET' , 'DELETE' ] ) ) { foreach ( $ this -> params as $ key => $ param ) { $ _GET [ $ key ] = $ param ; } return ; } $ menu_item = menu_get_item ( $ this -> path ) ; $ _POST [ 'form_id' ] = isset ( $ menu_item [ 'page_arguments' ] ) ? $ menu_item [ 'page_arguments' ] [ 0 ] : '' ; foreach ( $ this -> params as $ key => $ param ) { $ _POST [ $ key ] = $ param ; } }


public function findOneByAttributeCode($attributeCode)
    {
        // load and return the EAV attribute with the passed code
        $this->attributeByAttributeCodeStmt->execute(array(MemberNames::ATTRIBUTE_CODE => $attributeCode));
        return $this->attributeByAttributeCodeStmt->fetch(\PDO::FETCH_ASSOC);
    }

Return's the EAV attribute with the passed code.

@param string $attributeCode The code of the EAV attribute to return

@return array The EAV attribute
@deprecated Since 2.0.2
@see \TechDivision\Import\Attribute\Repositories\AttributeRepositoryInterface::findOneByEntityIdAndAttributeCode()

Return s the EAV attribute with the passed code .


public function tearDown($serial)
    {

        // invoke the parent method
        parent::tearDown($serial);

        // load the registry processor
        $registryProcessor = $this->getRegistryProcessor();

        // update the status
        $registryProcessor->mergeAttributesRecursive(
            $serial,
            array(
                RegistryKeys::PRE_LOADED_ATTRIBUTE_IDS => $this->preLoadedAttributeIds,
            )
        );
    }

public
function
tearDown
(
$
serial
)
{
// invoke the parent method
parent
::
tearDown
(
$
serial
)
;
// load the registry processor
$
registryProcessor
=
$
this
->
getRegistryProcessor
(
)
;
// update the status
$
registryProcessor
->
mergeAttributesRecursive
(
$
serial
,
array
(
RegistryKeys
::
PRE_LOADED_ATTRIBUTE_IDS
=>
$
this
->
preLoadedAttributeIds
,
)
)
;
}

Clean up the global data after importing the bunch.

@param string $serial The serial of the actual import

@return void

Clean up the global data after importing the bunch .


public function preLoadAttributeId(array $attribute)
    {
        $this->preLoadedAttributeIds[$attribute[MemberNames::ATTRIBUTE_CODE]]= $attribute[MemberNames::ATTRIBUTE_ID];
    }

public function preLoadAttributeId ( array $ attribute ) { $ this -> preLoadedAttributeIds [ $ attribute [ MemberNames :: ATTRIBUTE_CODE ] ] = $ attribute [ MemberNames :: ATTRIBUTE_ID ] ; }

Pre-load and temporary persist the attribute ID for the passed EAV attribute.

@param array $attribute The EAV attribute to pre-load

@return void

Pre - load and temporary persist the attribute ID for the passed EAV attribute .


public function publish($data_table, array $ids = [], $primary_key = '')
    {
        $publisher = new PublishRecords($data_table, $ids, $primary_key);
        $publisher->publish();

        return $publisher;
    }

public function publish ( $ data_table , array $ ids = [ ] , $ primary_key = '' ) { $ publisher = new PublishRecords ( $ data_table , $ ids , $ primary_key ) ; $ publisher -> publish ( ) ; return $ publisher ; }

Publish records from chado to entities.

@param string data_table Chado table name such as feature.
@param array $ids CURRENTLY UNSUPPORTED.
@param string $primary_key The primary key name such as feature_id. If not
provided, the key is obtained using the tripal API.
@throws \Exception
@return \StatonLab\TripalTestSuite\Database\PublishRecords

Publish records from chado to entities .


public function assertSee($content)
    {
        $response = (string)$this->getResponseBody();
        PHPUnit::assertContains($content, $response, "Unable to find [$content] in response.");

        return $this;
    }

Assert string exists in response body.

@param string $content
@return $this


public function json()
    {
        $json = json_decode($this->getResponseBody(), true);
        if (is_null($json)) {
            PHPUnit::fail('Unable to decode json response!');

            throw new InvalidJSONException('Unable to decode json response!');
        }

        return $json;
    }

public
function
json
(
)
{
$
json
=
json_decode
(
$
this
->
getResponseBody
(
)
,
true
)
;
if
(
is_null
(
$
json
)
)
{
PHPUnit
::
fail
(
'Unable to decode json response!'
)
;
throw
new
InvalidJSONException
(
'Unable to decode json response!'
)
;
}
return
$
json
;
}

Get the json response as an associative array.

@return array
@throws \StatonLab\TripalTestSuite\Exceptions\InvalidJSONException

Get the json response as an associative array .


public function assertJsonStructure(array $structure, $data = null)
    {
        if (is_null($data)) {
            try {
                $data = $this->json();
            } catch (InvalidJSONException $exception) {
                PHPUnit::fail('Unable to decode json response!');
            }
        }

        foreach ($structure as $key => $value) {
            if (is_array($value)) {
                PHPUnit::assertArrayHasKey($key, $data);

                // Prevent infinite loops
                if (is_null($data[$key])) {
                    continue;
                }

                $this->assertJsonStructure($structure[$key], $data[$key]);
                continue;
            }

            PHPUnit::assertArrayHasKey($value, $data);
        }

        return $this;
    }

public
function
assertJsonStructure
(
array
$
structure
,
$
data
=
)
{
if
(
is_null
(
$
data
)
)
{
try
{
$
data
=
$
this
->
json
(
)
;
}
catch
(
InvalidJSONException
$
exception
)
{
PHPUnit
::
fail
(
'Unable to decode json response!'
)
;
}
}
foreach
(
$
structure
as
$
key
=>
$
value
)
{
if
(
is_array
(
$
value
)
)
{
PHPUnit
::
assertArrayHasKey
(
$
key
,
$
data
)
;
// Prevent infinite loops
if
(
is_null
(
$
data
[
$
key
]
)
)
{
continue
;
}
$
this
->
assertJsonStructure
(
$
structure
[
$
key
]
,
$
data
[
$
key
]
)
;
continue
;
}
PHPUnit
::
assertArrayHasKey
(
$
value
,
$
data
)
;
}
return
$
this
;
}

Assert that the response has the given structure.

@param array $structure Expected structure
@params array $data Response data
@return $this

Assert that the response has the given structure .


public function run()
    {
        // Don't bootstrap twice in runtime
        if (static::$bootstrapped) {
            return;
        }

        // Read environment variables to set drupal root
        $this->readEnvironmentFile();

        // Set the base url if provided in environment
        $this->setBaseURL();

        // Read environment variables
        if (! defined('DRUPAL_ROOT')) {
            define('DRUPAL_ROOT', $this->getDrupalRoot());
        }

        if (empty(DRUPAL_ROOT)) {
            throw new TripalTestSuiteException('DRUPAL_ROOT is not configured correctly. Please use .env files to set DRUPAL_ROOT.');
        }

        require_once DRUPAL_ROOT.'/includes/bootstrap.inc';
        $_SERVER['REMOTE_ADDR'] = '127.0.0.1';

        $cwd = getcwd();
        chdir(DRUPAL_ROOT);
        // The bootstrap function won't run twice since drupal checks if it has run it before
        drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
        chdir($cwd);

        static::$bootstrapped = true;
    }

Bootstrap Drupal.

@throws \Statonlab\TripalTestSuite\Exceptions\TripalTestSuiteException


protected function getDrupalRoot()
    {
        if ($path = getenv('DRUPAL_ROOT')) {
            return $path;
        }

        $path = getcwd();
        while ($path !== '/') {
            if (file_exists($path.'/includes/bootstrap.inc')) {
                return $path;
            }

            $path = dirname($path);
        }

        return '';
    }

protected function getDrupalRoot ( ) { if ( $ path = getenv ( 'DRUPAL_ROOT' ) ) { return $ path ; } $ path = getcwd ( ) ; while ( $ path !== '/' ) { if ( file_exists ( $ path . '/includes/bootstrap.inc' ) ) { return $ path ; } $ path = dirname ( $ path ) ; } return '' ; }


protected function getEnvironmentFilePath()
    {
        $dir = getcwd();

        // If running phpunit from the module root dir
        if (file_exists($dir.'/tests/.env')) {
            return $dir.'/tests/.env';
        }

        // If running phpunit from the module root dir
        if (file_exists($dir.'/test/.env')) {
            return $dir.'/test/.env';
        }

        // If running php unit from within the tests dir
        if (file_exists($dir.'/.env')) {
            return $dir.'/.env';
        }

        return false;
    }

Look for environment variable file.

@return bool|string


protected function readEnvironmentFile()
    {
        $env_file_path = $this->getEnvironmentFilePath();

        if ($env_file_path) {
            $line_count = 0;
            $file = fopen($env_file_path, 'r');
            while ($line = fgets($file)) {
                $line++;
                $line = trim($line);
                if (empty($line)) {
                    continue;
                }

                // Ignore comments
                if(str_begins_with('//', $line) || str_begins_with('-', $line) || str_begins_with('#', $line)) {
                    continue;
                }

                if (putenv(str_replace("\n", '', trim($line))) === false) {
                    throw new TripalTestSuiteException("Could not read environment line $line_count: $line");
                }
            }
        }
    }

Read env files.

@throws \Statonlab\TripalTestSuite\Exceptions\TripalTestSuiteException


public function publish()
    {
        // Find the bundle
        $this->bundles = db_query('SELECT name, bundle_id FROM chado_bundle
                             JOIN tripal_bundle ON tripal_bundle.id = chado_bundle.bundle_id
                             WHERE data_table = :data_table', [':data_table' => $this->data_table])->fetchAll();

        if (empty($this->bundles)) {
            throw new Exception("Unable to find bundles for $this->data_table. Publishing failed!");
        }

        // Perform the publishing
        foreach ($this->bundles as $bundle) {
            // Publish Records
            try {
                $published = $this->tripalChadoPublishRecords($bundle->name, $this->ids);
            } catch (Exception $exception) {
                $this->delete();
                throw $exception;
            }

            $this->published[] = $published;
        }
    }

Perform the publishing.

@throws Exception


public function loadDatabaseSeeders()
    {
        $workingDir = getcwd();
        if (file_exists("$workingDir/tests/DatabaseSeeders")) {
            foreach (glob("$workingDir/tests/DatabaseSeeders/*.php") as $seeder) {
                require_once $seeder;

                // Extract the class name
                /** @var \StatonLab\TripalTestSuite\Database\Seeder $className */
                $className = $this->getClassName($seeder);

                if (! class_exists($className)) {
                    $error = "Database seeder class $className not found. Make sure the filename and the class name match.";
                    throw new TripalTestBootstrapException($error);
                }

                $this->seeders[] = $className;
            }
        }

        return $this->seeders;
    }

Load the database seeders.

@return mixed
@throws TripalTestBootstrapException


public function getEntityType($entityTypeCode = null)
    {

        // set the default entity type code, if non has been passed
        if ($entityTypeCode === null) {
            $entityTypeCode = $this->getDefaultEntityTypeCode();
        }

        // query whether or not, the entity type with the passed code is available
        if (isset($this->entityTypes[$entityTypeCode])) {
            return $this->entityTypes[$entityTypeCode];
        }

        // throw an exception, if not
        throw new \Exception(
            sprintf(
                'Can\'t find entity type with code %s in file %s on line %d',
                $entityTypeCode,
                $this->getFilename(),
                $this->getLineNumber()
            )
        );
    }

Return's the entity type for the passed code, of if no entity type code has
been passed, the default one from the configuration will be used.

@param string|null $entityTypeCode The entity type code

@return array The requested entity type
@throws \Exception Is thrown, if the entity type with the passed code is not available

Return s the entity type for the passed code of if no entity type code has been passed the default one from the configuration will be used .


public function getEntityTypeId($entityTypeCode = null)
    {

        // load the entity type for the given code, or the default one otherwise
        $entityType = $this->getEntityType($entityTypeCode ? $entityTypeCode : $this->getDefaultEntityTypeCode());

        // return the entity type ID
        return $entityType[MemberNames::ENTITY_TYPE_ID];
    }

Returns the entity type ID for the passed code, or if no entity type code has
been passed, the default one from the configuration will be used.

@param string|null $entityTypeCode The entity type code

@return integer The actual entity type ID

Returns the entity type ID for the passed code or if no entity type code has been passed the default one from the configuration will be used .


private function _call($method, $uri, $params = [])
    {
        if (! str_begins_with('http', $uri)) {
            $client = new MenuCaller();

            return $client->setPath($uri)->setMethod($method)->addParams($params)->send();
        }

        try {
            $client = new Client();
            $uri = $this->_prepareURI($uri);

            if (! empty($this->_cookies)) {
                $domain = str_replace('http://', '', $GLOBALS['base_url']);
                $domain = str_replace('https://', '', $domain);
                $cookieJar = CookieJar::fromArray($this->_cookies, $domain);
                $params['cookies'] = $cookieJar;
            }

            return new TestResponse($client->request($method, $uri, $params));
        } catch (\GuzzleHttp\Exception\GuzzleException $exception) {
            PHPUnit::fail("Failed to send $method request to $uri. ".$exception->getMessage());
        }

        return null;
    }

Sends the request.

@param string $method
@param string $uri
@params array $params

@throws \Exception
@return TestResponse


private function _prepareURI($uri)
    {
        global $base_url;

        if (str_begins_with($uri, '/') || ! str_begins_with($uri, 'http')) {
            return trim($base_url.'/'.trim($uri, '/'), '/');
        }

        return trim($uri, '/');
    }

private function _prepareURI ( $ uri ) { global $ base_url ; if ( str_begins_with ( $ uri , '/' ) || ! str_begins_with ( $ uri , 'http' ) ) { return trim ( $ base_url . '/' . trim ( $ uri , '/' ) , '/' ) ; } return trim ( $ uri , '/' ) ; }

Prepare url for request.

@param $uri
@return string


public function acceptDistributedTracePayloadHttpsafe(string $payload, string $type = 'HTTP'): bool
    {
        if (!$this->isLoaded()) {
            return false;
        }

        return newrelic_accept_distributed_trace_payload_httpsafe($payload, $type);
    }

Accepts a distributed trace payload.

Agent version 8.4 or higher.

@see https://docs.newrelic.com/docs/agents/php-agent/php-agent-api/newrelicacceptdistributedtracepayloadhttpsafe-php-agent-api
@see self::createDistributedTracePayload

@param string $payload JSON formatted string created by using self::createDistributedTracePayload
@param string $type    (optional) A string overriding the default transport type.

@return bool

@since 2.1.0


public function endTransaction(bool $ignore = false): bool
    {
        if (!$this->isLoaded()) {
            return false;
        }

        return newrelic_end_transaction($ignore);
    }

public function endTransaction ( bool $ ignore = false ) : bool { if ( ! $ this -> isLoaded ( ) ) { return false ; } return newrelic_end_transaction ( $ ignore ) ; }

Stop instrumenting the current transaction immediately.

Agent version 3.0.5.95 or higher.

@see https://docs.newrelic.com/docs/agents/php-agent/php-agent-api/newrelic_end_transaction
@see self::endOfTransaction
@see self::startTransaction

@param bool $ignore (optional) Defaults to false

@return bool

Stop instrumenting the current transaction immediately .


public function setAppname($name, string $license = null, bool $xmit = false): bool
    {
        if (!$this->isLoaded()) {
            return false;
        }

        $name = is_array($name) ? implode(';', $name) : $name;

        if (isset($license)) {
            return newrelic_set_appname($name, $license, $xmit);
        }

        return newrelic_set_appname($name);
    }

public function setAppname ( $ name , string $ license = null , bool $ xmit = false ) : bool { if ( ! $ this -> isLoaded ( ) ) { return false ; } $ name = is_array ( $ name ) ? implode ( ';' , $ name ) : $ name ; if ( isset ( $ license ) ) { return newrelic_set_appname ( $ name , $ license , $ xmit ) ; } return newrelic_set_appname ( $ name ) ; }

Sets the New Relic app name, which controls data rollup.

Agent version 3.1.5.111 or higher.

@see https://docs.newrelic.com/docs/agents/php-agent/php-agent-api/newrelic_set_appname

@param string|array $name    Name(s) of app metrics should be reported under in New Relic user interface
@param string       $license (optional) Specify a different license key to report metrics to a different
New Relic account
@param bool         $xmit    (optional) Defaults to false

@return bool

Sets the New Relic app name which controls data rollup .


public function setUserAttributes(string $user, string $account, string $product): bool
    {
        if (!$this->isLoaded()) {
            return false;
        }

        return newrelic_set_user_attributes($user, $account, $product);
    }

public function setUserAttributes ( string $ user , string $ account , string $ product ) : bool { if ( ! $ this -> isLoaded ( ) ) { return false ; } return newrelic_set_user_attributes ( $ user , $ account , $ product ) ; }

Create user-related custom attributes. newrelic_add_custom_parameter is more flexible.

Agent version 3.1.5.111 or higher.

@see https://docs.newrelic.com/docs/agents/php-agent/php-agent-api/newrelic_set_user_attributes
@see self::addCustomParameter

@param string $user    Specify a name or username to associate with this page view
@param string $account Specify the name of a user account to associate with this page view
@param string $product Specify the name of a product to associate with this page view

@return bool

Create user - related custom attributes . newrelic_add_custom_parameter is more flexible .


public function startTransaction(string $appname, string $license = null): bool
    {
        if (!$this->isLoaded()) {
            return false;
        }

        if (isset($license)) {
            return newrelic_start_transaction($appname, $license);
        }

        return newrelic_start_transaction($appname);
    }

public function startTransaction ( string $ appname , string $ license = null ) : bool { if ( ! $ this -> isLoaded ( ) ) { return false ; } if ( isset ( $ license ) ) { return newrelic_start_transaction ( $ appname , $ license ) ; } return newrelic_start_transaction ( $ appname ) ; }

Starts a new transaction, usually after manually ending a transaction.

Agent version 3.0.5.95 or higher.

@see https://docs.newrelic.com/docs/agents/php-agent/php-agent-api/newrelic_start_transaction
@see self::endTransaction

@param string $appname The application name to associate with data from this transaction
@param string $license (optional) Provide a different license key if you want the transaction to report
to a different New Relic account

@return bool

Starts a new transaction usually after manually ending a transaction .


public function toUrl($url)
    {
        $allow_not_routed_url = $this->config['allow_not_routed_url'] ?? false;
        $exclude_urls         = $this->config['options']['exclude_urls'] ?? [];
        $exclude_hosts        = $this->config['options']['exclude_hosts'] ?? [];

        $uriTargetHost  = (new Uri($url))->getHost();
        if (true === $allow_not_routed_url ||
            \in_array($url, $exclude_urls) ||
            \in_array($uriTargetHost, $exclude_hosts)
        ) {
            return parent::toUrl($url);
        }

        $controller = $this->getController();

        $request = $controller->getRequest();
        $basePath = $request->getBasePath();

        $default_url = $this->config['default_url'] ?? '/';

        if ($basePath !== '') {
            if (\strpos($url, $basePath) !== 0) {
                $url = $basePath . $url;
            }

            if (\strpos($default_url, $basePath) !== 0) {
                $default_url  = $basePath . $default_url;
            }
        }

        $current_uri = $request->getRequestUri();
        $request->setUri($url);

        $uriTarget = (new Uri($url))->__toString();

        if ($current_uri === $uriTarget) {
            $this->getEventManager()->trigger('redirect-same-url');

            return;
        }

        $mvcEvent = $this->getEvent();
        $routeMatch = $mvcEvent->getRouteMatch();
        $currentRouteMatchName = $routeMatch->getMatchedRouteName();
        $router = $mvcEvent->getRouter();

        $uriCurrentHost = (new Uri($router->getRequestUri()))->getHost();
        if (($routeToBeMatched = $router->match($request))
            && (
                $uriTargetHost === null
                ||
                $uriCurrentHost === $uriTargetHost
            )

            && (
                (
                    ($routeToBeMatchedRouteName = $routeToBeMatched->getMatchedRouteName()) !== $currentRouteMatchName
                        && (
                            $this->manager->has($routeToBeMatched->getParam('controller'))
                            ||
                            $routeToBeMatched->getParam('middleware') !== false
                        )
                )
                ||
                (
                    $routeToBeMatched->getParam('action') != $routeMatch->getParam('action')
                )
                ||
                (
                    $routeToBeMatchedRouteName === $currentRouteMatchName
                )
            )

        ) {
            return parent::toUrl($url);
        }

        return parent::toUrl($default_url);
    }

public function toUrl ( $ url ) { $ allow_not_routed_url = $ this -> config [ 'allow_not_routed_url' ] ?? false ; $ exclude_urls = $ this -> config [ 'options' ] [ 'exclude_urls' ] ?? [ ] ; $ exclude_hosts = $ this -> config [ 'options' ] [ 'exclude_hosts' ] ?? [ ] ; $ uriTargetHost = ( new Uri ( $ url ) ) -> getHost ( ) ; if ( true === $ allow_not_routed_url || \ in_array ( $ url , $ exclude_urls ) || \ in_array ( $ uriTargetHost , $ exclude_hosts ) ) { return parent :: toUrl ( $ url ) ; } $ controller = $ this -> getController ( ) ; $ request = $ controller -> getRequest ( ) ; $ basePath = $ request -> getBasePath ( ) ; $ default_url = $ this -> config [ 'default_url' ] ?? '/' ; if ( $ basePath !== '' ) { if ( \ strpos ( $ url , $ basePath ) !== 0 ) { $ url = $ basePath . $ url ; } if ( \ strpos ( $ default_url , $ basePath ) !== 0 ) { $ default_url = $ basePath . $ default_url ; } } $ current_uri = $ request -> getRequestUri ( ) ; $ request -> setUri ( $ url ) ; $ uriTarget = ( new Uri ( $ url ) ) -> __toString ( ) ; if ( $ current_uri === $ uriTarget ) { $ this -> getEventManager ( ) -> trigger ( 'redirect-same-url' ) ; return ; } $ mvcEvent = $ this -> getEvent ( ) ; $ routeMatch = $ mvcEvent -> getRouteMatch ( ) ; $ currentRouteMatchName = $ routeMatch -> getMatchedRouteName ( ) ; $ router = $ mvcEvent -> getRouter ( ) ; $ uriCurrentHost = ( new Uri ( $ router -> getRequestUri ( ) ) ) -> getHost ( ) ; if ( ( $ routeToBeMatched = $ router -> match ( $ request ) ) && ( $ uriTargetHost === null || $ uriCurrentHost === $ uriTargetHost ) && ( ( ( $ routeToBeMatchedRouteName = $ routeToBeMatched -> getMatchedRouteName ( ) ) !== $ currentRouteMatchName && ( $ this -> manager -> has ( $ routeToBeMatched -> getParam ( 'controller' ) ) || $ routeToBeMatched -> getParam ( 'middleware' ) !== false ) ) || ( $ routeToBeMatched -> getParam ( 'action' ) != $ routeMatch -> getParam ( 'action' ) ) || ( $ routeToBeMatchedRouteName === $ currentRouteMatchName ) ) ) { return parent :: toUrl ( $ url ) ; } return parent :: toUrl ( $ default_url ) ; }

Redirect with Handling against url.

@param string $url

@return \Zend\Http\PhpEnvironment\Response


public static function prepareConstructorArgs(\ReflectionClass $reflectionClass, array $params)
    {

        // prepare the array for the initialized arguments
        $initializedParams = array();

        // prepare the array for the arguments in camel case (in configuration we use a '-' notation)
        $paramsInCamelCase = array();

        // convert the configuration keys to camelcase
        foreach ($params as $key => $value) {
            $paramsInCamelCase[lcfirst(str_replace('-', '', ucwords($key, '-')))] = $value;
        }

        // load the constructor's reflection parameters
        $constructorParameters = $reflectionClass->getConstructor()->getParameters();

        // prepare the arguments by applying the values from the configuration
        /** @var \ReflectionParameter $reflectionParameter */
        foreach ($constructorParameters as $reflectionParameter) {
            if (isset($paramsInCamelCase[$paramName = $reflectionParameter->getName()])) {
                $initializedParams[$paramName] = $paramsInCamelCase[$paramName];
            } elseif ($reflectionParameter->isOptional()) {
                $initializedParams[$paramName] = $reflectionParameter->getDefaultValue();
            } else {
                $initializedParams[$paramName] = null;
            }
        }

        // return the array with the prepared arguments
        return $initializedParams;
    }

Prepare's the arguments for the passed reflection class by applying the values from the passed configuration array
to the apropriate arguments. If no value is found in the configuration, the constructor argument's default value is
used.

@param \ReflectionClass $reflectionClass The reflection class to prepare the arguments for
@param array            $params          The constructor arguments from the configuration

@return array The array with the constructor arguements

Prepare s the arguments for the passed reflection class by applying the values from the passed configuration array to the apropriate arguments . If no value is found in the configuration the constructor argument s default value is used .


protected function appendExceptionSuffix($message = null, $filename = null, $lineNumber = null)
    {
        return $this->getSubject()-> appendExceptionSuffix($message, $filename, $lineNumber);
    }

protected function appendExceptionSuffix ( $ message = null , $ filename = null , $ lineNumber = null ) { return $ this -> getSubject ( ) -> appendExceptionSuffix ( $ message , $ filename , $ lineNumber ) ; }

Append's the exception suffix containing filename and line number to the
passed message. If no message has been passed, only the suffix will be
returned.

@param string|null $message    The message to append the exception suffix to
@param string|null $filename   The filename used to create the suffix
@param string|null $lineNumber The line number used to create the suffx

@return string The message with the appended exception suffix

Append s the exception suffix containing filename and line number to the passed message . If no message has been passed only the suffix will be returned .


protected function wrapException(
        $columnName,
        \Exception $parent = null,
        $className = '\TechDivision\Import\Exceptions\WrappedColumnException'
    ) {
        return $this->getSubject()->wrapException($columnName, $parent, $className);
    }

Wraps the passed exeception into a new one by trying to resolve the original filname,
line number and column name and use it for a detailed exception message.

@param string     $columnName The column name that should be resolved
@param \Exception $parent     The exception we want to wrap
@param string     $className  The class name of the exception type we want to wrap the parent one

@return \Exception the wrapped exception

Wraps the passed exeception into a new one by trying to resolve the original filname line number and column name and use it for a detailed exception message .


public function parse($filename, InterpreterInterface $interpreter)
    {

        // for mac's office excel csv
        ini_set('auto_detect_line_endings', true);

        // initialize the configuration
        $delimiter      = $this->config->getDelimiter();
        $enclosure      = $this->config->getEnclosure();
        $escape         = $this->config->getEscape();
        $fromCharset    = $this->config->getFromCharset();
        $toCharset      = $this->config->getToCharset();
        $flags          = $this->config->getFlags();
        $ignoreHeader   = $this->config->getIgnoreHeaderLine();

        // query whether or not the charset has to be converted
        if ($fromCharset === null) {
            $url = $filename;
        } else {
            $url = ConvertMbstringEncoding::getFilterURL($filename, $fromCharset, $toCharset);
        }

        // initialize the CSV file object
        $csv = new \SplFileObject($url);
        $csv->setCsvControl($delimiter, $enclosure, $escape);
        $csv->setFlags($flags);

        // backup current locale
        $originalLocale = setlocale(LC_ALL, '0');
        setlocale(LC_ALL, 'en_US.UTF-8');

        // process each line of the CSV file
        foreach ($csv as $lineNumber => $line) {
            if ($ignoreHeader && $lineNumber == 0 || (count($line) === 1 && trim($line[0]) === '')) {
                continue;
            }
            $interpreter->interpret($line);
        }

        // reset locale
        $localeArray = array();
        parse_str(str_replace(';', '&', $originalLocale), $localeArray);
        setlocale(LC_ALL, $localeArray);
    }

Parse the passed CSV file.

@param string                                           $filename    The filename to parse
@param \Goodby\CSV\Import\Protocol\InterpreterInterface $interpreter The interpreter instance

@return void


public function load($id)
    {

        // execute the prepared statement and return the EAV attribute group with the passed ID
        $this->eavAttributeGroupStmt->execute(array($id));
        return $this->eavAttributeGroupStmt->fetch(\PDO::FETCH_ASSOC);
    }

Return's the EAV attribute group with the passed ID.

@param integer $id The EAV attribute group ID

@return array The EAV attribute group

Return s the EAV attribute group with the passed ID .


public function findAllByAttributeSetId($attributeSetId)
    {

        // initialize the array for the EAV attribute sets
        $eavAttributeGroups = array();

        // load the attributes
        $this->eavAttributeGroupsByAttributeSetIdStmt->execute(array(MemberNames::ATTRIBUTE_SET_ID => $attributeSetId));

        // load the available EAV attribute option groups
        $availableEavAttributeGroups = $this->eavAttributeGroupsByAttributeSetIdStmt->fetchAll(\PDO::FETCH_ASSOC);

        // prepare the array with the attribute group names as keys
        foreach ($availableEavAttributeGroups as $eavAttributeGroup) {
            $eavAttributeGroups[$eavAttributeGroup[MemberNames::ATTRIBUTE_GROUP_NAME]] = $eavAttributeGroup;
        }

        // return the array with the EAV attribute groups
        return $eavAttributeGroups;
    }

Return's the attribute groups for the passed attribute set ID, whereas the array
is prepared with the attribute group names as keys.

@param mixed $attributeSetId The EAV attribute set ID to return the attribute groups for

@return array|boolean The EAV attribute groups for the passed attribute ID

Return s the attribute groups for the passed attribute set ID whereas the array is prepared with the attribute group names as keys .


public function findOneByEntityTypeCodeAndAttributeSetNameAndAttributeGroupName($entityTypeCode, $attributeSetName, $attributeGroupName)
    {

        // initialize the params
        $params = array(
            MemberNames::ENTITY_TYPE_CODE     => $entityTypeCode,
            MemberNames::ATTRIBUTE_SET_NAME   => $attributeSetName,
            MemberNames::ATTRIBUTE_GROUP_NAME => $attributeGroupName
        );

        // execute the prepared statement and return the EAV attribute group with the passed params
        $this->eavAttributeGroupByEntityTypeCodeAndAttributeSetNameAndAttributeGroupNameStmt->execute($params);
        return $this->eavAttributeGroupByEntityTypeCodeAndAttributeSetNameAndAttributeGroupNameStmt->fetch(\PDO::FETCH_ASSOC);
    }

Return's the EAV attribute group with the passed entity type code, attribute set and attribute group name.

@param string $entityTypeCode     The entity type code of the EAV attribute group to return
@param string $attributeSetName   The attribute set name of the EAV attribute group to return
@param string $attributeGroupName The attribute group name of the EAV attribute group to return

@return array The EAV attribute group

Return s the EAV attribute group with the passed entity type code attribute set and attribute group name .


public function createLexerConfig()
    {

        // initialize the lexer configuration
        $config = new LexerConfig();

        // query whether or not a delimiter character has been configured
        if ($delimiter = $this->configuration->getDelimiter()) {
            $config->setDelimiter($delimiter);
        }

        // query whether or not a custom escape character has been configured
        if ($escape = $this->configuration->getEscape()) {
            $config->setEscape($escape);
        }

        // query whether or not a custom enclosure character has been configured
        if ($enclosure = $this->configuration->getEnclosure()) {
            $config->setEnclosure($enclosure);
        }

        // query whether or not a custom source charset has been configured
        if ($fromCharset = $this->configuration->getFromCharset()) {
            $config->setFromCharset($fromCharset);
        }

        // query whether or not a custom target charset has been configured
        if ($toCharset = $this->configuration->getToCharset()) {
            $config->setToCharset($toCharset);
        }

        // return the lexer configuratio
        return $config;
    }

Factory method to create a new lexer configuration instance.

@return \Goodby\CSV\Import\Standard\LexerConfig The lexer configuration

Factory method to create a new lexer configuration instance .


public function findOneByOptionIdAndStoreId($optionId, $storeId)
    {

        // the parameters of the EAV attribute option to load
        $params = array(
            MemberNames::OPTION_ID => $optionId,
            MemberNames::STORE_ID  => $storeId,
        );

        // prepare the cache key
        $cacheKey = $this->cacheKey(SqlStatementKeys::EAV_ATTRIBUTE_OPTION_VALUE_BY_OPTION_ID_AND_STORE_ID, $params);

        // return the cached result if available
        if ($this->isCached($cacheKey)) {
            return $this->fromCache($cacheKey);
        }

        // load and return the EAV attribute option value with the passed parameters
        $this->eavAttributeOptionValueByOptionIdAndStoreIdStmt->execute($params);

        // query whether or not the EAV attribute option value is available in the database
        if ($eavAttributeOptionValue = $this->eavAttributeOptionValueByOptionIdAndStoreIdStmt->fetch(\PDO::FETCH_ASSOC)) {
            // add the EAV attribute option value to the cache, register the cache key reference as well
            $this->toCache(
                $eavAttributeOptionValue[MemberNames::VALUE_ID],
                $eavAttributeOptionValue,
                array($cacheKey => $eavAttributeOptionValue[MemberNames::VALUE_ID])
            );
            // finally, return it
            return $eavAttributeOptionValue;
        }
    }

Load's and return's the EAV attribute option value with the passed option ID and store ID

@param string  $optionId The option ID of the attribute option
@param integer $storeId  The store ID of the attribute option to load

@return array The EAV attribute option value

Load s and return s the EAV attribute option value with the passed option ID and store ID


public function createFileResolver(SubjectConfigurationInterface $subject)
    {

        // create a new file resolver instance for the subject with the passed configuration
        $fileResolver = $this->container->get($subject->getFileResolver()->getId());
        $fileResolver->setSubjectConfiguration($subject);

        // return the file resolver instance
        return $fileResolver;
    }

Creates and returns the file resolver instance for the subject with the passed configuration.

@param \TechDivision\Import\Configuration\SubjectConfigurationInterface $subject The subject to create the file resolver for

@return \TechDivision\Import\Subjects\FileResolver\FileResolverInterface The file resolver instance

Creates and returns the file resolver instance for the subject with the passed configuration .


public function findAll()
    {

        // prepare the core configuration data
        $coreConfigDatas = array();

        // execute the prepared statement
        $this->coreConfigDataStmt->execute();

        // load the available core config data
        $availableCoreConfigDatas = $this->coreConfigDataStmt->fetchAll(\PDO::FETCH_ASSOC);

        // create the array with the resolved category path as keys
        foreach ($availableCoreConfigDatas as $coreConfigData) {
            // prepare the unique identifier
            $uniqueIdentifier = $this->coreConfigDataUidGenerator->generate($coreConfigData);
            // append the config data value with the unique identifier
            $coreConfigDatas[$uniqueIdentifier] = $coreConfigData;
        }

        // return array with the configuration data
        return $coreConfigDatas;
    }

Return's an array with the Magento 2 configuration.

@return array The configuration

Return s an array with the Magento 2 configuration .


public function getSystemLogger($name = LoggerKeys::SYSTEM)
    {

        // query whether or not, the requested logger is available
        if (isset($this->systemLoggers[$name])) {
            return $this->systemLoggers[$name];
        }

        // throw an exception if the requested logger is NOT available
        throw new \Exception(sprintf('The requested logger \'%s\' is not available', $name));
    }

Return's the logger with the passed name, by default the system logger.

@param string $name The name of the requested system logger

@return \Psr\Log\LoggerInterface The logger instance
@throws \Exception Is thrown, if the requested logger is NOT available

Return s the logger with the passed name by default the system logger .


public function createPlugin(PluginConfigurationInterface $pluginConfiguration)
    {

        // load the plugin instance from the DI container and set the plugin configuration
        $pluginInstance = $this->container->get($pluginConfiguration->getId());
        $pluginInstance->setPluginConfiguration($pluginConfiguration);

        // return the plugin instance
        return $pluginInstance;
    }

Factory method to create new plugin instance.

@param \TechDivision\Import\Configuration\PluginConfigurationInterface $pluginConfiguration The plugin configuration

@return \TechDivision\Import\Plugins\PluginInterface The plugin instance

Factory method to create new plugin instance .


protected function mergeEntity(array $entity, array $attr)
    {
        return array_merge($entity, $attr, array(EntityStatus::MEMBER_NAME => EntityStatus::STATUS_UPDATE));
    }

protected function mergeEntity ( array $ entity , array $ attr ) { return array_merge ( $ entity , $ attr , array ( EntityStatus :: MEMBER_NAME => EntityStatus :: STATUS_UPDATE ) ) ; }

Merge's and return's the entity with the passed attributes and set's the
status to 'update'.

@param array $entity The entity to merge the attributes into
@param array $attr   The attributes to be merged

@return array The merged entity

Merge s and return s the entity with the passed attributes and set s the status to update .


public function createNumberConverter(SubjectConfigurationInterface $subject)
    {

        // create a new number converter instance for the subject with the passed configuration
        $numberConverter = $this->container->get($subject->getNumberConverter()->getId());
        $numberConverter->setSubjectConfiguration($subject);

        // return the number converter instance
        return $numberConverter;
    }

Creates and returns the number converter instance for the subject with the passed configuration.

@param \TechDivision\Import\Configuration\SubjectConfigurationInterface $subject The subject to create the number converter for

@return \TechDivision\Import\Subjects\I18n\NumberConverterInterface The number converter instance

Creates and returns the number converter instance for the subject with the passed configuration .


public function castValueByBackendType($backendType, $value)
    {

        // cast the value to a valid timestamp
        if ($backendType === BackendTypeKeys::BACKEND_TYPE_DATETIME) {
            return \DateTime::createFromFormat($this->getConfiguration()->getDateConverter()->getSourceDateFormat(), $value)->format('Y-m-d H:i:s');
        }

        // cast the value to a float value
        if ($backendType === BackendTypeKeys::BACKEND_TYPE_FLOAT) {
            return (float) $value;
        }

        // cast the value to an integer
        if ($backendType === BackendTypeKeys::BACKEND_TYPE_INT) {
            return (int) $value;
        }

        // we don't need to cast strings
        return $value;
    }

public
function
castValueByBackendType
(
$
backendType
,
$
value
)
{
// cast the value to a valid timestamp
if
(
$
backendType
===
BackendTypeKeys
::
BACKEND_TYPE_DATETIME
)
{
return
\
DateTime
::
createFromFormat
(
$
this
->
getConfiguration
(
)
->
getDateConverter
(
)
->
getSourceDateFormat
(
)
,
$
value
)
->
format
(
'Y-m-d H:i:s'
)
;
}
// cast the value to a float value
if
(
$
backendType
===
BackendTypeKeys
::
BACKEND_TYPE_FLOAT
)
{
return
(
float
)
$
value
;
}
// cast the value to an integer
if
(
$
backendType
===
BackendTypeKeys
::
BACKEND_TYPE_INT
)
{
return
(
int
)
$
value
;
}
// we don't need to cast strings
return
$
value
;
}

Cast's the passed value based on the backend type information.

@param string $backendType The backend type to cast to
@param mixed  $value       The value to be casted

@return mixed The casted value

Cast s the passed value based on the backend type information .


public function getEntityTypeCode()
    {

        // load the entity type code from the configuration
        $entityTypeCode = $this->getConfiguration()->getConfiguration()->getEntityTypeCode();

        // try to map the entity type code
        if (isset($this->entityTypeCodeToAttributeSetMappings[$entityTypeCode])) {
            $entityTypeCode = $this->entityTypeCodeToAttributeSetMappings[$entityTypeCode];
        }

        // return the (mapped) entity type code
        return $entityTypeCode;
    }

Return's the entity type code to be used.

@return string The entity type code to be used

Return s the entity type code to be used .


public function getAttributes()
    {

        // query whether or not, the requested EAV attributes are available
        if (isset($this->attributes[$entityTypeCode = $this->getEntityTypeCode()])) {
            // load the attributes for the entity type code
            $attributes = $this->attributes[$entityTypeCode];

            // query whether or not an attribute set has been loaded from the source file
            if (is_array($this->attributeSet) && isset($this->attributeSet[MemberNames::ATTRIBUTE_SET_NAME])) {
                // load the attribute set name
                $attributeSetName = $this->attributeSet[MemberNames::ATTRIBUTE_SET_NAME];

                // query whether or not attributes for the actual attribute set name
                if ($attributeSetName && isset($attributes[$attributeSetName])) {
                    return $attributes[$attributeSetName];
                }

                // throw an exception, if not
                throw new \Exception(
                    $this->appendExceptionSuffix(
                        sprintf('Found invalid attribute set name "%s"', $attributeSetName)
                    )
                );
            } else {
                return call_user_func_array('array_merge', $attributes);
            }
        }

        // throw an exception, if not
        throw new \Exception(
            $this->appendExceptionSuffix(
                sprintf('Found invalid entity type code "%s"', $entityTypeCode)
            )
        );
    }

Return's the attributes for the attribute set of the product that has to be created.

@return array The attributes
@throws \Exception Is thrown, if the attribute set or the given entity type with the passed name is not available

Return s the attributes for the attribute set of the product that has to be created .


public function getEavUserDefinedAttributes()
    {

        // initialize the array with the user defined EAV attributes
        $eavUserDefinedAttributes = array();

        // query whether or not user defined EAV attributes for the actualy entity type are available
        if (isset($this->userDefinedAttributes[$entityTypeCode = $this->getEntityTypeCode()])) {
            $eavUserDefinedAttributes = $this->userDefinedAttributes[$entityTypeCode];
        }

        // return the array with the user defined EAV attributes
        return $eavUserDefinedAttributes;
    }

Return's an array with the available user defined EAV attributes for the actual entity type.

@return array The array with the user defined EAV attributes

Return s an array with the available user defined EAV attributes for the actual entity type .


public function getEavAttributeByAttributeCode($attributeCode)
    {

        // load the attributes
        $attributes = $this->getAttributes();

        // query whether or not the attribute exists
        if (isset($attributes[$attributeCode])) {
            return $attributes[$attributeCode];
        }

        // throw an exception if the requested attribute is not available
        throw new \Exception(
            $this->appendExceptionSuffix(
                sprintf('Can\'t load attribute with code "%s"', $attributeCode)
            )
        );
    }

Return's the EAV attribute with the passed attribute code.

@param string $attributeCode The attribute code

@return array The array with the EAV attribute
@throws \Exception Is thrown if the attribute with the passed code is not available

Return s the EAV attribute with the passed attribute code .


public function getCategoriesWithResolvedPath()
    {

        // prepare the categories
        $categories = array();

        // load the categories from the database
        $availableCategories = $this->categoryRepository->findAll();

        // create the array with the resolved category path as keys
        foreach ($availableCategories as $category) {
            // expload the entity IDs from the category path
            $entityIds = explode('/', $category[MemberNames::PATH]);

            // cut-off the root category
            array_shift($entityIds);

            // continue with the next category if no entity IDs are available
            if (sizeof($entityIds) === 0) {
                continue;
            }

            // initialize the array for the path elements
            $path = array();
            foreach ($entityIds as $entityId) {
                $cat = $this->categoryVarcharRepository->findByEntityId($entityId);
                $path[] = $cat[MemberNames::VALUE];
            }

            // append the catogory with the string path as key
            $categories[implode('/', $path)] = $category;
        }

        // return array with the categories
        return $categories;
    }

Returns an array with the available categories and their
resolved path as keys.

@return array The array with the categories

Returns an array with the available categories and their resolved path as keys .


public function getCategoriesWithResolvedPathByStoreView($storeViewId)
    {
        // prepare the categories
        $categories = array();

        // load the categories from the database
        $availableCategories = $this->categoryRepository->findAllByStoreView($storeViewId);

        // create the array with the resolved category path as keys
        foreach ($availableCategories as $category) {
            // expload the entity IDs from the category path
            $entityIds = explode('/', $category[MemberNames::PATH]);

            // cut-off the root category
            array_shift($entityIds);

            // continue with the next category if no entity IDs are available
            if (sizeof($entityIds) === 0) {
                continue;
            }

            // initialize the array for the path elements
            $path = array();
            foreach ($entityIds as $entityId) {
                $cat = $this->categoryVarcharRepository->findByEntityId($entityId);
                $path[] = $cat[MemberNames::VALUE];
            }

            // append the catogory with the string path as key
            $categories[implode('/', $path)] = $category;
        }

        // return array with the categories
        return $categories;
    }

Return's an array with the available categories and their resolved path
as keys by store view ID.

@param integer $storeViewId The store view ID to return the categories for

@return array The available categories for the passed store view ID

Return s an array with the available categories and their resolved path as keys by store view ID .


public function getHeader($name)
    {

        // map column => attribute name
        $name = $this->mapAttributeCodeByHeaderMapping($name);

        // query whether or not, the header is available
        if (isset($this->headers[$name])) {
            return $this->headers[$name];
        }

        // throw an exception, if not
        throw new \InvalidArgumentException(sprintf('Header %s is not available', $name));
    }

Return's the header value for the passed name.

@param string $name The name of the header to return the value for

@return mixed The header value
@throws \InvalidArgumentException Is thrown, if the header with the passed name is NOT available

Return s the header value for the passed name .


public function addHeader($name)
    {

        // add the header
        $this->headers[$name] = $position = sizeof($this->headers);

        // return the new header's position
        return $position;
    }

public
function
addHeader
(
$
name
)
{
// add the header
$
this
->
headers
[
$
name
]
=
$
position
=
sizeof
(
$
this
->
headers
)
;
// return the new header's position
return
$
position
;
}

Add's the header with the passed name and position, if not NULL.

@param string $name The header name to add

@return integer The new headers position

Add s the header with the passed name and position if not NULL .


public function mapAttributeCodeByHeaderMapping($attributeCode)
    {

        // load the header mappings
        $headerMappings = $this->getHeaderMappings();

        // query weather or not we've a mapping, if yes, map the attribute code
        if (isset($headerMappings[$attributeCode])) {
            $attributeCode = $headerMappings[$attributeCode];
        }

        // return the (mapped) attribute code
        return $attributeCode;
    }

Map the passed attribute code, if a header mapping exists and return the
mapped mapping.

@param string $attributeCode The attribute code to map

@return string The mapped attribute code, or the original one

Map the passed attribute code if a header mapping exists and return the mapped mapping .


public function tearDown($serial)
    {

        // load the registry processor
        $registryProcessor = $this->getRegistryProcessor();

        // update the source directory for the next subject
        $registryProcessor->mergeAttributesRecursive(
            $serial,
            array(
                RegistryKeys::SOURCE_DIRECTORY => $newSourceDir = $this->getNewSourceDir($serial),
                RegistryKeys::FILES => array($this->getFilename() => array(RegistryKeys::STATUS => 1))
            )
        );

        // log a debug message with the new source directory
        $this->getSystemLogger()->debug(
            sprintf('Subject %s successfully updated source directory to %s', get_class($this), $newSourceDir)
        );
    }

Clean up the global data after importing the variants.

@param string $serial The serial of the actual import

@return void

Clean up the global data after importing the variants .


public function registerObserver(ObserverInterface $observer, $type)
    {

        // query whether or not the array with the callbacks for the
        // passed type has already been initialized, or not
        if (!isset($this->observers[$type])) {
            $this->observers[$type] = array();
        }

        // append the callback with the instance of the passed type
        $this->observers[$type][] = $observer;
    }

Register the passed observer with the specific type.

@param \TechDivision\Import\Observers\ObserverInterface $observer The observer to register
@param string                                           $type     The type to register the observer with

@return void

Register the passed observer with the specific type .


public function registerCallback(CallbackInterface $callback, $type)
    {

        // query whether or not the array with the callbacks for the
        // passed type has already been initialized, or not
        if (!isset($this->callbacks[$type])) {
            $this->callbacks[$type] = array();
        }

        // append the callback with the instance of the passed type
        $this->callbacks[$type][] = $callback;
    }

Register the passed callback with the specific type.

@param \TechDivision\Import\Callbacks\CallbackInterface $callback The subject to register the callbacks for
@param string                                           $type     The type to register the callback with

@return void

Register the passed callback with the specific type .


public function getCallbacksByType($type)
    {

        // initialize the array for the callbacks
        $callbacks = array();

        // query whether or not callbacks for the type are available
        if (isset($this->callbacks[$type])) {
            $callbacks = $this->callbacks[$type];
        }

        // return the array with the type's callbacks
        return $callbacks;
    }

Return's the array with callbacks for the passed type.

@param string $type The type of the callbacks to return

@return array The callbacks

Return s the array with callbacks for the passed type .


public function importRow(array $row)
    {

        // initialize the row
        $this->row = $row;

        // raise the line number and reset the skip row flag
        $this->lineNumber++;
        $this->skipRow = false;

        // invoke the events that has to be fired before the artfact's row will be processed
        $this->getEmitter()->emit(EventNames::SUBJECT_ARTEFACT_ROW_PROCESS_START, $this);

        // initialize the headers with the columns from the first line
        if (sizeof($this->headers) === 0) {
            foreach ($this->row as $value => $key) {
                $this->headers[$this->mapAttributeCodeByHeaderMapping($key)] = $value;
            }
            return;
        }

        // load the available observers
        $availableObservers = $this->getObservers();

        // process the observers
        foreach ($availableObservers as $observers) {
            // invoke the pre-import/import and post-import observers
            /** @var \TechDivision\Import\Observers\ObserverInterface $observer */
            foreach ($observers as $observer) {
                // query whether or not we have to skip the row
                if ($this->skipRow) {
                    // log a debug message with the actual line nr/file information
                    $this->getSystemLogger()->warning(
                        $this->appendExceptionSuffix(
                            sprintf(
                                'Skip processing operation "%s" after observer "%s"',
                                $this->operationName,
                                get_class($observer)
                            )
                        )
                    );

                    // skip the row
                    break 2;
                }

                // if not, set the subject and process the observer
                if ($observer instanceof ObserverInterface) {
                    $this->row = $observer->handle($this);
                }
            }
        }

        // query whether or not a minute has been passed
        if ($this->lastLog < time() - 60) {
            // log the number processed rows per minute
            $this->getSystemLogger()->info(
                sprintf(
                    'Successfully processed "%d (%d)" rows per minute of file "%s"',
                    $this->lineNumber - $this->lastLineNumber,
                    $this->lineNumber,
                    $this->getFilename()
                )
            );

            // reset the last log time and the line number
            $this->lastLog = time();
            $this->lastLineNumber = $this->lineNumber;
        }

        // log a debug message with the actual line nr/file information
        $this->getSystemLogger()->debug(
            $this->appendExceptionSuffix(
                sprintf(
                    'Successfully processed operation "%s"',
                    $this->operationName
                )
            )
        );

        // invoke the events that has to be fired when the artfact's row has been successfully processed
        $this->getEmitter()->emit(EventNames::SUBJECT_ARTEFACT_ROW_PROCESS_SUCCESS, $this);
    }

Imports the passed row into the database. If the import failed, the exception
will be catched and logged, but the import process will be continued.

@param array $row The row with the data to be imported

@return void

Imports the passed row into the database . If the import failed the exception will be catched and logged but the import process will be continued .


public function prepareStoreViewCode()
    {

        // re-set the store view code
        $this->setStoreViewCode(null);

        // initialize the store view code
        if ($storeViewCode = $this->getValue(ColumnKeys::STORE_VIEW_CODE)) {
            $this->setStoreViewCode($storeViewCode);
        }
    }

public
function
prepareStoreViewCode
(
)
{
// re-set the store view code
$
this
->
setStoreViewCode
(
)
;
// initialize the store view code
if
(
$
storeViewCode
=
$
this
->
getValue
(
ColumnKeys
::
STORE_VIEW_CODE
)
)
{
$
this
->
setStoreViewCode
(
$
storeViewCode
)
;
}
}

Prepare's the store view code in the subject. If the store_view_code row doesn't contain
any value, the default code of the default store view will be set.

@return void

Prepare s the store view code in the subject . If the store_view_code row doesn t contain any value the default code of the default store view will be set .


public function getStoreId($storeViewCode)
    {

        // query whether or not, the requested store is available
        if (isset($this->stores[$storeViewCode])) {
            return (integer) $this->stores[$storeViewCode][MemberNames::STORE_ID];
        }

        // throw an exception, if not
        throw new \Exception(
            sprintf(
                'Found invalid store view code %s in file %s on line %d',
                $storeViewCode,
                $this->getFilename(),
                $this->getLineNumber()
            )
        );
    }

Return's the store ID of the store with the passed store view code

@param string $storeViewCode The store view code to return the store ID for

@return integer The ID of the store with the passed ID
@throws \Exception Is thrown, if the store with the actual code is not available

Return s the store ID of the store with the passed store view code


public function getRootCategory()
    {

        // load the actual store view code
        $storeViewCode = $this->getStoreViewCode($this->getDefaultStoreViewCode());

        // query weather or not we've a root category or not
        if (isset($this->rootCategories[$storeViewCode])) {
            return $this->rootCategories[$storeViewCode];
        }

        // throw an exception if the root category is NOT available
        throw new \Exception(sprintf('Root category for %s is not available', $storeViewCode));
    }

Return's the root category for the actual view store.

@return array The store's root category
@throws \Exception Is thrown if the root category for the passed store code is NOT available

Return s the root category for the actual view store .


public function resolveOriginalColumnName($columnName)
    {

        // try to load the original data
        $originalData = $this->getOriginalData();

        // query whether or not original data is available
        if (isset($originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES])) {
            // query whether or not the original column name is available
            if (isset($originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES][$columnName])) {
                return $originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES][$columnName];
            }

            // query whether or a wildcard column name is available
            if (isset($originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES]['*'])) {
                return $originalData[ColumnKeys::ORIGINAL_COLUMN_NAMES]['*'];
            }
        }

        // return the original column name
        return $columnName;
    }

Resolve the original column name for the passed one.

@param string $columnName The column name that has to be resolved

@return string|null The original column name

Resolve the original column name for the passed one .


public function getOriginalData()
    {

        // initialize the array for the original data
        $originalData = array();

        // query whether or not the column contains original data
        if ($this->hasOriginalData()) {
            // unerialize the original data from the column
            $originalData = unserialize($this->row[$this->headers[ColumnKeys::ORIGINAL_DATA]]);
        }

        // return an empty array, if not
        return $originalData;
    }

Return's the original data if available, or an empty array.

@return array The original data

Return s the original data if available or an empty array .


public function hasOriginalData()
    {
        return isset($this->headers[ColumnKeys::ORIGINAL_DATA]) && isset($this->row[$this->headers[ColumnKeys::ORIGINAL_DATA]]);
    }

public function hasOriginalData ( ) { return isset ( $ this -> headers [ ColumnKeys :: ORIGINAL_DATA ] ) && isset ( $ this -> row [ $ this -> headers [ ColumnKeys :: ORIGINAL_DATA ] ] ) ; }

Query's whether or not the actual column contains original data like
filename, line number and column names.

@return boolean TRUE if the actual column contains origin data, else FALSE

Query s whether or not the actual column contains original data like filename line number and column names .


public function wrapException(
        array $columnNames = array(),
        \Exception $parent = null,
        $className = '\TechDivision\Import\Exceptions\WrappedColumnException'
    ) {

        // initialize the message
        $message = $parent->getMessage();

        // query whether or not has been a result of invalid data of a previous column of a CSV file
        if ($this->hasOriginalData()) {
            // load the original data
            $originalData = $this->getOriginalData();

            // replace old filename and line number of the original message
            $message = $this->appendExceptionSuffix(
                $this->stripExceptionSuffix($message),
                $originalData[ColumnKeys::ORIGINAL_FILENAME],
                $originalData[ColumnKeys::ORIGINAL_LINE_NUMBER]
            );
        } else {
            // append filename and line number to the original message
            $message = $this->appendExceptionSuffix(
                $this->stripExceptionSuffix($message),
                $this->filename,
                $this->lineNumber
            );
        }

        // query whether or not, column names has been passed
        if (sizeof($columnNames) > 0) {
            // prepare the original column names
            $originalColumnNames = array();
            foreach ($columnNames as $columnName) {
                $originalColumnNames[] = $this->resolveOriginalColumnName($columnName);
            }

            // append the column information
            $message = sprintf('%s in column(s) %s', $message, implode(', ', $originalColumnNames));
        }

        // create a new exception and wrap the parent one
        return new $className($message, null, $parent);
    }

Wraps the passed exeception into a new one by trying to resolve the original filname,
line number and column names and use it for a detailed exception message.

@param array      $columnNames The column names that should be resolved and wrapped
@param \Exception $parent      The exception we want to wrap
@param string     $className   The class name of the exception type we want to wrap the parent one

@return \Exception the wrapped exception

Wraps the passed exeception into a new one by trying to resolve the original filname line number and column names and use it for a detailed exception message .


public function appendExceptionSuffix($message = null, $filename = null, $lineNumber = null)
    {

        // query whether or not a filename has been passed
        if ($filename === null) {
            $filename = $this->getFilename();
        }

        // query whether or not a line number has been passed
        if ($lineNumber === null) {
            $lineNumber = $this->getLineNumber();
        }

        // if no message has been passed, only return the suffix
        if ($message === null) {
            return sprintf(' in file %s on line %d', $filename, $lineNumber);
        }

        // concatenate the message with the suffix and return it
        return sprintf('%s in file %s on line %d', $message, $filename, $lineNumber);
    }

Append's the exception suffix containing filename and line number to the
passed message. If no message has been passed, only the suffix will be
returned

@param string|null $message    The message to append the exception suffix to
@param string|null $filename   The filename used to create the suffix
@param string|null $lineNumber The line number used to create the suffx

@return string The message with the appended exception suffix

Append s the exception suffix containing filename and line number to the passed message . If no message has been passed only the suffix will be returned


public function getNewFileName($targetFilename)
    {

        // load the file information
        $fileInfo = pathinfo($targetFilename);

        // query whether or not, the file exists
        if ($this->getFilesystemAdapter()->isFile($targetFilename)) {
            // initialize the incex and the basename
            $index = 1;
            $baseName = $fileInfo['filename'] . '.' . $fileInfo['extension'];

            // prepare the new filename by raising the index
            while ($this->getFilesystemAdapter()->isFile($fileInfo['dirname'] . '/' . $baseName)) {
                $baseName = $fileInfo['filename'] . '_' . $index . '.' . $fileInfo['extension'];
                $index++;
            }

            // set the new filename
            $targetFilename = $baseName;
        } else {
            // if not, simply return the filename
            return $fileInfo['basename'];
        }

        // return the new filename
        return $targetFilename;
    }

Get new file name if the same is already exists.

@param string $targetFilename The name of the exisising files

@return string The new filename

Get new file name if the same is already exists .


public function uploadFile($filename)
    {

        // trim the leading /, if available
        $trimmedFilename = ltrim($filename, '/');
        $mediaDir = ltrim($this->getMediaDir(), '/');
        $imagesFileDir = ltrim($this->getImagesFileDir(), '/');

        // prepare source/target filename
        $sourceFilename = sprintf('%s/%s', $imagesFileDir, $trimmedFilename);
        $targetFilename = sprintf('%s/%s', $mediaDir, $trimmedFilename);

        // query whether or not the image file to be imported is available
        if (!$this->getFilesystemAdapter()->isFile($sourceFilename)) {
            throw new \Exception(sprintf('Media file %s not available', $sourceFilename));
        }

        // prepare the target filename, if necessary
        $newTargetFilename = $this->getNewFileName($targetFilename);
        $targetFilename = str_replace(basename($targetFilename), $newTargetFilename, $targetFilename);

        // make sure, the target directory exists
        if (!$this->getFilesystemAdapter()->isDir($targetDirectory = dirname($targetFilename))) {
            $this->getFilesystemAdapter()->mkdir($targetDirectory, 0755);
        }

        // copy the image to the target directory
        $this->getFilesystemAdapter()->copy($sourceFilename, $targetFilename);

        // return the new target filename
        return str_replace($mediaDir, '', $targetFilename);
    }

Upload's the file with the passed name to the Magento
media directory. If the file already exists, the will
be given a new name that will be returned.

@param string $filename The name of the file to be uploaded

@return string The name of the uploaded file
@throws \Exception Is thrown, if the file with the passed name is not available

Upload s the file with the passed name to the Magento media directory . If the file already exists the will be given a new name that will be returned .


public function deleteFile($filename)
    {

        // trim the leading /, if available
        $trimmedFilename = ltrim($filename, '/');
        $mediaDir = ltrim($this->getMediaDir(), '/');

        // prepare source/target filename
        $targetFilename = sprintf('%s/%s', $mediaDir, $trimmedFilename);

        // query whether or not the image file to be deleted is available
        if (!$this->getFilesystemAdapter()->isFile($targetFilename)) {
            throw new \Exception(sprintf('Media file %s not available', $targetFilename));
        }

        // delte the image from the target directory
        $this->getFilesystemAdapter()->delete($targetFilename);
    }

Delete the file with the passed name.

@param string $filename The name of the file to be deleted

@return boolean TRUE on success, else FALSE


public function findAll()
    {

        // initialize the array for the EAV entity types
        $eavEntityTypes = array();

        // try to load the EAV entity types
        $this->eavEntityTypeStmt->execute();

        // load the available EAV entity types
        $availableEntityTypes = $this->eavEntityTypeStmt->fetchAll(\PDO::FETCH_ASSOC);

        // prepare the EAV entity types => we need the entity type code as key
        foreach ($availableEntityTypes as $eavEntityType) {
            $eavEntityTypes[$eavEntityType[MemberNames::ENTITY_TYPE_CODE]] = $eavEntityType;
        }

        // return the array with the EAV entity types
        return $eavEntityTypes;
    }

Return's an array with all available EAV entity types with the entity type code as key.

@return array The available link types

Return s an array with all available EAV entity types with the entity type code as key .


public function findOneByEntityTypeCode($entityTypeCode)
    {
        // load and return the EAV attribute with the passed params
        $this->eavEntityTypeByEntityTypeACodeStmt->execute(array(MemberNames::ENTITY_TYPE_CODE => $entityTypeCode));
        return $this->eavEntityTypeByEntityTypeACodeStmt->fetch(\PDO::FETCH_ASSOC);
    }

Return's an EAV entity type with the passed entity type code.

@param string $entityTypeCode The code of the entity type to return

@return array The entity type with the passed entity type code

Return s an EAV entity type with the passed entity type code .


public function serialize(array $unserialized = null)
    {

        // do nothing, if the passed value is empty or NULL
        if ($unserialized === null || $unserialized === '') {
            return;
        }

        // load the global configuration
        $configuration = $this->getConfiguration();

        // initializet delimiter, enclosure and escape char
        $delimiter = $this->getDelimiter() ? $this->getDelimiter() : $configuration->getDelimiter();
        $enclosure = $configuration->getEnclosure();
        $escape = $configuration->getEscape();

        // create hte callback method to enclose/escape the values
        $callback = function ($value) use ($enclosure, $escape) {
            return $enclosure . str_replace($escape, $escape . $escape, $value) . $enclosure;
        };

        // implode and return the enclosed/escaped values
        return implode($delimiter, array_map($callback, $unserialized));
    }

Serializes the elements of the passed array by using the
instances CSV configuration options.

@param array|null $unserialized The serialized data

@return string|null The serialized array

Serializes the elements of the passed array by using the instances CSV configuration options .


public function unserialize($serialized = null)
    {

        // do nothing, if the passed value is empty or NULL
        if ($serialized === null || $serialized === '') {
            return;
        }

        // load the global configuration
        $configuration = $this->getConfiguration();

        // initializet delimiter, enclosure and escape char
        $delimiter = $this->getDelimiter() ? $this->getDelimiter() : $configuration->getDelimiter();
        $enclosure = $configuration->getEnclosure();
        $escape = $configuration->getEscape();

        // parse and return the found data as array
        return str_getcsv($serialized, $delimiter, $enclosure, $escape);
    }

Unserializes the elements of the passed value by using the
instances CSV configuration options.

@param string|null $serialized The value to unserialize

@return array|null The exploded values

Unserializes the elements of the passed value by using the instances CSV configuration options .


protected function getTargetDir()
    {

        // load the actual status
        $status = $this->getRegistryProcessor()->getAttribute($this->getSerial());

        // query whether or not the configured source directory is available
        if (!is_dir($sourceDir = $status[RegistryKeys::SOURCE_DIRECTORY])) {
            throw new \Exception(sprintf('Configured source directory %s is not available!', $sourceDir));
        }

        // return the source directory where we want to export to
        return $sourceDir;
    }

Return's the target directory the CSV files has to be exported to.

@return string The name of the target directory

Return s the target directory the CSV files has to be exported to .


public function createExportConfig()
    {

        // initialize the lexer configuration
        $config = new ExporterConfig();

        // query whether or not a delimiter character has been configured
        if ($delimiter = $this->configuration->getDelimiter()) {
            $config->setDelimiter($delimiter);
        }

        // query whether or not a custom escape character has been configured
        if ($escape = $this->configuration->getEscape()) {
            $config->setEscape($escape);
        }

        // query whether or not a custom enclosure character has been configured
        if ($enclosure = $this->configuration->getEnclosure()) {
            $config->setEnclosure($enclosure);
        }

        // query whether or not a custom source charset has been configured
        if ($fromCharset = $this->configuration->getFromCharset()) {
            $config->setFromCharset($fromCharset);
        }

        // query whether or not a custom target charset has been configured
        if ($toCharset = $this->configuration->getToCharset()) {
            $config->setToCharset($toCharset);
        }

        // query whether or not a custom file mode has been configured
        if ($fileMode = $this->configuration->getFileMode()) {
            $config->setFileMode($fileMode);
        }

        // return the lexer configuration
        return $config;
    }

Factory method to create a new export configuration instance.

@return \Goodby\CSV\Export\Standard\ExporterConfig The export configuration

Factory method to create a new export configuration instance .


public function init(CsvConfigurationInterface $configuration)
    {

        // pass the configuration to the parent instance
        parent::init($configuration);

        // create the CSV value serializer instance
        $this->setValueCsvSerializer($this->getValueCsvSerializerFactory()->createSerializer($configuration));
    }

Passes the configuration and initializes the serializer.

@param \TechDivision\Import\Configuration\CsvConfigurationInterface $configuration The CSV configuration

@return void

Passes the configuration and initializes the serializer .


public function unserialize($serialized = null)
    {

        // initialize the array for the unserialized additional attributes
        $attributes = array();

        // explode the additional attributes
        if ($additionalAttributes = $this->explode($serialized)) {
            // iterate over the attributes and append them to the row
            foreach ($additionalAttributes as $additionalAttribute) {
                // explode attribute code/option value from the attribute
                list ($attributeCode, $optionValue) = explode('=', $additionalAttribute);

                // extract the key/value pairs into an array
                $attributes[$attributeCode] = $optionValue;
            }
        }

        // return the array with the unserialized additional attributes
        return $attributes;
    }

Unserializes the elements of the passed string.

@param string|null $serialized The value to unserialize

@return array The unserialized values
@see \TechDivision\Import\Serializers\SerializerInterface::unserialize()

Unserializes the elements of the passed string .


public function serialize(array $unserialized = null)
    {

        // initialize the array
        $attributes = array();

        if (is_array($unserialized)) {
            // serialize the key/value pairs into the array
            foreach ($unserialized as $attributeCode => $attributeValue) {
                $attributes[] = implode('=', array($attributeCode, $attributeValue));
            }
        }

        // serialize the array itself
        return $this->implode($attributes);
    }

Serializes the elements of the passed array.

@param array|null $unserialized The serialized data

@return string The serialized array
@see \TechDivision\Import\Serializers\SerializerInterface::serialize()

Serializes the elements of the passed array .


protected function getPreparedStatement($name = null)
    {

        // try to load the prepared statement, or use the default one
        if (isset($this->preparedStatements[$name])) {
            return $this->preparedStatements[$name];
        }

        // return the first (default) prepared statement
        return reset($this->preparedStatements);
    }

Return's the prepared statement.

@param string $name The name of the prepared statement to return

@return \PDOStatement The prepared statement


public function init()
    {

        // load the statements
        $statements = $this->getStatements();

        foreach ($statements as $name => $statement) {
            $this->addPreparedStatement($name, $this->getConnection()->prepare($statement));
        }
    }

public
function
init
(
)
{
// load the statements
$
statements
=
$
this
->
getStatements
(
)
;
foreach
(
$
statements
as
$
name
=>
$
statement
)
{
$
this
->
addPreparedStatement
(
$
name
,
$
this
->
getConnection
(
)
->
prepare
(
$
statement
)
)
;
}
}

Initializes the proceessor with the prepared statements.

@return void

Initializes the proceessor with the prepared statements .


protected function parseAdditionaAttributes($additionalAttributes)
    {

        // load the global configuration
        $configuration = $this->getSubject()->getConfiguration()->getConfiguration();

        // initializet delimiter, enclosure and escape char
        $delimiter = $configuration->getDelimiter();
        $enclosure = $configuration->getEnclosure();
        $escape = $configuration->getEscape();

        // parse and return the found data as array
        return str_getcsv($additionalAttributes, $delimiter, $enclosure, $escape);
    }

Parses the string with the additional attributes as CSV and returns an array.

@param string $additionalAttributes The string with the additional attributes

@return array The array with the parsed
@link http://php.net/manual/de/function.str-getcsv.php

Parses the string with the additional attributes as CSV and returns an array .


public function generate(array $entity)
    {

        // load the data to generate the entity with
        $path = $entity[MemberNames::PATH];
        $scope = $entity[MemberNames::SCOPE];
        $scopeId = $entity[MemberNames::SCOPE_ID];

        // generate and return the entity
        return sprintf('%s/%s/%s', $scope, $scopeId, $path);
    }

Create a unique identifier for the passed 'core_config_data' entity.

@param array $entity The entity to generate the UID for

@return string The unique identifier
@see \TechDivision\Import\Utils\Generators\GeneratorInterface::generate()

Create a unique identifier for the passed core_config_data entity .


protected function resolveReference($from)
    {

        // query whether or not a reference exists
        if (isset($this->references[$from])) {
            return $this->references[$from];
        }

        // return the passed reference
        return $from;
    }

Resolve's the cache key.

@param string $from The cache key to resolve

@return string The resolved reference


public function toCache($cacheKey, $value, array $references = array())
    {

        // add the value to the cache
        $this->cache[$cacheKey] = $value;

        // also register the references if given
        foreach ($references as $from => $to) {
            $this->references[$from] = $to;
        }
    }

Add the passed value to the cache.

@param string $cacheKey   The cache key
@param mixed  $value      The value to cache
@param array  $references An array with references to add

@return void


public function fromCache($cacheKey)
    {

        // query whether or not a value for the cache key is available
        if (isset($this->cache[$resolvedCacheKey = $this->resolveReference($cacheKey)])) {
            return $this->cache[$resolvedCacheKey];
        }

        // throw an exception if not
        throw new \Exception(sprintf('Can\'t find cached value for key "%s"', $cacheKey));
    }

Query whether or not a value for the passed cache key exists. If yes, the value
will be returned, else an exception will be thrown.

@param string $cacheKey The cache key to return the value for

@return mixed The value for the passed cache key
@throws \Exception Is thrown, if no value is available

Query whether or not a value for the passed cache key exists . If yes the value will be returned else an exception will be thrown .


public function flushCache($cacheKey = null)
    {

        // flush the complete cache, if NO cache key has been passed
        if ($cacheKey === null) {
            $this->references = $this->cache = array();
            return;
        }

        // only flush the value with the passed cache key
        if (isset($this->cache[$resolvedCacheKey = $this->resolveReference($cacheKey)])) {
            unset($this->cache[$resolvedCacheKey]);
        }
    }

Flush the cache, or the value with the passed key.

@param mixed|null $cacheKey The key of the value to flush

@return void

Flush the cache or the value with the passed key .


public function load($id)
    {

        // execute the prepared statement and return the EAV attribute set with the passed ID
        $this->eavAttributeSetStmt->execute(array($id));
        return $this->eavAttributeSetStmt->fetch(\PDO::FETCH_ASSOC);
    }

Return's the EAV attribute set with the passed ID.

@param integer $id The EAV attribute set ID

@return array The attribute set

Return s the EAV attribute set with the passed ID .


public function findAllByEntityTypeId($entityTypeId)
    {

        // initialize the array for the attribute sets
        $eavAttributeSets = array();

        // load the attributes
        $this->eavAttributeSetsByEntityTypeIdStmt->execute(array($entityTypeId));

        // load the available EAV attribute sets
        $availableEavAttributeSets = $this->eavAttributeSetsByEntityTypeIdStmt->fetchAll(\PDO::FETCH_ASSOC);

        // prepare the array with the attribute set names as keys
        foreach ($availableEavAttributeSets as $eavAttributeSet) {
            $eavAttributeSets[$eavAttributeSet[MemberNames::ATTRIBUTE_SET_NAME]] = $eavAttributeSet;
        }

        // return the array with the attribute sets
        return $eavAttributeSets;
    }

Return's the attribute sets for the passed entity type ID, whereas the array
is prepared with the attribute set names as keys.

@param mixed $entityTypeId The entity type ID to return the attribute sets for

@return array|boolean The attribute sets for the passed entity type ID

Return s the attribute sets for the passed entity type ID whereas the array is prepared with the attribute set names as keys .


public function findOneByEntityTypeIdAndAttributeSetName($entityTypeId, $attributeSetName)
    {

        // initialize the params
        $params = array(
            MemberNames::ENTITY_TYPE_ID     => $entityTypeId,
            MemberNames::ATTRIBUTE_SET_NAME => $attributeSetName
        );

        // load and return the attribute set
        $this->eavAttributeSetByEntityTypeIdAndAttributeSetNameStmt->execute($params);
        return $this->eavAttributeSetByEntityTypeIdAndAttributeSetNameStmt->fetch(\PDO::FETCH_ASSOC);
    }

Load's and return's the EAV attribute set with the passed entity type ID and attribute set name.

@param string $entityTypeId     The entity type ID of the EAV attribute set to load
@param string $attributeSetName The attribute set name of the EAV attribute set to return

@return array The EAV attribute set

Load s and return s the EAV attribute set with the passed entity type ID and attribute set name .


public function findOneByEntityTypeCodeAndAttributeSetName($entityTypeCode, $attributeSetName)
    {

        // initialize the params
        $params = array(
            MemberNames::ENTITY_TYPE_CODE   => $entityTypeCode,
            MemberNames::ATTRIBUTE_SET_NAME => $attributeSetName
        );

        // load and return the attribute set
        $this->eavAttributeSetByEntityTypeCodeAndAttributeSetNameStmt->execute($params);
        return $this->eavAttributeSetByEntityTypeCodeAndAttributeSetNameStmt->fetch(\PDO::FETCH_ASSOC);
    }

Load's and return's the EAV attribute set with the passed entity type code and attribute set name.

@param string $entityTypeCode   The entity type code of the EAV attribute set to load
@param string $attributeSetName The attribute set name of the EAV attribute set to return

@return array The EAV attribute set

Load s and return s the EAV attribute set with the passed entity type code and attribute set name .


public function createExportAdapter(SubjectConfigurationInterface $subjectConfiguration)
    {

        // load the export adapter configuration
        $exportAdapterConfiguration = $subjectConfiguration->getExportAdapter();

        // load the serializer factory instance
        $serializerFactory = $this->container->get($exportAdapterConfiguration->getSerializer()->getId());

        // create the instance and pass the export adapter configuration instance
        $exportAdapter = $this->container->get(DependencyInjectionKeys::IMPORT_ADAPTER_EXPORT_CSV);
        $exportAdapter->init($exportAdapterConfiguration, $serializerFactory);

        // return the initialized export adapter instance
        return $exportAdapter;
    }

Creates and returns the export adapter for the subject with the passed configuration.

@param \TechDivision\Import\Configuration\SubjectConfigurationInterface $subjectConfiguration The subject configuration

@return \TechDivision\Import\Adapter\ExportAdapterInterface The export adapter instance

Creates and returns the export adapter for the subject with the passed configuration .


public function quote($string, $parameterType = \PDO::PARAM_STR)
    {
        return $this->connection->quote($string, $parameterType);
    }

public function quote ( $ string , $ parameterType = \ PDO :: PARAM_STR ) { return $ this -> connection -> quote ( $ string , $ parameterType ) ; }

Quotes a string for use in a query.

@param string  $string        The string to be quoted
@param integer $parameterType Provides a data type hint for drivers that have alternate quoting styles

@return string|boolean Returns a quoted string that is theoretically safe to pass into an SQL statement or FALSE if the driver does not support quoting in this way
@link http://php.net/manual/en/pdo.quote.php


public function findAllByEntityTypeAndEntityId($entityType, $entityId)
    {

        // initialize the params
        $params = array(
            MemberNames::ENTITY_TYPE => $entityType,
            MemberNames::ENTITY_ID   => $entityId
        );

        // load and return the URL rewrites
        $this->urlRewritesByEntityTypeAndEntityIdStmt->execute($params);
        return $this->urlRewritesByEntityTypeAndEntityIdStmt->fetchAll(\PDO::FETCH_ASSOC);
    }

public
function
findAllByEntityTypeAndEntityId
(
$
entityType
,
$
entityId
)
{
// initialize the params
$
params
=
array
(
MemberNames
::
ENTITY_TYPE
=>
$
entityType
,
MemberNames
::
ENTITY_ID
=>
$
entityId
)
;
// load and return the URL rewrites
$
this
->
urlRewritesByEntityTypeAndEntityIdStmt
->
execute
(
$
params
)
;
return
$
this
->
urlRewritesByEntityTypeAndEntityIdStmt
->
fetchAll
(
\
PDO
::
FETCH_ASSOC
)
;
}

Return's an array with the URL rewrites for the passed entity type and ID.

@param string  $entityType The entity type to load the URL rewrites for
@param integer $entityId   The entity ID to load the URL rewrites for

@return array The URL rewrites

Return s an array with the URL rewrites for the passed entity type and ID .


public function findAllByEntityTypeAndEntityIdAndStoreId($entityType, $entityId, $storeId)
    {

        // initialize the params
        $params = array(
            MemberNames::ENTITY_TYPE => $entityType,
            MemberNames::ENTITY_ID   => $entityId,
            MemberNames::STORE_ID    => $storeId
        );

        // load and return the URL rewrites
        $this->urlRewritesByEntityTypeAndEntityIdAndStoreIdStmt->execute($params);
        return $this->urlRewritesByEntityTypeAndEntityIdAndStoreIdStmt->fetchAll(\PDO::FETCH_ASSOC);
    }

Return's an array with the URL rewrites for the passed entity type, entity and store ID.

@param string  $entityType The entity type to load the URL rewrites for
@param integer $entityId   The entity ID to load the URL rewrites for
@param integer $storeId    The store ID to load the URL rewrites for

@return array The URL rewrites

Return s an array with the URL rewrites for the passed entity type entity and store ID .


private function notify(array $row)
    {

        // make the observers local
        $observers = $this->observers;

        // invoke the observers on the passed line
        foreach ($observers as $observer) {
            $this->delegate($observer, $row);
        }
    }

Notify the observers.

@param array $row The row that has to be processed

@return void


private function checkRowConsistency(array $row)
    {

        // query whether or not strict mode is enabled
        if ($this->isNotStrict()) {
            return;
        }

        // count the number of columns
        $current = count($row);

        // if the row consistency has not been set, set it
        if ($this->rowConsistency === null) {
            $this->rowConsistency = $current;
        }

        // check row consistency
        if ($current !== $this->rowConsistency) {
            throw new StrictViolationException(sprintf('Column size should be %u, but %u columns given', $this->rowConsistency, $current));
        }

        // set the new row consistency
        $this->rowConsistency = $current;
    }

Check if the column count is consistent with comparing other rows.

@param array $row The row that has to be processed

@return void
@throws \Goodby\CSV\Export\Standard\Exception\StrictViolationException Is thrown, if row consistency check fails

Check if the column count is consistent with comparing other rows .


public function hasValue($name)
    {

        // query whether or not the header is available
        if ($this->hasHeader($name)) {
            // load the key for the row
            $headerValue = $this->getHeader($name);

            // query whether the rows column has a vaild value
            return (isset($this->row[$headerValue]) && $this->row[$headerValue] !== '');
        }

        // return FALSE if not
        return false;
    }

Query whether or not a value for the column with the passed name exists.

@param string $name The column name to query for a valid value

@return boolean TRUE if the value is set, else FALSE

Query whether or not a value for the column with the passed name exists .