public function maybeUnserialize($value)
    {
        if ($value && $this->isSerialized($value)) {
            if (mb_strpos($value, $this::CLOSURE) === 0) {
                return $this->unserializeClosure($value);
            } else {
                return unserialize($value);
            }
        } else {
            return $value; // Not applicable.
        }
    }

public
function
maybeUnserialize
(
$
value
)
{
if
(
$
value
&&
$
this
->
isSerialized
(
$
value
)
)
{
if
(
mb_strpos
(
$
value
,
$
this
::
CLOSURE
)
===
0
)
{
return
$
this
->
unserializeClosure
(
$
value
)
;
}
else
{
return
unserialize
(
$
value
)
;
}
}
else
{
return
$
value
;
// Not applicable.
}
}

Maybe unserialize value.

@since 150424 Serializer.

@param mixed $value Value.

@return mixed The unserialized value.


protected function embedlyMarkup(string $url, \StdClass $embed): string
    {
        $markup = ''; // Initialize HTML markup.

        if (!$url || empty($embed->type) || empty($embed->provider_name)) {
            return $markup; // Not possible; i.e., empty string.
        }
        $provider_slug = $this->c::nameToSlug($embed->provider_name);
        $classes       = '_-embedly _-'.$embed->type.' _-'.$provider_slug;

        switch ($embed->type) { // See: <http://jas.xyz/1O7ymwT>
            case 'rich':
            case 'video':
                if (!empty($embed->html)) {
                    $markup = '
c::escAttr($classes).'">'.
                        $embed->html.
                    '
';
                }
                break;

            case 'photo':
                if (!empty($embed->url) && isset($embed->width, $embed->height)) {
                    $markup = '
c::escAttr($classes).'">'.
                        'c::escUrl($url).'" title="'.$this->c::escAttr($embed->title ?? '').'">'.
                            'c::escUrl($embed->url).'" width="'.$this->c::escAttr((string) $embed->width).'" height="'.$this->c::escAttr((string) $embed->height).'" alt="" />'.
                        ''.
                    '
';
                }
                break;

            case 'link':
                if (!empty($embed->thumbnail_url) && isset($embed->thumbnail_width, $embed->thumbnail_height)) {
                    $markup = '
c::escAttr($classes).'">'.
                        'c::escUrl($url).'" title="'.$this->c::escAttr($embed->title ?? '').'">'.
                            'c::escUrl($embed->thumbnail_url).'" width="'.$this->c::escAttr((string) $embed->thumbnail_width).'" height="'.$this->c::escAttr((string) $embed->thumbnail_height).'" alt="" />'.
                        ''.
                    '
';
                }
                break;
        }
        return $markup;
    }

protected
function
embedlyMarkup
(
string
$
url
,
\
StdClass
$
embed
)
:
string
{
$
markup
=
''
;
// Initialize HTML markup.
if
(
!
$
url
||
empty
(
$
embed
->
type
)
||
empty
(
$
embed
->
provider_name
)
)
{
return
$
markup
;
// Not possible; i.e., empty string.
}
$
provider_slug
=
$
this
->
c
::
nameToSlug
(
$
embed
->
provider_name
)
;
$
classes
=
'_-embedly _-'
.
$
embed
->
type
.
' _-'
.
$
provider_slug
;
switch
(
$
embed
->
type
)
{
// See: <http://jas.xyz/1O7ymwT>
case
'rich'
:
case
'video'
:
if
(
!
empty
(
$
embed
->
html
)
)
{
$
markup
=
'

c
::
escAttr
(
$
classes
)
.
'">'
.
$
embed
->
html
.
'
'
;
}
break
;
case
'photo'
:
if
(
!
empty
(
$
embed
->
url
)
&&
isset
(
$
embed
->
width
,
$
embed
->
height
)
)
{
$
markup
=
'

c
::
escAttr
(
$
classes
)
.
'">'
.
'
c
::
escUrl
(
$
url
)
.
'" title="'
.
$
this
->
c
::
escAttr
(
$
embed
->
title
??
''
)
.
'">'
.
'
c
::
escUrl
(
$
embed
->
url
)
.
'" width="'
.
$
this
->
c
::
escAttr
(
(
string
)
$
embed
->
width
)
.
'" height="'
.
$
this
->
c
::
escAttr
(
(
string
)
$
embed
->
height
)
.
'" alt="" />'
.
''
.
'
'
;
}
break
;
case
'link'
:
if
(
!
empty
(
$
embed
->
thumbnail_url
)
&&
isset
(
$
embed
->
thumbnail_width
,
$
embed
->
thumbnail_height
)
)
{
$
markup
=
'

c
::
escAttr
(
$
classes
)
.
'">'
.
'
c
::
escUrl
(
$
url
)
.
'" title="'
.
$
this
->
c
::
escAttr
(
$
embed
->
title
??
''
)
.
'">'
.
'
c
::
escUrl
(
$
embed
->
thumbnail_url
)
.
'" width="'
.
$
this
->
c
::
escAttr
(
(
string
)
$
embed
->
thumbnail_width
)
.
'" height="'
.
$
this
->
c
::
escAttr
(
(
string
)
$
embed
->
thumbnail_height
)
.
'" alt="" />'
.
''
.
'
'
;
}
break
;
}
return
$
markup
;
}

Get Embedly markup.

@since 151125 OEmbed utilities.

@param string    $url   URL the embed is for.
@param \StdClass $embed The embed response object.

@return string The Embedly HTML markup.


protected function getEmbedlyCache(string $url)
    {
        $cache_dir = $this->cache_dir.'/embedly';
        $cache_dir .= '/'.$this->c::sha1ModShardId($url);
        $cache_file = $cache_dir.'/'.sha1($url);

        if (is_file($cache_file)) {
            $embed = file_get_contents($cache_file);
            $embed = unserialize($embed);
            if ($embed instanceof \StdClass) {
                return $embed;
            }
        }
    }

protected function getEmbedlyCache ( string $ url ) { $ cache_dir = $ this -> cache_dir . '/embedly' ; $ cache_dir .= '/' . $ this -> c :: sha1ModShardId ( $ url ) ; $ cache_file = $ cache_dir . '/' . sha1 ( $ url ) ; if ( is_file ( $ cache_file ) ) { $ embed = file_get_contents ( $ cache_file ) ; $ embed = unserialize ( $ embed ) ; if ( $ embed instanceof \ StdClass ) { return $ embed ; } } }

Get Embedly cache.

@since 151125 OEmbed utilities.

@param string $url URL to check the cache for.

@return \StdClass|null Cached embed code, if possible.


protected function viaWordPress(string $string): string
    {
        if (!$this->c::isWordPress()
            || !$this->c::canCallFunc('wp_oembed_get')
            || !$this->c::canCallFunc('wp_embed_defaults')) {
            throw $this->c::issue('Unable to oEmbed via WordPress.');
        }
        $oembed_args = array_merge(wp_embed_defaults(), ['discover' => false]);
        $string      = preg_replace_callback('/^\s*(https?:\/\/[^\s"]+)\s*$/uim', function ($m) use ($oembed_args) {
            $oembed = wp_oembed_get($m[1], $oembed_args);
            return $oembed ? $oembed : $m[0];
        }, $string);

        return $string;
    }

protected
function
viaWordPress
(
string
$
string
)
:
string
{
if
(
!
$
this
->
c
::
isWordPress
(
)
||
!
$
this
->
c
::
canCallFunc
(
'wp_oembed_get'
)
||
!
$
this
->
c
::
canCallFunc
(
'wp_embed_defaults'
)
)
{
throw
$
this
->
c
::
issue
(
'Unable to oEmbed via WordPress.'
)
;
}
$
oembed_args
=
array_merge
(
wp_embed_defaults
(
)
,
[
'discover'
=>
false
]
)
;
$
string
=
preg_replace_callback
(
'/^\s*(https?:\/\/[^\s"]+)\s*$/uim'
,
function
(
$
m
)
use
(
$
oembed_args
)
{
$
oembed
=
wp_oembed_get
(
$
m
[
1
]
,
$
oembed_args
)
;
return
$
oembed
$
oembed
:
$
m
[
0
]
;
}
,
$
string
)
;
return
$
string
;
}

Via WordPress.

@since 151125 OEmbed utilities.

@param string $string String to parse.


public function render(EncodedPolyline $encodedPolyline, Map $map)
    {
        $this->jsonBuilder
            ->reset()
            ->setValue('[map]', $map->getJavascriptVariable(), false)
            ->setValue('[path]', $this->encodingHelper->renderDecodePath($encodedPolyline->getValue()), false)
            ->setValues($encodedPolyline->getOptions());

        return sprintf(
            '%s = new google.maps.Polyline(%s);'.PHP_EOL,
            $encodedPolyline->getJavascriptVariable(),
            $this->jsonBuilder->build()
        );
    }

public
function
render
(
EncodedPolyline
$
encodedPolyline
,
Map
$
map
)
{
$
this
->
jsonBuilder
->
reset
(
)
->
setValue
(
'[map]'
,
$
map
->
getJavascriptVariable
(
)
,
false
)
->
setValue
(
'[path]'
,
$
this
->
encodingHelper
->
renderDecodePath
(
$
encodedPolyline
->
getValue
(
)
)
,
false
)
->
setValues
(
$
encodedPolyline
->
getOptions
(
)
)
;
return
sprintf
(
'%s = new google.maps.Polyline(%s);'
.
PHP_EOL
,
$
encodedPolyline
->
getJavascriptVariable
(
)
,
$
this
->
jsonBuilder
->
build
(
)
)
;
}

Renders an encoded polyline.

@param \Ivory\GoogleMap\Overlays\EncodedPolyline $encodedPolyline The encoded polyline.
@param \Ivory\GoogleMap\Map                      $map             The map.

@return string The JS output.


public function setSouthWest()
    {
        $args = func_get_args();

        if (isset($args[0]) && ($args[0] instanceof Coordinate)) {
            $this->southWest = $args[0];
        } elseif ((isset($args[0]) && is_numeric($args[0])) && (isset($args[1]) && is_numeric($args[1]))) {
            if ($this->southWest === null) {
                $this->southWest = new Coordinate();
            }

            $this->southWest->setLatitude($args[0]);
            $this->southWest->setLongitude($args[1]);

            if (isset($args[2]) && is_bool($args[2])) {
                $this->southWest->setNoWrap($args[2]);
            }
        } elseif (!isset($args[0])) {
            $this->southWest = null;
        } else {
            throw BaseException::invalidBoundSouthWest();
        }
    }

public function setSouthWest ( ) { $ args = func_get_args ( ) ; if ( isset ( $ args [ 0 ] ) && ( $ args [ 0 ] instanceof Coordinate ) ) { $ this -> southWest = $ args [ 0 ] ; } elseif ( ( isset ( $ args [ 0 ] ) && is_numeric ( $ args [ 0 ] ) ) && ( isset ( $ args [ 1 ] ) && is_numeric ( $ args [ 1 ] ) ) ) { if ( $ this -> southWest === null ) { $ this -> southWest = new Coordinate ( ) ; } $ this -> southWest -> setLatitude ( $ args [ 0 ] ) ; $ this -> southWest -> setLongitude ( $ args [ 1 ] ) ; if ( isset ( $ args [ 2 ] ) && is_bool ( $ args [ 2 ] ) ) { $ this -> southWest -> setNoWrap ( $ args [ 2 ] ) ; } } elseif ( ! isset ( $ args [ 0 ] ) ) { $ this -> southWest = null ; } else { throw BaseException :: invalidBoundSouthWest ( ) ; } }

Sets the south west coordinate.

Available prototypes:
- function setSouthWest(Ivory\GoogleMap\Base\Coordinate $southWest = null)
- function setSouthWest(double $latitude, double $longitude, boolean $noWrap = true)

@throws \Ivory\GoogleMap\Exception\BaseException If the south west coordinate is not valid (prototypes).


public function setNorthEast()
    {
        $args = func_get_args();

        if (isset($args[0]) && ($args[0] instanceof Coordinate)) {
            $this->northEast = $args[0];
        } elseif ((isset($args[0]) && is_numeric($args[0])) && (isset($args[1]) && is_numeric($args[1]))) {
            if ($this->northEast === null) {
                $this->northEast = new Coordinate();
            }

            $this->northEast->setLatitude($args[0]);
            $this->northEast->setLongitude($args[1]);

            if (isset($args[2]) && is_bool($args[2])) {
                $this->northEast->setNoWrap($args[2]);
            }
        } elseif (!isset($args[0])) {
            $this->northEast = null;
        } else {
            throw BaseException::invalidBoundNorthEast();
        }
    }

public function setNorthEast ( ) { $ args = func_get_args ( ) ; if ( isset ( $ args [ 0 ] ) && ( $ args [ 0 ] instanceof Coordinate ) ) { $ this -> northEast = $ args [ 0 ] ; } elseif ( ( isset ( $ args [ 0 ] ) && is_numeric ( $ args [ 0 ] ) ) && ( isset ( $ args [ 1 ] ) && is_numeric ( $ args [ 1 ] ) ) ) { if ( $ this -> northEast === null ) { $ this -> northEast = new Coordinate ( ) ; } $ this -> northEast -> setLatitude ( $ args [ 0 ] ) ; $ this -> northEast -> setLongitude ( $ args [ 1 ] ) ; if ( isset ( $ args [ 2 ] ) && is_bool ( $ args [ 2 ] ) ) { $ this -> northEast -> setNoWrap ( $ args [ 2 ] ) ; } } elseif ( ! isset ( $ args [ 0 ] ) ) { $ this -> northEast = null ; } else { throw BaseException :: invalidBoundNorthEast ( ) ; } }

Sets the north east coordinate.

Available prototypes:
- function setNorthEast(Ivory\GoogleMap\Base\Coordinate $northEast = null)
- function setNorthEast(double $latitude, double $longitude, boolean $noWrap = true)

@throws \Ivory\GoogleMap\Exception\BaseException If the north east coordinate is not valid (prototypes).


public function getCenter()
    {
        $centerLatitude = ($this->getSouthWest()->getLatitude() + $this->getNorthEast()->getLatitude()) / 2;
        $centerLongitude = ($this->getSouthWest()->getLongitude() + $this->getNorthEast()->getLongitude()) / 2;

        return new Coordinate($centerLatitude, $centerLongitude);
    }

public function getCenter ( ) { $ centerLatitude = ( $ this -> getSouthWest ( ) -> getLatitude ( ) + $ this -> getNorthEast ( ) -> getLatitude ( ) ) / 2 ; $ centerLongitude = ( $ this -> getSouthWest ( ) -> getLongitude ( ) + $ this -> getNorthEast ( ) -> getLongitude ( ) ) / 2 ; return new Coordinate ( $ centerLatitude , $ centerLongitude ) ; }

Gets the center of the bound.

@return \Ivory\GoogleMap\Base\Coordinate The bound center.


public function abbrBytes(string $string): int
    {
        if (!preg_match('/^(?<value>[0-9\.]+)\s*(?<modifier>bytes|byte|kbs|kb|k|mb|m|gb|g|tb|t)$/ui', $string, $_m)) {
            return 0; // Default value of `0`, failure.
        }
        $value    = (float) $_m['value'];
        $modifier = mb_strtolower($_m['modifier']);
        // unset($_m); // Housekeeping.

        switch ($modifier) {
            case 't':
            case 'tb':
                $value *= 1024;
                // Fall through.
                // no break
            case 'g':
            case 'gb':
                $value *= 1024;
                // Fall through.
                // no break
            case 'm':
            case 'mb':
                $value *= 1024;
                // Fall through.
                // no break
            case 'k':
            case 'kb':
            case 'kbs':
                $value *= 1024;
        }
        return (int) $value;
    }

Bytes represented by notation.

@since 150424 Initial release.
@since 170824.30708 Returns `int` instead of `float`.

@param string $string A string byte notation.

@return int Bytes represented by notation.


public function remoteBytes(string $url, bool $report_failure = false, int $expires_after = 86400): int
    {
        if (!$url) { // If no URL, no file size.
            return $report_failure ? -1 : 0;
        }
        if (($bytes = $this->c::dirCacheGet(__METHOD__, $url)) !== null) {
            return $bytes; // Cached this already.
        } // Get from an existing cache if at all possible.

        $r = $this->c::remoteResponse('HEAD::'.$url, [
            'max_con_secs' => 5, 'max_stream_secs' => 5,
        ]);
        if ($r->code === 200 && isset($r->headers['content-length'])) {
            $bytes = (int) $r->headers['content-length'];
        } else {
            $bytes = $report_failure ? -1 : 0; // Not possible.
        }
        $this->c::dirCacheSet(__METHOD__, $url, $bytes, $expires_after);
        return $bytes; // Cached for future reference.
    }

Determines remote file size.

@since 170824.30708 Remote file size.

@param string $url            URL to check size of.
@param int    $expires_after  Cache expires after (in seconds).
@param bool   $report_failure If true, return `-1` on failure.

@return int Remote file size, in bytes.
@note If `$report_failure` is true, `-1` indicates failure.
For example, if file does not exist, or it has no `content-length` header.


public function un(array $parts): string
    {
        $scheme   = '';
        $host     = $port     = '';
        $user     = $pass     = '';
        $path     = $query     = $fragment = '';

        $parts = array_map('strval', $parts);

        if (isset($parts['scheme'][0])) {
            if ($parts['scheme'] === '//') {
                $scheme = $parts['scheme'];
            } else {
                $scheme = $parts['scheme'].'://';
            }
        } // Supports cross-protocol scheme.

        if (isset($parts['host'][0])) {
            $host = $parts['host'];
        }
        if (isset($parts['port'][0])) {
            $port = ':'.$parts['port'];
        }
        if (isset($parts['user'][0])) {
            $user = $parts['user'];
        }
        if (isset($parts['pass'][0])) {
            $pass = ':'.$parts['pass'];
        }
        if (isset($user[0]) || isset($pass[0])) {
            $pass .= '@'; // `user@`, `:pass@`, or `user:pass@`.
        }
        if (isset($parts['path'][0])) {
            $path = '/'.$this->c::mbLTrim($parts['path'], '/');
        }
        if (isset($parts['query'][0])) {
            $query = '?'.$parts['query'];
        }
        if (isset($parts['fragment'][0])) {
            $fragment = '#'.$parts['fragment'];
        }
        return $scheme.$user.$pass.$host.$port.$path.$query.$fragment;
    }

public
function
un
(
array
$
parts
)
:
string
{
$
scheme
=
''
;
$
host
=
$
port
=
''
;
$
user
=
$
pass
=
''
;
$
path
=
$
query
=
$
fragment
=
''
;
$
parts
=
array_map
(
'strval'
,
$
parts
)
;
if
(
isset
(
$
parts
[
'scheme'
]
[
0
]
)
)
{
if
(
$
parts
[
'scheme'
]
===
'//'
)
{
$
scheme
=
$
parts
[
'scheme'
]
;
}
else
{
$
scheme
=
$
parts
[
'scheme'
]
.
'://'
;
}
}
// Supports cross-protocol scheme.
if
(
isset
(
$
parts
[
'host'
]
[
0
]
)
)
{
$
host
=
$
parts
[
'host'
]
;
}
if
(
isset
(
$
parts
[
'port'
]
[
0
]
)
)
{
$
port
=
':'
.
$
parts
[
'port'
]
;
}
if
(
isset
(
$
parts
[
'user'
]
[
0
]
)
)
{
$
user
=
$
parts
[
'user'
]
;
}
if
(
isset
(
$
parts
[
'pass'
]
[
0
]
)
)
{
$
pass
=
':'
.
$
parts
[
'pass'
]
;
}
if
(
isset
(
$
user
[
0
]
)
||
isset
(
$
pass
[
0
]
)
)
{
$
pass
.=
'@'
;
// `user@`, `:pass@`, or `user:pass@`.
}
if
(
isset
(
$
parts
[
'path'
]
[
0
]
)
)
{
$
path
=
'/'
.
$
this
->
c
::
mbLTrim
(
$
parts
[
'path'
]
,
'/'
)
;
}
if
(
isset
(
$
parts
[
'query'
]
[
0
]
)
)
{
$
query
=
'?'
.
$
parts
[
'query'
]
;
}
if
(
isset
(
$
parts
[
'fragment'
]
[
0
]
)
)
{
$
fragment
=
'#'
.
$
parts
[
'fragment'
]
;
}
return
$
scheme
.
$
user
.
$
pass
.
$
host
.
$
port
.
$
path
.
$
query
.
$
fragment
;
}

Unparses a URL.

@since 150424 Initial release.

@param array $parts Input URL parts.

@return string Unparsed URL in string format.


public function render(Coordinate $coordinate)
    {
        return sprintf(
            '%s = new google.maps.LatLng(%s, %s, %s);'.PHP_EOL,
            $coordinate->getJavascriptVariable(),
            $coordinate->getLatitude(),
            $coordinate->getLongitude(),
            json_encode($coordinate->isNoWrap())
        );
    }

Renders a coordinate.

@param \Ivory\GoogleMap\Base\Coordinate $coordinate The coordinate.

@return string The JS output.


public function render(MarkerImage $markerImage)
    {
        return sprintf(
            '%s = new google.maps.MarkerImage("%s", %s, %s, %s, %s);'.PHP_EOL,
            $markerImage->getJavascriptVariable(),
            $markerImage->getUrl(),
            $markerImage->hasSize() ? $markerImage->getSize()->getJavascriptVariable() : 'null',
            $markerImage->hasOrigin() ? $markerImage->getOrigin()->getJavascriptVariable() : 'null',
            $markerImage->hasAnchor() ? $markerImage->getAnchor()->getJavascriptVariable() : 'null',
            $markerImage->hasScaledSize() ? $markerImage->getScaledSize()->getJavascriptVariable() : 'null'
        );
    }

Renders a marker image.

@param \Ivory\GoogleMap\Overlays\MarkerImage $markerImage The marker image.

@return string The JS output.


public function parse($xml, array $pluralizationRules = array())
    {
        $parsedXml = json_decode(json_encode(new \SimpleXMLElement($xml)), true);

        return $this->pluralize($parsedXml, $pluralizationRules);
    }

public function parse ( $ xml , array $ pluralizationRules = array ( ) ) { $ parsedXml = json_decode ( json_encode ( new \ SimpleXMLElement ( $ xml ) ) , true ) ; return $ this -> pluralize ( $ parsedXml , $ pluralizationRules ) ; }

Parses xml according to pluralization rules.

@param string  $xml                The xml.
@param array   $pluralizationRules The pluralization rules.

@return \stdClass The parsed & pluralized xml.

Parses xml according to pluralization rules .


protected function pluralize(array $xml, array $rules)
    {
        foreach ($xml as $attribute => $value) {
            if (isset($rules[$attribute])) {
                $xml[$rules[$attribute]] = $value;
                unset($xml[$attribute]);

                $attribute = $rules[$attribute];

                if (!is_array($value) || is_string(key($value))) {
                    $xml[$attribute] = array($value);
                }
            }

            if (is_array($xml[$attribute])) {
                $xml[$attribute] = $this->pluralize($xml[$attribute], $rules);
            }
        }

        return $this->normalize($xml);
    }

protected function pluralize ( array $ xml , array $ rules ) { foreach ( $ xml as $ attribute => $ value ) { if ( isset ( $ rules [ $ attribute ] ) ) { $ xml [ $ rules [ $ attribute ] ] = $ value ; unset ( $ xml [ $ attribute ] ) ; $ attribute = $ rules [ $ attribute ] ; if ( ! is_array ( $ value ) || is_string ( key ( $ value ) ) ) { $ xml [ $ attribute ] = array ( $ value ) ; } } if ( is_array ( $ xml [ $ attribute ] ) ) { $ xml [ $ attribute ] = $ this -> pluralize ( $ xml [ $ attribute ] , $ rules ) ; } } return $ this -> normalize ( $ xml ) ; }

Pluralizes xml.

@param array $xml   The xml.
@param array $rules The pluralization rules.

@return \stdClass The pluralized xml.


public static function invalidDistanceMatrixRequestTravelMode()
    {
        $travelModes = array_diff(TravelMode::getTravelModes(), array(TravelMode::TRANSIT));

        return new static(sprintf(
            'The distance matrix request travel mode can only be : %s.',
            implode(', ', $travelModes)
        ));
    }

Gets the "INVALID DISTANCE MATRIX REQUEST TRAVEL MODE" exception.

@return \Ivory\GoogleMap\Exception\DistanceMatrixException The "INVALID DISTANCE MATRIX REQUEST TRAVEL MODE" exception.

Gets the INVALID DISTANCE MATRIX REQUEST TRAVEL MODE exception .


public function parse(string $host, bool $no_port = false): array
    {
        $host = mb_strtolower($host); // `abc.xyz.example.com:80`.

        $name = preg_replace('/\:[0-9]+$/u', '', $host); // `abc.xyz.example.com`.
        $port = (explode(':', $host, 2) + ['', ''])[1]; // `80`; i.e., port number.

        $name_parts = explode('.', $name); // `[abc,xyz,example,com]`.

        $subs = array_slice($name_parts, 0, -2); // `[abc,xyz]`.
        $sub  = implode('.', $subs); // `abc.xyz`.

        $root_name     = implode('.', array_slice($name_parts, -2)); // `example.com`.
        $root_port     = $port; // This is nothing more than a copy of the `$port`; `80`.
        $root          = $root_name.(isset($root_port[0]) ? ':'.$root_port : ''); // `example.com:80`.
        $root_basename = implode('.', array_slice($name_parts, -2, 1)); // `example`.

        $tld = implode('.', array_slice($name_parts, -1)); // `com`, `net`, `org`, etc.

        return compact('name', 'port', 'sub', 'subs', 'root', 'root_name', 'root_port', 'root_basename', 'tld');
    }

Host parser.

@since 151002 Adding host parser.
@since 170124.74961 Adding `port` key.
@since 170124.74961 Adding `root_name` key.
@since 170124.74961 Adding `root_port` key.
@since 170124.74961 Removing `root_as_name` key.
@since 170124.74961 The `name` key now contains only the name.
@since 170124.74961 The `root` key now contains a full root host (including port).
@since 170124.74961 Bug fix. Hosts with ports in their name are now exploded properly.

@param string $host The input host to parse.

@return array `[name, port, sub, subs, root, root_name, root_port, root_basename, tld]`.

@internal This allows an empty `$host` so that a caller can get the array elements even if empty.


public function unParse(array $parts): string
    {
        $name = $port= '';

        if (isset($parts['name'][0])) {
            $name = $parts['name'];
        }
        if (isset($parts['port'][0])) {
            $port = ':'.$parts['port'];
        }
        return $name.$port;
    }

public function unParse ( array $ parts ) : string { $ name = $ port = '' ; if ( isset ( $ parts [ 'name' ] [ 0 ] ) ) { $ name = $ parts [ 'name' ] ; } if ( isset ( $ parts [ 'port' ] [ 0 ] ) ) { $ port = ':' . $ parts [ 'port' ] ; } return $ name . $ port ; }

Unparses a host.

@since 151002 Adding host parser.
@since 170124.74961 Collecting both `name` and `port` now.

@param array $parts Input host parts.

@return string Unparsed host string.


public function setPosition()
    {
        $args = func_get_args();

        if (isset($args[0]) && ($args[0] instanceof Coordinate)) {
            $this->position = $args[0];
        } elseif ((isset($args[0]) && is_numeric($args[0])) && (isset($args[1]) && is_numeric($args[1]))) {
            $this->position->setLatitude($args[0]);
            $this->position->setLongitude($args[1]);

            if (isset($args[2]) && is_bool($args[2])) {
                $this->position->setNoWrap($args[2]);
            }
        } elseif (!isset($args[0])) {
            $this->position = null;
        } else {
            throw OverlayException::invalidMarkerPosition();
        }
    }

public function setPosition ( ) { $ args = func_get_args ( ) ; if ( isset ( $ args [ 0 ] ) && ( $ args [ 0 ] instanceof Coordinate ) ) { $ this -> position = $ args [ 0 ] ; } elseif ( ( isset ( $ args [ 0 ] ) && is_numeric ( $ args [ 0 ] ) ) && ( isset ( $ args [ 1 ] ) && is_numeric ( $ args [ 1 ] ) ) ) { $ this -> position -> setLatitude ( $ args [ 0 ] ) ; $ this -> position -> setLongitude ( $ args [ 1 ] ) ; if ( isset ( $ args [ 2 ] ) && is_bool ( $ args [ 2 ] ) ) { $ this -> position -> setNoWrap ( $ args [ 2 ] ) ; } } elseif ( ! isset ( $ args [ 0 ] ) ) { $ this -> position = null ; } else { throw OverlayException :: invalidMarkerPosition ( ) ; } }

Sets the marker position.

Available prototypes:
- function setPosition(Ivory\GoogleMap\Base\Coordinate $position = null)
- function setPosition(double $latitude, double $longitude, boolean $noWrap = true)

@throws \Ivory\GoogleMap\Exception\OverlayException If the position is not valid.


public function setAnimation($animation = null)
    {
        if (!in_array($animation, Animation::getAnimations()) && ($animation !== null)) {
            throw OverlayException::invalidMarkerAnimation();
        }

        $this->animation = $animation;
    }

public function setAnimation ( $ animation = null ) { if ( ! in_array ( $ animation , Animation :: getAnimations ( ) ) && ( $ animation !== null ) ) { throw OverlayException :: invalidMarkerAnimation ( ) ; } $ this -> animation = $ animation ; }

Sets the marker animation.

@param string $animation The marker animation.

@throws \Ivory\GoogleMap\Exception\OverlayException If the animation is not valid.


public function setIcon()
    {
        $args = func_get_args();

        if (isset($args[0]) && ($args[0] instanceof MarkerImage)) {
            if ($args[0]->getUrl() === null) {
                throw OverlayException::invalidMarkerIconUrl();
            }

            $this->icon = $args[0];
        } elseif (isset($args[0]) && is_string($args[0])) {
            if ($this->icon === null) {
                $this->icon = new MarkerImage();
            }

            $this->icon->setUrl($args[0]);
        } elseif (!isset($args[0])) {
            $this->icon = null;
        } else {
            throw OverlayException::invalidMarkerIcon();
        }
    }

public function setIcon ( ) { $ args = func_get_args ( ) ; if ( isset ( $ args [ 0 ] ) && ( $ args [ 0 ] instanceof MarkerImage ) ) { if ( $ args [ 0 ] -> getUrl ( ) === null ) { throw OverlayException :: invalidMarkerIconUrl ( ) ; } $ this -> icon = $ args [ 0 ] ; } elseif ( isset ( $ args [ 0 ] ) && is_string ( $ args [ 0 ] ) ) { if ( $ this -> icon === null ) { $ this -> icon = new MarkerImage ( ) ; } $ this -> icon -> setUrl ( $ args [ 0 ] ) ; } elseif ( ! isset ( $ args [ 0 ] ) ) { $ this -> icon = null ; } else { throw OverlayException :: invalidMarkerIcon ( ) ; } }

Sets the marker icon.

Available prototypes:
- function setIcon(Ivory\GoogleMap\Overlays\MarkerImage $markerImage = null)
- function setIcon(string $url = null)

@throws \Ivory\GoogleMap\Exception\OverlayException If the icon is not valid.


public function setShadow()
    {
        $args = func_get_args();

        if (isset($args[0]) && ($args[0] instanceof MarkerImage)) {
            if ($args[0]->getUrl() === null) {
                throw OverlayException::invalidMarkerShadowUrl();
            }

            $this->shadow = $args[0];
        } elseif (isset($args[0]) && is_string($args[0])) {
            if ($this->shadow === null) {
                $this->shadow = new MarkerImage();
            }

            $this->shadow->setUrl($args[0]);
        } elseif (!isset($args[0])) {
            $this->shadow = null;
        } else {
            throw OverlayException::invalidMarkerShadow();
        }
    }

public function setShadow ( ) { $ args = func_get_args ( ) ; if ( isset ( $ args [ 0 ] ) && ( $ args [ 0 ] instanceof MarkerImage ) ) { if ( $ args [ 0 ] -> getUrl ( ) === null ) { throw OverlayException :: invalidMarkerShadowUrl ( ) ; } $ this -> shadow = $ args [ 0 ] ; } elseif ( isset ( $ args [ 0 ] ) && is_string ( $ args [ 0 ] ) ) { if ( $ this -> shadow === null ) { $ this -> shadow = new MarkerImage ( ) ; } $ this -> shadow -> setUrl ( $ args [ 0 ] ) ; } elseif ( ! isset ( $ args [ 0 ] ) ) { $ this -> shadow = null ; } else { throw OverlayException :: invalidMarkerShadow ( ) ; } }

Sets the marker shadow.

Available prototypes:
- function setShadow(Ivory\GoogleMap\Overlays\MarkerImage $markerImage = null)
- function setShadow(string $url = null)

@throws \Ivory\GoogleMap\Exception\OverlayException If the marker shadow is not valid.


public function setShape()
    {
        $args = func_get_args();

        if (isset($args[0]) && ($args[0] instanceof MarkerShape)) {
            if (!$args[0]->hasCoordinates()) {
                throw OverlayException::invalidMarkerShapeCoordinates();
            }

            $this->shape = $args[0];
        } elseif ((isset($args[0]) && is_string($args[0])) && (isset($args[1]) && is_array($args[1]))) {
            if ($this->shape === null) {
                $this->shape = new MarkerShape();
            }

            $this->shape->setType($args[0]);
            $this->shape->setCoordinates($args[1]);
        } elseif (!isset($args[0])) {
            $this->shape = null;
        } else {
            throw OverlayException::invalidMarkerShape();
        }
    }

public function setShape ( ) { $ args = func_get_args ( ) ; if ( isset ( $ args [ 0 ] ) && ( $ args [ 0 ] instanceof MarkerShape ) ) { if ( ! $ args [ 0 ] -> hasCoordinates ( ) ) { throw OverlayException :: invalidMarkerShapeCoordinates ( ) ; } $ this -> shape = $ args [ 0 ] ; } elseif ( ( isset ( $ args [ 0 ] ) && is_string ( $ args [ 0 ] ) ) && ( isset ( $ args [ 1 ] ) && is_array ( $ args [ 1 ] ) ) ) { if ( $ this -> shape === null ) { $ this -> shape = new MarkerShape ( ) ; } $ this -> shape -> setType ( $ args [ 0 ] ) ; $ this -> shape -> setCoordinates ( $ args [ 1 ] ) ; } elseif ( ! isset ( $ args [ 0 ] ) ) { $ this -> shape = null ; } else { throw OverlayException :: invalidMarkerShape ( ) ; } }

Sets the marker shape.

Available prototypes:
- function setShape(Ivory\GoogleMap\Overlays\MarkerShape $shape = null)
- function setShape(string $type, array $coordinates)

@throws \Ivory\GoogleMap\Exception\OverlayException If the shape is not valid.


public function headerIdCallback(string $raw): string
    {
        $id = mb_strtolower($raw);
        $id = preg_replace('/[^\w]+/u', '-', $id);
        $id = 'j2h.'.$this->c::mbTrim($id, '', '-');

        $this->header_id_counter[$id] = $this->header_id_counter[$id] ?? 0;
        ++$this->header_id_counter[$id]; // Increment counter.

        if ($this->header_id_counter[$id] > 1) {
            $id .= '-'.$this->header_id_counter[$id];
        }
        return $id; // `id=""` attribute value.
    }

public
function
headerIdCallback
(
string
$
raw
)
:
string
{
$
id
=
mb_strtolower
(
$
raw
)
;
$
id
=
preg_replace
(
'/[^\w]+/u'
,
'-'
,
$
id
)
;
$
id
=
'j2h.'
.
$
this
->
c
::
mbTrim
(
$
id
,
''
,
'-'
)
;
$
this
->
header_id_counter
[
$
id
]
=
$
this
->
header_id_counter
[
$
id
]
??
0
;
++
$
this
->
header_id_counter
[
$
id
]
;
// Increment counter.
if
(
$
this
->
header_id_counter
[
$
id
]
>
1
)
{
$
id
.=
'-'
.
$
this
->
header_id_counter
[
$
id
]
;
}
return
$
id
;
// `id=""` attribute value.
}

Default header `id=""` callback.

@since 170211.63148 ID callback.

@param string $raw Header text value.

@return string The `id=""` attribute value.


public function firstImageUrl(string $markdown): string
    {
        $regex      = '/(?<=^|[\s;,])\!\[[^\v[\]]*\]\((?<url>https?\:\/\/[^\s()]+?\.(?:png|jpeg|jpg|gif))\)(?=$|[\s.!?;,])/ui';
        return $url = $markdown && preg_match($regex, $markdown, $_m) ? $_m['url'] : '';
    }

First image URL.

@since 170124.74961 Initial release.

@param string $markdown Markdown.

@return string First image URL.


public function attributes($value, array $args = [])
    {
        if (is_array($value) || is_object($value)) {
            foreach ($value as $_key => &$_value) {
                $_value = $this->attributes($_value, $args);
            } // unset($_key, $_value);
            return $value;
        }
        if (!($string = (string) $value)) {
            return $string; // Nothing to do.
        }
        $default_args = [
            'allowed_attributes' => [],
        ];
        $args = array_merge($default_args, $args);
        $args = array_intersect_key($args, $default_args);

        $allowed_attributes = // Force lowercase.
            array_map('mb_strtolower', (array) $args['allowed_attributes']);

        $regex_tags  = '/(?<open>\<[\w\-]+)(?<attrs>[^>]+)(?<close>\>)/ui';
        $regex_attrs = '/\s+(?<attr>[\w\-]+)(?:\s*\=\s*(["\']).*?\\2|\s*\=[^\s]*)?/uis';

        return preg_replace_callback($regex_tags, function ($m) use ($allowed_attributes, $regex_attrs) {
            return $m['open'].preg_replace_callback($regex_attrs, function ($m) use ($allowed_attributes) {
                return in_array(mb_strtolower($m['attr']), $allowed_attributes, true) ? $m[0] : '';
            }, $m['attrs']).$m['close']; // With modified attributes.
        }, $string); // Removes attributes; leaving only those allowed explicitly.
    }

Strips HTML attributes deeply.

@since 150424 Initial release.

@param mixed $value Any input value.
@param array $args  Any additional behavioral args.

@return string|array|object String w/ HTML attributes stripped.


public function setBound()
    {
        $args = func_get_args();

        if (isset($args[0]) && ($args[0] instanceof Bound)) {
            if (!$args[0]->hasCoordinates()) {
                throw OverlayException::invalidRectangleBoundCoordinates();
            }

            $this->bound = $args[0];
        } elseif ((isset($args[0]) && ($args[0] instanceof Coordinate))
            && (isset($args[1]) && ($args[1] instanceof Coordinate))
        ) {
            $this->bound->setSouthWest($args[0]);
            $this->bound->setNorthEast($args[1]);
        } elseif ((isset($args[0]) && is_numeric($args[0]))
            && (isset($args[1]) && is_numeric($args[1]))
            && (isset($args[2]) && is_numeric($args[2]))
            && (isset($args[3]) && is_numeric($args[3]))
        ) {
            $this->bound->setSouthWest(new Coordinate($args[0], $args[1]));
            $this->bound->setNorthEast(new Coordinate($args[2], $args[3]));

            if (isset($args[4]) && is_bool($args[4])) {
                $this->bound->getSouthWest()->setNoWrap($args[4]);
            }

            if (isset($args[5]) && is_bool($args[5])) {
                $this->bound->getNorthEast()->setNoWrap($args[5]);
            }
        } else {
            throw OverlayException::invalidRectangleBound();
        }
    }

public function setBound ( ) { $ args = func_get_args ( ) ; if ( isset ( $ args [ 0 ] ) && ( $ args [ 0 ] instanceof Bound ) ) { if ( ! $ args [ 0 ] -> hasCoordinates ( ) ) { throw OverlayException :: invalidRectangleBoundCoordinates ( ) ; } $ this -> bound = $ args [ 0 ] ; } elseif ( ( isset ( $ args [ 0 ] ) && ( $ args [ 0 ] instanceof Coordinate ) ) && ( isset ( $ args [ 1 ] ) && ( $ args [ 1 ] instanceof Coordinate ) ) ) { $ this -> bound -> setSouthWest ( $ args [ 0 ] ) ; $ this -> bound -> setNorthEast ( $ args [ 1 ] ) ; } elseif ( ( isset ( $ args [ 0 ] ) && is_numeric ( $ args [ 0 ] ) ) && ( isset ( $ args [ 1 ] ) && is_numeric ( $ args [ 1 ] ) ) && ( isset ( $ args [ 2 ] ) && is_numeric ( $ args [ 2 ] ) ) && ( isset ( $ args [ 3 ] ) && is_numeric ( $ args [ 3 ] ) ) ) { $ this -> bound -> setSouthWest ( new Coordinate ( $ args [ 0 ] , $ args [ 1 ] ) ) ; $ this -> bound -> setNorthEast ( new Coordinate ( $ args [ 2 ] , $ args [ 3 ] ) ) ; if ( isset ( $ args [ 4 ] ) && is_bool ( $ args [ 4 ] ) ) { $ this -> bound -> getSouthWest ( ) -> setNoWrap ( $ args [ 4 ] ) ; } if ( isset ( $ args [ 5 ] ) && is_bool ( $ args [ 5 ] ) ) { $ this -> bound -> getNorthEast ( ) -> setNoWrap ( $ args [ 5 ] ) ; } } else { throw OverlayException :: invalidRectangleBound ( ) ; } }

Sets the rectangle bound.

Available prototypes:
- function setBound(Ivory\GoogleMap\Base\Bound $bound)
- function setBount(Ivory\GoogleMap\Base\Coordinate $southWest, Ivory\GoogleMap\Base\Coordinate $northEast)
- function setBound(
double $southWestLatitude,
double $southWestLongitude,
double $northEastLatitude,
double $northEastLongitude,
boolean southWestNoWrap = true,
boolean $northEastNoWrap = true
)

@throws \Ivory\GoogleMap\Exception\OverlayException If the bound is not valid.


public function message(string $slug = ''): string
    {
        $slug     = $slug ?: $this->slug();
        $messages = $this->messages($slug);
        return $messages[0] ?? $this->default_message;
    }

public function message ( string $ slug = '' ) : string { $ slug = $ slug ? : $ this -> slug ( ) ; $ messages = $ this -> messages ( $ slug ) ; return $ messages [ 0 ] ?? $ this -> default_message ; }

Get error slug.

@since 160710 Error utils.

@param string $slug Error slug.

@return string Error message.


public function messages(string $slug = '', bool $by_slug = false): array
    {
        if (!$slug) { // All messages (i.e., for all slugs)?
            //
            if ($by_slug) { // All messages keyed by slug?
                return $this->errors ?: [$this->default_slug => $this->default_message];
                //
            } else { // Merge all messages into a single array.
                $messages = []; // Initialize array.

                foreach ($this->errors as $_slug => $_messages) {
                    $messages = array_merge($messages, $_messages);
                } // unset($_slug, $_messages); // Housekeeping.

                return $messages ?: [$this->default_message];
            }
        } else { // For a specific slug.
            $messages = $this->errors[$slug] ?? [];
            return $messages ?: [$this->default_message];
        }
    }

Get error messages.

@since 160710 Error utils.

@param string $slug    Error slug.
@param bool   $by_slug All errors by slug?

@return string[] An array of error messages.


public function data(string $slug = '', bool $by_slug = false)
    {
        if (!$slug) { // All data (i.e., for all slugs)?
            //
            if ($by_slug) { // All data keyed by slug?
                return $this->error_data ?: [$this->default_slug => null];
                //
            } else { // Data for the first slug.
                // NOTE: Different than `messages()`.
                $slug = $this->slug(); // First slug.
                return $this->error_data[$slug] ?? null;
            }
        } else {
            return $this->error_data[$slug] ?? null;
        }
    }

public
function
data
(
string
$
slug
=
''
,
bool
$
by_slug
=
false
)
{
if
(
!
$
slug
)
{
// All data (i.e., for all slugs)?
//
if
(
$
by_slug
)
{
// All data keyed by slug?
return
$
this
->
error_data
:
[
$
this
->
default_slug
=>
]
;
//
}
else
{
// Data for the first slug.
// NOTE: Different than `messages()`.
$
slug
=
$
this
->
slug
(
)
;
// First slug.
return
$
this
->
error_data
[
$
slug
]
??
;
}
}
else
{
return
$
this
->
error_data
[
$
slug
]
??
;
}
}

Get error data.

@since 160710 Error utils.

@param string $slug    Error slug.
@param bool   $by_slug All data by slug?

@return array|mixed|null Error data.


public function add(string $slug, string $message = '', $data = null)
    {
        $slug = $slug ?: $this->default_slug;

        if (!$message && $slug === $this->default_slug) {
            $message = $this->default_message;
        } elseif (!$message) { // If empty, base it on slug.
            $message = mb_strtolower($this->c::slugToName($slug));
            $message = $this->c::mbUcFirst($message).'.';
        }
        $this->errors[$slug][] = $message;

        if (isset($data) || !array_key_exists($slug, $this->error_data)) {
            $this->error_data[$slug] = $data;
        }
    }

public
function
add
(
string
$
slug
,
string
$
message
=
''
,
$
data
=
)
{
$
slug
=
$
slug
:
$
this
->
default_slug
;
if
(
!
$
message
&&
$
slug
===
$
this
->
default_slug
)
{
$
message
=
$
this
->
default_message
;
}
elseif
(
!
$
message
)
{
// If empty, base it on slug.
$
message
=
mb_strtolower
(
$
this
->
c
::
slugToName
(
$
slug
)
)
;
$
message
=
$
this
->
c
::
mbUcFirst
(
$
message
)
.
'.'
;
}
$
this
->
errors
[
$
slug
]
[
]
=
$
message
;
if
(
isset
(
$
data
)
||
!
array_key_exists
(
$
slug
,
$
this
->
error_data
)
)
{
$
this
->
error_data
[
$
slug
]
=
$
data
;
}
}

Add error.

@since 160710 Error utils.

@param string $slug    Error slug.
@param string $message Error message.
@param mixed  $data    Error data.


public function addCoordinate()
    {
        $args = func_get_args();

        if (isset($args[0]) && ($args[0] instanceof Coordinate)) {
            $this->coordinates[] = $args[0];
        } elseif ((isset($args[0]) && is_numeric($args[0])) && (isset($args[1]) && is_numeric($args[1]))) {
            $coordinate = new Coordinate($args[0], $args[1]);

            if (isset($args[2]) && is_bool($args[2])) {
                $coordinate->setNoWrap($args[2]);
            }

            $this->coordinates[] = $coordinate;
        } else {
            throw OverlayException::invalidPolygonCoordinate();
        }
    }

public function addCoordinate ( ) { $ args = func_get_args ( ) ; if ( isset ( $ args [ 0 ] ) && ( $ args [ 0 ] instanceof Coordinate ) ) { $ this -> coordinates [ ] = $ args [ 0 ] ; } elseif ( ( isset ( $ args [ 0 ] ) && is_numeric ( $ args [ 0 ] ) ) && ( isset ( $ args [ 1 ] ) && is_numeric ( $ args [ 1 ] ) ) ) { $ coordinate = new Coordinate ( $ args [ 0 ] , $ args [ 1 ] ) ; if ( isset ( $ args [ 2 ] ) && is_bool ( $ args [ 2 ] ) ) { $ coordinate -> setNoWrap ( $ args [ 2 ] ) ; } $ this -> coordinates [ ] = $ coordinate ; } else { throw OverlayException :: invalidPolygonCoordinate ( ) ; } }

Adds a coordinate to the polygon.

Available prototypes:
- function addCoordinate(Ivory\GoogleMap\Base\Coordinate $coordinate)
- function addCoordinate(double $latitude, double $longitude, boolean $noWrap = true)

@throws \Ivory\GoogleMap\Exception\OverlayException If the coordinate is not valid.


public function load($html) {
        if ($html instanceof \DOMDocument) {
            $d = $html;
        } elseif ($html instanceof \DOMElement) {
            $d = $html->ownerDocument;
        } elseif ($html instanceof \SplFileInfo) {
            $d = new \DOMDocument();
            $d->preserveWhiteSpace = false;
            $d->validateOnParse = true;
            $d->loadHTMLFile($html->getPathname());
        } else {
            $d = new \DOMDocument();
            $d->preserveWhiteSpace = false;
            $d->validateOnParse = true;
            $d->loadHTML($html);
        }
        $d->formatOutput = false;
        $d->normalizeDocument();
        $this->doc = $d;
        return $this;
    }

public function load ( $ html ) { if ( $ html instanceof \ DOMDocument ) { $ d = $ html ; } elseif ( $ html instanceof \ DOMElement ) { $ d = $ html -> ownerDocument ; } elseif ( $ html instanceof \ SplFileInfo ) { $ d = new \ DOMDocument ( ) ; $ d -> preserveWhiteSpace = false ; $ d -> validateOnParse = true ; $ d -> loadHTMLFile ( $ html -> getPathname ( ) ) ; } else { $ d = new \ DOMDocument ( ) ; $ d -> preserveWhiteSpace = false ; $ d -> validateOnParse = true ; $ d -> loadHTML ( $ html ) ; } $ d -> formatOutput = false ; $ d -> normalizeDocument ( ) ; $ this -> doc = $ d ; return $ this ; }

Load an HTML document

@param \DOMDocument|\DOMElement|\SplFileInfo|string $html
@return PrettyMin


public function minify($options = [])
    {
        $resolver = new OptionsResolver();
        $resolver->setDefaults([
            'minify_js' => $this->options['minify_js'],
            'minify_css' => $this->options['minify_css'],
            'remove_comments' => $this->options['remove_comments'],
            'remove_empty_attributes' => $this->options['remove_empty_attributes']
        ]);
        $options = $resolver->resolve($options);

        if ($options['minify_js']) {
            $this->minifyJavascript();
        }
        if ($options['minify_css']) {
            $this->minifyCss();
        }
        if ($options['remove_comments']) {
            $this->removeComments();
        }

        if ($options['remove_empty_attributes']) {
            $this->removeEmptyAttributes();
        }

        $this->removeWhitespace();

        return $this;
    }

public function minify ( $ options = [ ] ) { $ resolver = new OptionsResolver ( ) ; $ resolver -> setDefaults ( [ 'minify_js' => $ this -> options [ 'minify_js' ] , 'minify_css' => $ this -> options [ 'minify_css' ] , 'remove_comments' => $ this -> options [ 'remove_comments' ] , 'remove_empty_attributes' => $ this -> options [ 'remove_empty_attributes' ] ] ) ; $ options = $ resolver -> resolve ( $ options ) ; if ( $ options [ 'minify_js' ] ) { $ this -> minifyJavascript ( ) ; } if ( $ options [ 'minify_css' ] ) { $ this -> minifyCss ( ) ; } if ( $ options [ 'remove_comments' ] ) { $ this -> removeComments ( ) ; } if ( $ options [ 'remove_empty_attributes' ] ) { $ this -> removeEmptyAttributes ( ) ; } $ this -> removeWhitespace ( ) ; return $ this ; }

Minify the loaded HTML document

@param array $options
@return PrettyMin


protected function indentRecursive(\DOMNode $currentNode, $depth) {
        $indent_characters = $this->options['indent_characters'];

        $indentCurrent = true;
        $indentChildren = true;
        $indentClosingTag = false;
        if(($currentNode->nodeType == XML_TEXT_NODE)) {
            $indentCurrent = false;
        }

        if (in_array($currentNode->nodeName, $this->options['keep_whitespace_in'])) {
            $indentCurrent = true;
            $indentChildren = false;
            $indentClosingTag = (strpos($currentNode->nodeValue, "\n") !== false);
        }

        if (in_array($currentNode->nodeName, $this->options['keep_whitespace_around'])) {
            $indentCurrent = false;
        }
        if($indentCurrent && $depth > 0) {
            // Indenting a node consists of inserting before it a new text node
            // containing a newline followed by a number of tabs corresponding
            // to the node depth.
            $textNode = $currentNode->ownerDocument->createTextNode("\n" . str_repeat($indent_characters, $depth));
            $currentNode->parentNode->insertBefore($textNode, $currentNode);
        }
        if($indentCurrent && $currentNode->childNodes && $indentChildren) {
            foreach($currentNode->childNodes as $childNode) {
                $indentClosingTag = $this->indentRecursive($childNode, $depth + 1);
            }
        }
        if($indentClosingTag) {
            // If children have been indented, then the closing tag
            // of the current node must also be indented.
            if ($currentNode->lastChild && ($currentNode->lastChild->nodeType == XML_CDATA_SECTION_NODE || $currentNode->lastChild->nodeType == XML_TEXT_NODE) && preg_match('/\n\s?$/', $currentNode->lastChild->textContent)) {
                $currentNode->lastChild->nodeValue = preg_replace('/\n\s?$/', "\n" . str_repeat("\t", $depth), $currentNode->lastChild->nodeValue);
            } else {
                $textNode = $currentNode->ownerDocument->createTextNode("\n" . str_repeat("\t", $depth));
                $currentNode->appendChild($textNode);
            }
        }
        return $indentCurrent;
    }

indent HTML code

originally based on http://stackoverflow.com/a/18260955

@param \DOMNode $currentNode
@param int $depth
@return bool


public function postLoad(LifecycleEventArgs $args)
    {
        $document = $args->getDocument();

        if ($document instanceof UserInterface) {
            $repository = $args->getDocumentManager()->getRepository('Organizations\Entity\Organization');
            $userId  = $document->getId();
            $reference = new OrganizationReference($userId, $repository);

            $document->setOrganization($reference);
        }
    }

public function postLoad ( LifecycleEventArgs $ args ) { $ document = $ args -> getDocument ( ) ; if ( $ document instanceof UserInterface ) { $ repository = $ args -> getDocumentManager ( ) -> getRepository ( 'Organizations\Entity\Organization' ) ; $ userId = $ document -> getId ( ) ; $ reference = new OrganizationReference ( $ userId , $ repository ) ; $ document -> setOrganization ( $ reference ) ; } }

Creates and injects the organization reference to an user entity.

@param LifecycleEventArgs $args

Creates and injects the organization reference to an user entity .


protected function createSetPasswordViewModel()
    {
        $organization = $this->getOrganizationEntity();
        $result       = $this->forward()->dispatch('Auth\Controller\Password', array('action' => 'index'));
        $model        = new ViewModel(
            array(
                'organization' => $organization->getOrganizationName()->getName()
            )
        );

        if (!$result->getVariable('valid', false)) {
            $model->setVariable('form', $result->getVariable('form'));
        }

        return $model;
    }

protected function createSetPasswordViewModel ( ) { $ organization = $ this -> getOrganizationEntity ( ) ; $ result = $ this -> forward ( ) -> dispatch ( 'Auth\Controller\Password' , array ( 'action' => 'index' ) ) ; $ model = new ViewModel ( array ( 'organization' => $ organization -> getOrganizationName ( ) -> getName ( ) ) ) ; if ( ! $ result -> getVariable ( 'valid' , false ) ) { $ model -> setVariable ( 'form' , $ result -> getVariable ( 'form' ) ) ; } return $ model ; }

Creates a view model for success view script with set password form.

@return ViewModel

Creates a view model for success view script with set password form .


protected function getOrganizationEntity()
    {
        /* @var $orgRepo \Organizations\Repository\Organization */
        $orgRepo = $this->orgRepo;
        $organiationId = $this->params()->fromQuery('organization');

        $organization = $orgRepo->find($organiationId);

        return $organization;
    }

Gets the referenced organization entity.

Retrieves the identifier from the requests' query params.

@return \Organizations\Entity\OrganizationInterface

Gets the referenced organization entity .


protected function createErrorViewModel($message)
    {
        /* @var $response \Zend\Http\Response */
        $response = $this->getResponse();
        $response->setStatusCode(500);

        $model = new ViewModel(array('message' => $message));
        $model->setTemplate('organizations/error/invite');

        return $model;
    }

Creates a view model for the error page view script.

Sets the response status code to 500 (indicating an internal error).

@param string $message

@return ViewModel

Creates a view model for the error page view script .


public function add($file, $params = 'footer', $onUnknownExtension = false)
    {
        RoumenAsset::add($this->elixir($file), $params, $onUnknownExtension);
    }

public function add ( $ file , $ params = 'footer' , $ onUnknownExtension = false ) { RoumenAsset :: add ( $ this -> elixir ( $ file ) , $ params , $ onUnknownExtension ) ; }

Add the asset using our version of the exlixer loader.

@param string $file
@param string $params
@param bool   $onUnknownExtension

@return void

Add the asset using our version of the exlixer loader .


public function reverseStylesOrder($params = 'footer')
    {
        if (isset(RoumenAsset::$scripts[$params])) {
            RoumenAsset::$scripts[$params] = array_reverse(RoumenAsset::$scripts[$params], true);
        }
    }

public function reverseStylesOrder ( $ params = 'footer' ) { if ( isset ( RoumenAsset :: $ scripts [ $ params ] ) ) { RoumenAsset :: $ scripts [ $ params ] = array_reverse ( RoumenAsset :: $ scripts [ $ params ] , true ) ; } }

Reverse the order of scripts.

@param string $params

@return void


public function addFirst($file, $params = 'footer', $onUnknownExtension = false)
    {
        RoumenAsset::addFirst($this->elixir($file), $params, $onUnknownExtension);
    }

public function addFirst ( $ file , $ params = 'footer' , $ onUnknownExtension = false ) { RoumenAsset :: addFirst ( $ this -> elixir ( $ file ) , $ params , $ onUnknownExtension ) ; }

Add the asset first using our version of the exliser loader.

@param string $file
@param string $params
@param bool   $onUnknownExtension

@return return string

Add the asset first using our version of the exliser loader .


public function addAfter($file1, $file2, $params = 'footer', $onUnknownExtension = false)
    {
        RoumenAsset::addAfter($this->elixir($file1), $this->elixir($file2), $params, $onUnknownExtension);
    }

public function addAfter ( $ file1 , $ file2 , $ params = 'footer' , $ onUnknownExtension = false ) { RoumenAsset :: addAfter ( $ this -> elixir ( $ file1 ) , $ this -> elixir ( $ file2 ) , $ params , $ onUnknownExtension ) ; }

Add new asset after another asset in its array.

@param string       $file1
@param string       $file2
@param string|array $params
@param bool         $onUnknownExtension

@return void

Add new asset after another asset in its array .


public function addMeta($meta, $data = [])
    {
        if (is_string($meta)) {
            $meta = [$meta => $data];
        }

        foreach ($meta as $key => $data) {
            self::$meta[$key] = $data;
        }
    }

public function addMeta ( $ meta , $ data = [ ] ) { if ( is_string ( $ meta ) ) { $ meta = [ $ meta => $ data ] ; } foreach ( $ meta as $ key => $ data ) { self :: $ meta [ $ key ] = $ data ; } }


public function meta()
    {
        foreach(self::$meta as $name => $attributes) {
            echo Html::meta()
                ->name(array_has($attributes, 'config.noname') ? false : $name)
                ->addAttributes(array_except($attributes, ['config']));
            echo "\n";
        }
    }

public function meta ( ) { foreach ( self :: $ meta as $ name => $ attributes ) { echo Html :: meta ( ) -> name ( array_has ( $ attributes , 'config.noname' ) ? false : $ name ) -> addAttributes ( array_except ( $ attributes , [ 'config' ] ) ) ; echo "\n" ; } }


public function controller($file_extensions, $file)
    {
        // Only look in a single file extension folder.
        if (!is_array($file_extensions)) {
            $file_extensions = [$file_extensions];
        }

        // Replace dots with slashes.
        $file = str_replace('.', '/', $file);

        if (substr($file, -1) === '*') {
            $folder = dirname(substr($file, 0, -1));
            $base_folder = basename(substr($file, 0, -1));

            foreach ($file_extensions as $extension) {
                $extension_folder = $folder.'/'.$extension.'/'.$base_folder;
                $folder_contents = scandir(resource_path().'/views/'.$extension_folder);

                foreach ($folder_contents as $folder_file) {
                    if ($folder_file == '.' || $folder_file == '..') {
                        continue;
                    }

                    $full_path = resource_path().'/views/'.$extension_folder.'/'.$folder_file;
                    $file_name = $extension_folder.'/'.$folder_file;

                    $this->loadFile($file_name, $extension, $full_path);
                }
            }

            return;
        }

        // Go through each file extension folder.
        foreach ($file_extensions as $extension) {
            $file_name = $file.'.'.$extension;

            $local_file_path = dirname(resource_path().'/views/'.$file_name);
            $local_file_path .= '/'.$extension.'/'.basename($file_name);

            $full_path = '';

            if (env('APP_ENV') == 'local') {
                if (file_exists($local_file_path)) {
                    $full_path = $local_file_path;
                } else {
                    $full_path = public_path().'/assets/'.$file_name;
                }
            }

            $this->loadFile($file_name, $extension, $full_path);
        }
    }

Load local files for a given controller.

@param array  $file_extensions
@param string $file

@return void

Load local files for a given controller .


public function loadFile($file_name, $extension, $full_path = '')
    {
        if (array_has(config('rev-manifest', []), $file_name) || (!empty($full_path) && file_exists($full_path))) {
            if (env('APP_ASSET_INLINE', false)) {
                if (!isset($this->loaded_inline[$full_path])) {
                    $contents = file_get_contents($full_path);
                    $contents = '/* '.$file_name." */ \n\n".$contents;
                    if ($extension == 'js') {
                        $this->addScript($contents, 'inline');
                    } else {
                        $this->addStyle($contents);
                    }
                    $this->loaded_inline[$full_path] = true;
                }
            } else {
                $this->add($file_name, 'ready');
            }
        }
    }

public
function
loadFile
(
$
file_name
,
$
extension
,
$
full_path
=
''
)
{
if
(
array_has
(
config
(
'rev-manifest'
,
[
]
)
,
$
file_name
)
||
(
!
empty
(
$
full_path
)
&&
file_exists
(
$
full_path
)
)
)
{
if
(
env
(
'APP_ASSET_INLINE'
,
false
)
)
{
if
(
!
isset
(
$
this
->
loaded_inline
[
$
full_path
]
)
)
{
$
contents
=
file_get_contents
(
$
full_path
)
;
$
contents
=
'/* '
.
$
file_name
.
" */ \n\n"
.
$
contents
;
if
(
$
extension
==
'js'
)
{
$
this
->
addScript
(
$
contents
,
'inline'
)
;
}
else
{
$
this
->
addStyle
(
$
contents
)
;
}
$
this
->
loaded_inline
[
$
full_path
]
=
true
;
}
}
else
{
$
this
->
add
(
$
file_name
,
'ready'
)
;
}
}
}

Load a file.

@param string $file_name
@param string $extension
@param string $full_path

@return void


public function createQuery($params, $queryBuilder)
    {
        if ($params instanceof Parameters) {
            $value = $params->toArray();
        } else {
            $value = $params;
        }

        /*
         * if user is recruiter or admin
         * filter query based on permissions.view
         */
        $auth = $this->authService;
        $user = $auth->getUser();
        $ignored = [null,'guest',UserInterface::ROLE_USER];
        if (!in_array($user->getRole(), $ignored)) {
            $queryBuilder->field('permissions.view')->equals($user->getId());
        }

        if (isset($params['q']) && $params['q'] && $params['q'] != 'en/organizations/profile') {
            $queryBuilder->text($params['q'])->language('none');
        }

        if (!isset($value['sort'])) {
            $value['sort'] = '-date';
        }

        $queryBuilder->sort($this->filterSort($value['sort']));

        if (isset($params['type']) && $params['type'] === 'profile') {
            //@TODO: we should use aggregate query here
            $queryBuilder->field('profileSetting')
                ->in([Organization::PROFILE_ALWAYS_ENABLE,Organization::PROFILE_ACTIVE_JOBS])
            ;

            $filters = $this->getOrganizationProfileFilters($queryBuilder);
            if (count($filters) > 0) {
                $queryBuilder->field('id')->notIn($filters);
            }
        }

        return $queryBuilder;
    }

Creates a query for filtering organizations

@see \Core\Repository\Filter\AbstractPaginationQuery::createQuery()
@param $params
@param \Doctrine\ODM\MongoDB\Query\Builder $queryBuilder
@return mixed


public function process($email)
    {
        $translator = $this->getTranslator();

        if (!$this->validateEmail($email)) {
            return array(
                'ok'      => false,
                'message' => $translator->translate('Email address is invalid.')
            );
        }

        $userAndToken = $this->loadOrCreateUser($email);

        try {
            $mailer = $this->getMailerPlugin();
            $mailer('Organizations/InviteEmployee', $userAndToken, true);
        } catch (\Exception $e) {
            return array(
                'ok'      => false,
                'message' => $translator->translate(trim('Sending invitation mail failed. '.$e->getMessage()))
            );
        }

        $user = $userAndToken['user'];

        /* @var $user \Auth\Entity\User
         * @var $info \Auth\Entity\InfoInterface
         */

        $info = $user->getInfo();

        return array(
            'ok'     => true,
            'result' => array(
                'userId'    => $user->getId(),
                'userName'  => $info->getDisplayName(),
                'userEmail' => $email
            )
        );
    }

Processes the invitation of an user by an organization owner.

Validators the email address, loads or creates the user and finallly sends
the mail.

The return value is meant to be used as an array of variables passed to a
ViewModelInterface instance.

@param string $email

@return array

Processes the invitation of an user by an organization owner .


protected function validateEmail($email)
    {
        if (!$email) {
            return false;
        }

        $validator = $this->getEmailValidator();

        return $validator->isValid($email);
    }

protected function validateEmail ( $ email ) { if ( ! $ email ) { return false ; } $ validator = $ this -> getEmailValidator ( ) ; return $ validator -> isValid ( $ email ) ; }

Validates an email address.

@param string $email

@return bool


protected function loadOrCreateUser($email)
    {
        $repository = $this->getUserRepository();
        $generator  = $this->getUserTokenGenerator();

        /* @var $user \Auth\Entity\User */
        $user = $repository->findByEmail(
            $email, /*do not check isDraft flag */
            null
        );

        if (!$user) {
            $user = $repository->create();
            $user->setEmail($email)
                 ->setLogin($email)
                 ->setRole(\Auth\Entity\User::ROLE_RECRUITER)
                 ->setIsDraft(true);
            $info = $user->getInfo();
            /* @var $info \Auth\Entity\InfoInterface */
            $info->setEmail($email);
        }

        $token = $generator->generate(
            $user, /* daysToLive */
            7
        ); // will store user!

        return array('user' => $user, 'token' => $token);
    }

Loads or creates an user.

Tries to load an user from the database, and creates a new
user draft, if no user was found.
A token will be generated to authenticate this user in further interactions
(with other parts of this application).

@param string $email

@return array An array with the keys 'user' and 'token', where 'user' is an UserInterface instance and
'token' is the generated token.


protected function load()
    {
        if (null !== $this->_type) {
            return;
        }

        // Is the user the owner of the referenced organization?
        $org = $this->_repository->findByUser($this->_userId);

        if ($org) {
            $this->_type = self::TYPE_OWNER;
            $this->_organization = $org;

            return;
        }

        // Is the user employed by the referenced organization?
        $org = $this->_repository->findByEmployee($this->_userId);

        if ($org) {
            $this->_type = self::TYPE_EMPLOYEE;
            $this->_organization = $org;

            return;
        }

        // It seems the user is not associated with an organization.
        $this->_type = self::TYPE_NONE;
    }

Loads the organization from the database and sets the reference type.

Loads the organization from the database and sets the reference type .


protected function proxy($method)
    {
        if (!$this->hasAssociation()) {
            return $this;
        }

        $args = array_slice(func_get_args(), 1);

        $return = call_user_func_array(array($this->_organization, $method), $args);

        return ($return === $this->_organization) ? $this : $return;
    }

protected function proxy ( $ method ) { if ( ! $ this -> hasAssociation ( ) ) { return $ this ; } $ args = array_slice ( func_get_args ( ) , 1 ) ; $ return = call_user_func_array ( array ( $ this -> _organization , $ method ) , $ args ) ; return ( $ return === $ this -> _organization ) ? $ this : $ return ; }

Executes a proxy call to the associated organization entity.

Does nothing, if no organization is available.

Call it like:
<pre>
$this->proxy($method[, $arg1[, $arg2[, ...]]]);
</pre>

@param $method

@return self|mixed

Executes a proxy call to the associated organization entity .


public function getHiringOrganizationsCursor(OrganizationInterface $organization)
    {
        $qb = $this->createQueryBuilder();
        $qb->field('parent')->equals($organization->getId());
        $qb->field('isDraft')->equals(false);
        $q  = $qb->getQuery();
        $cursor = $q->execute();

        return $cursor;
    }

public function getHiringOrganizationsCursor ( OrganizationInterface $ organization ) { $ qb = $ this -> createQueryBuilder ( ) ; $ qb -> field ( 'parent' ) -> equals ( $ organization -> getId ( ) ) ; $ qb -> field ( 'isDraft' ) -> equals ( false ) ; $ q = $ qb -> getQuery ( ) ; $ cursor = $ q -> execute ( ) ; return $ cursor ; }

Gets a cursor for all hiring organizations.

@param OrganizationInterface $organization parent organization

@return \Doctrine\ODM\MongoDB\Cursor
@usedBy \Organizations\Entity\Organization::getHiringOrganizations()
@since 0.18

Gets a cursor for all hiring organizations .


public function findByName($name, $create = true)
    {
        $query = $this->dm->createQueryBuilder('Organizations\Entity\OrganizationName')->hydrate(false)->field('name')->equals($name)->select("_id");
        $result = $query->getQuery()->execute()->toArray(false);
        if (empty($result) && $create) {
            $repositoryNames = $this->dm->getRepository('Organizations\Entity\OrganizationName');
            $entityName = $repositoryNames->create();
            $entityName->setName($name);
            $entity = $this->create();
            $entity->setOrganizationName($entityName);
            $this->store($entity);
            $organizations = array($entity);
        } else {
            $idName = $result[0]['_id'];
            $organizations = $this->findBy(array('organizationName' => $idName));
        }
        return $organizations;
    }

public function findByName ( $ name , $ create = true ) { $ query = $ this -> dm -> createQueryBuilder ( 'Organizations\Entity\OrganizationName' ) -> hydrate ( false ) -> field ( 'name' ) -> equals ( $ name ) -> select ( "_id" ) ; $ result = $ query -> getQuery ( ) -> execute ( ) -> toArray ( false ) ; if ( empty ( $ result ) && $ create ) { $ repositoryNames = $ this -> dm -> getRepository ( 'Organizations\Entity\OrganizationName' ) ; $ entityName = $ repositoryNames -> create ( ) ; $ entityName -> setName ( $ name ) ; $ entity = $ this -> create ( ) ; $ entity -> setOrganizationName ( $ entityName ) ; $ this -> store ( $ entity ) ; $ organizations = array ( $ entity ) ; } else { $ idName = $ result [ 0 ] [ '_id' ] ; $ organizations = $ this -> findBy ( array ( 'organizationName' => $ idName ) ) ; } return $ organizations ; }

Find a organizations by an name

@param String $name
@param boolean $create
@return array


public function findByUser($userOrId)
    {
        $userId = $userOrId instanceof \Auth\Entity\UserInterface ? $userOrId->getId() : $userOrId;
        $qb     = $this->createQueryBuilder();

        /*
         * HiringOrganizations also could be associated to the user, but we
         * do not want them to be queried here, so the query needs to check the
         * "parent" field, too.
         */
//        $qb->addAnd(
//           $qb->expr()->field('user')->equals($userId)
//                      ->addOr(
//                            $qb->expr()->addOr($qb->expr()->field('parent')->exists(false))
//                                       ->addOr($qb->expr()->field('parent')->equals(null))
//           )
//        );
        $qb->addAnd($qb->expr()->field('user')->equals($userId))
           ->addAnd(
               $qb->expr()->addOr($qb->expr()->field('parent')->exists(false))
                               ->addOr($qb->expr()->field('parent')->equals(null))
           );

        $q      = $qb->getQuery();
        $entity = $q->getSingleResult();

        return $entity;
    }

Finds the main organization of an user.

@param string|UserInterface $userOrId

@return null|OrganizationInterface

Finds the main organization of an user .


public function findByEmployee($userOrId)
    {
        $userId = $userOrId instanceof \Auth\Entity\UserInterface ? $userOrId->getId() : $userOrId;

        /*
         * Employees collection is only set on main organization,
         * so here, we do not have to query the "parent" field.
         *
         * Only search for "assigned" employees.
         */
        $entity = $this->findOneBy(
            array(
            'employees.user' => new \MongoId($userId),
            'employees.status' => EmployeeInterface::STATUS_ASSIGNED
            )
        );

        return $entity;
    }

Finds the organization, an user is employed by.

@param string|UserInterface $userOrId

@return null|OrganizationInterface

Finds the organization an user is employed by .


public function createWithName($name)
    {
        $entity = parent::create();
        $repositoryNames = $this->dm->getRepository('Organizations\Entity\OrganizationName');
        $entityName = $repositoryNames->create();
        $entityName->setName($name);
        $entity->setOrganizationName($entityName);
        return $entity;
    }

public function createWithName ( $ name ) { $ entity = parent :: create ( ) ; $ repositoryNames = $ this -> dm -> getRepository ( 'Organizations\Entity\OrganizationName' ) ; $ entityName = $ repositoryNames -> create ( ) ; $ entityName -> setName ( $ name ) ; $ entity -> setOrganizationName ( $ entityName ) ; return $ entity ; }

creates a new Organization, no matter if a organization with this name already exists,
also creates a new Name, but link this Name to another OrganizationName-Link, if this Name already exists
@param $name

creates a new Organization no matter if a organization with this name already exists also creates a new Name but link this Name to another OrganizationName - Link if this Name already exists


public function findDraft($user)
    {
        if ($user instanceof UserInterface) {
            $user = $user->getId();
        }

        $document = $this->findOneBy(
            array(
            'isDraft' => true,
            'user' => $user
            )
        );

        if (!empty($document)) {
            return $document;
        }

        return null;
    }

public function findDraft ( $ user ) { if ( $ user instanceof UserInterface ) { $ user = $ user -> getId ( ) ; } $ document = $ this -> findOneBy ( array ( 'isDraft' => true , 'user' => $ user ) ) ; if ( ! empty ( $ document ) ) { return $ document ; } return null ; }

Look for an drafted Document of a given user

@param $user
@return \Organizations\Entity\Organization|null


public function init()
    {
        $this->setName('contact');

        $this->add(
            array(
                'name' => 'street',
                'options' => array(
                        'label' => /* @translate */ 'Street'
                )
            )
        );

        $this->add(
            array(
                'name' => 'houseNumber',
                'options' => array(
                        'label' => /* @translate */ 'House Number'
                )
            )
        );

        $this->add(
            array(
                'name' => 'postalcode',
                'options' => array(
                        'label' => /* @translate */ 'Postal Code'
                )
            )
        );

        $this->add(
            array(
                'name' => 'city',
                'options' => array(
                        'label' => /* @translate */ 'City'
                )
            )
        );
        $this->add(
            [
                'name' => 'country',
                'options' => [
                    'label' => /* @translate */ 'Country'
                ]
            ]
        );
        $this->add(
            array(
                'name' => 'phone',
                'options' => array(
                    'label' => /* @translate */ 'Phone'
                )
            )
        );
        $this->add(
            array(
                'name' => 'fax',
                'options' => array(
                    'label' => /* @translate */ 'Fax'
                )
            )
        );
    }

public
function
init
(
)
{
$
this
->
setName
(
'contact'
)
;
$
this
->
add
(
array
(
'name'
=>
'street'
,
'options'
=>
array
(
'label'
=>
/* @translate */
'Street'
)
)
)
;
$
this
->
add
(
array
(
'name'
=>
'houseNumber'
,
'options'
=>
array
(
'label'
=>
/* @translate */
'House Number'
)
)
)
;
$
this
->
add
(
array
(
'name'
=>
'postalcode'
,
'options'
=>
array
(
'label'
=>
/* @translate */
'Postal Code'
)
)
)
;
$
this
->
add
(
array
(
'name'
=>
'city'
,
'options'
=>
array
(
'label'
=>
/* @translate */
'City'
)
)
)
;
$
this
->
add
(
[
'name'
=>
'country'
,
'options'
=>
[
'label'
=>
/* @translate */
'Country'
]
]
)
;
$
this
->
add
(
array
(
'name'
=>
'phone'
,
'options'
=>
array
(
'label'
=>
/* @translate */
'Phone'
)
)
)
;
$
this
->
add
(
array
(
'name'
=>
'fax'
,
'options'
=>
array
(
'label'
=>
/* @translate */
'Fax'
)
)
)
;
}


public function isEmployee(UserInterface $user)
    {
        return $this->refs && in_array($user->getId(), $this->refs->getEmployeeIds());
    }

public function isEmployee ( UserInterface $ user ) { return $ this -> refs && in_array ( $ user -> getId ( ) , $ this -> refs -> getEmployeeIds ( ) ) ; }

Returns true, if a User is an employee of the organization

@param UserInterface $user

@return bool

Returns true if a User is an employee of the organization


public function updatePermissions()
    {
        if ($this->isHiringOrganization()) {
            $organization = $this->getParent();
            $owner        = $organization->getUser();

            $this->setUser($owner);
        } else {
            $organization = $this;
        }

        /* @var $employees null | ArrayCollection | \Doctrine\ODM\MongoDB\PersistentCollection */
        $employees = $organization->getEmployees();

        $perms = $this->getPermissions();

        foreach ($employees as $emp) {
            /* @var $emp \Organizations\Entity\Employee */
            $perms->grant($emp->getUser(), PermissionsInterface::PERMISSION_CHANGE, false);
        }
        $perms->build();
    }

Updates the organizationsPermissions to allow all employees to view this organization.

In case of a HiringOrganization Permissions are granted to all employees of the parent
organization.

@ODM\PreUpdate
@ODM\PrePersist
@since 0.18

Updates the organizationsPermissions to allow all employees to view this organization .


public function setOrganizationName(OrganizationName $organizationName)
    {
        if (isset($this->organizationName)) {
            $this->organizationName->refCounterDec()->refCompanyCounterDec();
        }
        $this->organizationName = $organizationName;
        $this->organizationName->refCounterInc()->refCompanyCounterInc();
        $this->_organizationName = $organizationName->getName();

        return $this;
    }

public function setOrganizationName ( OrganizationName $ organizationName ) { if ( isset ( $ this -> organizationName ) ) { $ this -> organizationName -> refCounterDec ( ) -> refCompanyCounterDec ( ) ; } $ this -> organizationName = $ organizationName ; $ this -> organizationName -> refCounterInc ( ) -> refCompanyCounterInc ( ) ; $ this -> _organizationName = $ organizationName -> getName ( ) ; return $ this ; }

Sets the name of an organization

@param OrganizationName $organizationName

@return $this


public function setPermissions(PermissionsInterface $permissions)
    {
        // Assure the user has always all rights.
        if ($this->user) {
            $permissions->grant($this->user, Permissions::PERMISSION_ALL);
        }
        $this->permissions = $permissions;

        return $this;
    }

Sets the Permissions of an Organization

@param PermissionsInterface $permissions

@return $this


public function getImage($key = ImageSet::ORIGINAL)
    {
        if (is_bool($key)) {
            $key = $key ? ImageSet::THUMBNAIL : ImageSet::ORIGINAL;
        }

        return $this->getImages()->get($key, false) ?: $this->image;
    }

public function getImage ( $ key = ImageSet :: ORIGINAL ) { if ( is_bool ( $ key ) ) { $ key = $ key ? ImageSet :: THUMBNAIL : ImageSet :: ORIGINAL ; } return $ this -> getImages ( ) -> get ( $ key , false ) ? : $ this -> image ; }

Gets the Logo of an organization

@param string|bool $key Key of the image to get.
If true: get Thumbnail
If false: get Original

@return OrganizationImage
@deprecated since 0.29; use $this->getImages()->get()
@since 0.29 modified to return images from the image set for compatibility reasons


public function setContact(EntityInterface $contact = null)
    {
        if (!$contact instanceof OrganizationContact) {
            $contact = new OrganizationContact($contact);
        }
        $this->contact = $contact;

        return $this;
    }

public function setContact ( EntityInterface $ contact = null ) { if ( ! $ contact instanceof OrganizationContact ) { $ contact = new OrganizationContact ( $ contact ) ; } $ this -> contact = $ contact ; return $ this ; }

Sets the Contact Data of an organization

@param EntityInterface $contact

@return $this


public function getEmployees()
    {
        if ($this->isHiringOrganization()) {
            // Always return empty list, as we never have employees in this case.
            return new ArrayCollection();
        }

        if (!$this->employees) {
            $this->setEmployees(new ArrayCollection());
        }

        return $this->employees;
    }

Gets the list of employees

@return ArrayCollection|Collection


public function getEmployee($userOrId)
    {
        $employees = $this->getEmployees();
        $userId    = $userOrId instanceof \Auth\Entity\UserInterface ? $userOrId->getId() : $userOrId;

        foreach ($employees as $employee) {
            if ($employee->getUser()->getId() == $userId) {
                return $employee;
            }
        }

        return null;
    }

public function getEmployee ( $ userOrId ) { $ employees = $ this -> getEmployees ( ) ; $ userId = $ userOrId instanceof \ Auth \ Entity \ UserInterface ? $ userOrId -> getId ( ) : $ userOrId ; foreach ( $ employees as $ employee ) { if ( $ employee -> getUser ( ) -> getId ( ) == $ userId ) { return $ employee ; } } return null ; }

Gets an employee by User or ID.

@param UserInterface|string $userOrId

@return mixed|null


public function getEmployeesByRole($role)
    {
        $employees = new ArrayCollection();

        /* @var \Organizations\Entity\Employee $employee */
        foreach ($this->getEmployees() as $employee) {
            if ($role === $employee->getRole()) {
                $employees->add($employee);
            }
        }

        return $employees;
    }

Gets a list of Employees by a user role

@param string $role

@return ArrayCollection


public function setCreationOptions(array $options=null)
    {
        if (!isset($options['user']) || !$options['user'] instanceof UserInterface) {
            throw new \InvalidArgumentException('An user interface is required!');
        }

        if (!isset($options['token']) || !is_string($options['token'])) {
            $options['token'] = false;
        }

        if (!isset($options['template']) || !is_string($options['template'])) {
            $options['template'] = 'organizations/mail/invite-employee';
        }

        $this->options = $options;
    }

public
function
setCreationOptions
(
array
$
options
=
)
{
if
(
!
isset
(
$
options
[
'user'
]
)
||
!
$
options
[
'user'
]
instanceof
UserInterface
)
{
throw
new
\
InvalidArgumentException
(
'An user interface is required!'
)
;
}
if
(
!
isset
(
$
options
[
'token'
]
)
||
!
is_string
(
$
options
[
'token'
]
)
)
{
$
options
[
'token'
]
=
false
;
}
if
(
!
isset
(
$
options
[
'template'
]
)
||
!
is_string
(
$
options
[
'template'
]
)
)
{
$
options
[
'template'
]
=
'organizations/mail/invite-employee'
;
}
$
this
->
options
=
$
options
;
}

Sets creation options.

@param array $options

@return void
@throws \InvalidArgumentException


public function init()
    {
        $this->setName('employees');

        $this->add(
            array(
            'name' => 'inviteemployee',
            'type' => 'Organizations/InviteEmployeeBar',
            'options' => [
                'description' => /*@translate*/ 'Invite an employee via email address.',
            ]
            )
        );

        $this->add(
            array(

            'type' => 'Collection',
            'name' => 'employees',
            'options' => array(
                'count' => 0,
                'should_create_template' => true,
                'use_labeled_items' => false,
                'allow_add' => true,
                'allow_remove' => true,
                'renderFieldset' => true,
                'target_element' => array(
                    'type' => 'Organizations/EmployeeFieldset'
                )
            ),
            )
        );
    }

public
function
init
(
)
{
$
this
->
setName
(
'employees'
)
;
$
this
->
add
(
array
(
'name'
=>
'inviteemployee'
,
'type'
=>
'Organizations/InviteEmployeeBar'
,
'options'
=>
[
'description'
=>
/*@translate*/
'Invite an employee via email address.'
,
]
)
)
;
$
this
->
add
(
array
(
'type'
=>
'Collection'
,
'name'
=>
'employees'
,
'options'
=>
array
(
'count'
=>
0
,
'should_create_template'
=>
true
,
'use_labeled_items'
=>
false
,
'allow_add'
=>
true
,
'allow_remove'
=>
true
,
'renderFieldset'
=>
true
,
'target_element'
=>
array
(
'type'
=>
'Organizations/EmployeeFieldset'
)
)
,
)
)
;
}


protected function getFormular($organization)
    {
        /* @var $container \Organizations\Form\Organizations */
        //$services  = $this->serviceLocator;
        $forms     = $this->formManager;
        $container = $forms->get(
            'Organizations/Form',
            array(
            'mode' => $organization->getId() ? 'edit' : 'new'
            )
        );
        $container->setEntity($organization);
        $container->setParam('id', $organization->getId());
//        $container->setParam('applyId',$job->applyId);

        if ('__my__' != $this->params('id', '')) {
            $container->disableForm('employeesManagement')
                        ->disableForm('workflowSettings');
        } else {
            $container ->disableForm('organizationLogo')
                        ->disableForm('descriptionForm');
        }
        return $container;
    }

Gets the organization form container.

@param \Organizations\Entity\OrganizationInterface $organization

@return \Organizations\Form\Organizations


public function getUri(OrganizationImage $image)
    {
        if ($this->options->getEnabled()) {
            return sprintf('%s/%s', $this->options->getUriPath(), $this->getImageSubPath($image));
        }

        return $image->getUri();
    }

public function getUri ( OrganizationImage $ image ) { if ( $ this -> options -> getEnabled ( ) ) { return sprintf ( '%s/%s' , $ this -> options -> getUriPath ( ) , $ this -> getImageSubPath ( $ image ) ) ; } return $ image -> getUri ( ) ; }

Returns image URI

@param OrganizationImage $image
@return string


public function store(OrganizationImage $image)
    {
        $resource = $image->getResource();
        $path = $this->getImagePath($image);
        $this->createDirectoryRecursively(dirname($path));
        file_put_contents($path, $resource);
    }

public function store ( OrganizationImage $ image ) { $ resource = $ image -> getResource ( ) ; $ path = $ this -> getImagePath ( $ image ) ; $ this -> createDirectoryRecursively ( dirname ( $ path ) ) ; file_put_contents ( $ path , $ resource ) ; }

Store an image as a file in a file system

@param OrganizationImage $image


public function extract($object)
    {
        $result = array();
        foreach (self::getReflProperties($object) as $property) {
            $propertyName = $property->getName();
            if (!$this->filterComposite->filter($propertyName)) {
                continue;
            }
            $getter = 'get' . ucfirst($propertyName);
            $value = method_exists($object, $getter)
                   ? $object->$getter()
                   : $property->getValue($object);

            $result[$propertyName] = $this->extractValue($propertyName, $value);
        }

        return $result;
    }

public function extract ( $ object ) { $ result = array ( ) ; foreach ( self :: getReflProperties ( $ object ) as $ property ) { $ propertyName = $ property -> getName ( ) ; if ( ! $ this -> filterComposite -> filter ( $ propertyName ) ) { continue ; } $ getter = 'get' . ucfirst ( $ propertyName ) ; $ value = method_exists ( $ object , $ getter ) ? $ object -> $ getter ( ) : $ property -> getValue ( $ object ) ; $ result [ $ propertyName ] = $ this -> extractValue ( $ propertyName , $ value ) ; } return $ result ; }

Extract values from an object

@param  object $object
@return array


public function hydrateValue($name, $value, $data = null)
    {
        if ($this->hasStrategy($name)) {
            $strategy = $this->getStrategy($name);
            $value = $strategy->hydrate($value, $this->data, $this->object);
        }
        return $value;
    }

public function hydrateValue ( $ name , $ value , $ data = null ) { if ( $ this -> hasStrategy ( $ name ) ) { $ strategy = $ this -> getStrategy ( $ name ) ; $ value = $ strategy -> hydrate ( $ value , $ this -> data , $ this -> object ) ; } return $ value ; }

Converts a value for hydration. If no strategy exists the plain value is returned.

@param string $name The name of the strategy to use.
@param mixed $value The value that should be converted.
@param array $data The whole data is optionally provided as context.
@return mixed

Converts a value for hydration . If no strategy exists the plain value is returned .


public function checkCreatePermission(AssertionEvent $e)
    {
        /* @var $role \Auth\Entity\User
         * @var $organization \Organizations\Entity\OrganizationReference
         */
        $role = $e->getRole();

        if (!$role instanceof UserInterface) {
            return false;
        }

        $organization = $role->getOrganization();

        if (!$organization->hasAssociation()
            || $organization->isOwner()
        ) {
            return true;
        }

        $employees = $organization->getEmployees();

        foreach ($employees as $emp) {
            /* @var $emp \Organizations\Entity\EmployeeInterface */
            if ($emp->getUser()->getId() == $role->getId()
                && $emp->getPermissions()->isAllowed(EmployeePermissionsInterface::JOBS_CREATE)
            ) {
                return true;
            }
        }

        return false;
    }

Checks if the user may create jobs according to the organization permissions.

@param AssertionEvent $e

@return bool

Checks if the user may create jobs according to the organization permissions .


protected function configureForm($form, AbstractOptions $options)
    {
        $size = $options->getCompanyLogoMaxSize();
        $type = $options->getCompanyLogoMimeType();

        $form->get($this->fileName)->setViewHelper('formImageUpload')
            ->setMaxSize($size)
            ->setAllowedTypes($type)
            ->setForm($form);

        $form->setIsDescriptionsEnabled(true);
        $form->setDescription(
            /*@translate*/ 'Choose a Logo. This logo will be shown in the job opening and the application form.'
        );

        //$form->setHydrator(new ImageHydrator());
    }

Configure the Form width Options

@param \Core\Form\Form $form
@param AbstractOptions $options


public function ensureCorrectOrderNumber($orderNumber)
    {
        if (strlen($orderNumber) > self::ORDER_NUMBER_MAXIMUM_LENGHT) {
            throw new LogicException('Payment number can\'t have more than 12 characters');
        }

        // add 0 to the left in case length of the order number is less than 4
        $orderNumber = str_pad($orderNumber, self::ORDER_NUMBER_MINIMUM_LENGTH,
            '0', STR_PAD_LEFT);

        if (!preg_match('/^[0-9]{4}[a-z0-9]{0,12}$/i', $orderNumber)) {
            throw new LogicException('The payment gateway doesn\'t allow order numbers with this format.');
        }

        return $orderNumber;
    }

Validate the order number passed to the bank. it needs to pass the
following test

- Must be between 4 and 12 characters
- We complete with 0 to the left in case length or the number is lower
than 4 in order to make the integration easier
- Four first characters must be digits
- Following eight can be digits or characters which ASCII numbers are:
- between 65 and 90 ( A - Z)
- between 97 and 122 ( a - z )

If the test pass, orderNumber will be returned. if not, a Exception will be thrown

@param string $orderNumber

@return string

Validate the order number passed to the bank . it needs to pass the following test


private function encrypt_3DES($merchantOrder, $key)
    {

        $ciphertext = null;
        if ( function_exists( 'mcrypt_encrypt' ) && version_compare(phpversion(), '7.1', '<')  ) {
            // default IV
            $bytes = array(0,0,0,0,0,0,0,0); //byte [] IV = {0, 0, 0, 0, 0, 0, 0, 0}
            $iv = implode(array_map("chr", $bytes));
            $ciphertext = mcrypt_encrypt(MCRYPT_3DES, $key, $merchantOrder, MCRYPT_MODE_CBC, $iv);

        } elseif(function_exists( 'openssl_encrypt' ) && version_compare(phpversion(), '7.1', '>=') ) {
            $l = ceil(strlen($merchantOrder) / 8) * 8;
            $ciphertext = substr(openssl_encrypt($merchantOrder . str_repeat("\0", $l - strlen($merchantOrder)), 'des-ede3-cbc', $key, OPENSSL_RAW_DATA, "\0\0\0\0\0\0\0\0"), 0, $l);
        }

        return $ciphertext;
    }

private
function
encrypt_3DES
(
$
merchantOrder
,
$
key
)
{
$
ciphertext
=
;
if
(
function_exists
(
'mcrypt_encrypt'
)
&&
version_compare
(
phpversion
(
)
,
'7.1'
,
'<'
)
)
{
// default IV
$
bytes
=
array
(
0
,
0
,
0
,
0
,
0
,
0
,
0
,
0
)
;
//byte [] IV = {0, 0, 0, 0, 0, 0, 0, 0}
$
iv
=
implode
(
array_map
(
"chr"
,
$
bytes
)
)
;
$
ciphertext
=
mcrypt_encrypt
(
MCRYPT_3DES
,
$
key
,
$
merchantOrder
,
MCRYPT_MODE_CBC
,
$
iv
)
;
}
elseif
(
function_exists
(
'openssl_encrypt'
)
&&
version_compare
(
phpversion
(
)
,
'7.1'
,
'>='
)
)
{
$
l
=
ceil
(
strlen
(
$
merchantOrder
)
/
8
)
*
8
;
$
ciphertext
=
substr
(
openssl_encrypt
(
$
merchantOrder
.
str_repeat
(
"\0"
,
$
l
strlen
(
$
merchantOrder
)
)
,
'des-ede3-cbc'
,
$
key
,
OPENSSL_RAW_DATA
,
"\0\0\0\0\0\0\0\0"
)
,
0
,
$
l
)
;
}
return
$
ciphertext
;
}

3DES Function provided by Redsys

@param string $merchantOrder
@param string $key

@return string


function createMerchantSignatureNotif($key, $data)
    {
        $key = $this->decodeBase64($key);
        $decodec = $this->base64_url_decode($data);
        $orderData = json_decode($decodec, true);
        $key = $this->encrypt_3DES($orderData['Ds_Order'], $key);
        $res = $this->mac256($data, $key);

        return $this->base64_url_encode($res);
    }

function createMerchantSignatureNotif ( $ key , $ data ) { $ key = $ this -> decodeBase64 ( $ key ) ; $ decodec = $ this -> base64_url_decode ( $ data ) ; $ orderData = json_decode ( $ decodec , true ) ; $ key = $ this -> encrypt_3DES ( $ orderData [ 'Ds_Order' ] , $ key ) ; $ res = $ this -> mac256 ( $ data , $ key ) ; return $ this -> base64_url_encode ( $ res ) ; }

builds signature from the data sent by Redsys in the reply

@param $key
@param $data
@return string


public function validateNotificationSignature(array $notification)
    {
        $notification = ArrayObject::ensureArrayObject($notification);
        $notification->validateNotEmpty('Ds_Signature');
        $notification->validateNotEmpty('Ds_MerchantParameters');
        $data = $notification["Ds_MerchantParameters"];

        $key = $this->options['secret_key'];
        $signedResponse = $this->createMerchantSignatureNotif($key, $data);

        return $signedResponse == $notification['Ds_Signature'];
    }

public function validateNotificationSignature ( array $ notification ) { $ notification = ArrayObject :: ensureArrayObject ( $ notification ) ; $ notification -> validateNotEmpty ( 'Ds_Signature' ) ; $ notification -> validateNotEmpty ( 'Ds_MerchantParameters' ) ; $ data = $ notification [ "Ds_MerchantParameters" ] ; $ key = $ this -> options [ 'secret_key' ] ; $ signedResponse = $ this -> createMerchantSignatureNotif ( $ key , $ data ) ; return $ signedResponse == $ notification [ 'Ds_Signature' ] ; }

Validates notification sent by Redsys when it receives the payment

@param array $notification

@return bool


public function sign(array $params)
    {
        $base64DecodedKey = base64_decode($this->options['secret_key']);
        $key = $this->encrypt_3DES($params['Ds_Merchant_Order'],
            $base64DecodedKey);

        $res = $this->mac256(
            $this->createMerchantParameters($params),
            $key
        );

        return base64_encode($res);
    }

public function sign ( array $ params ) { $ base64DecodedKey = base64_decode ( $ this -> options [ 'secret_key' ] ) ; $ key = $ this -> encrypt_3DES ( $ params [ 'Ds_Merchant_Order' ] , $ base64DecodedKey ) ; $ res = $ this -> mac256 ( $ this -> createMerchantParameters ( $ params ) , $ key ) ; return base64_encode ( $ res ) ; }

Sing request sent to Gateway

@param array $params

@return string


public function request( $method, $uri = '', array $options = [] )
    {
        //
        // Add authentication options
        //

        // Username and password
        if (
            !empty( $this->authentication_options['username'] )
            && !empty( $this->authentication_options['password'] )
        ) {
            $options['auth'] = [
                $this->authentication_options['username'],
                $this->authentication_options['password'],
            ];
        }
        // HTTP token
        else if ( !empty( $this->authentication_options['http_token'] ) ) {
            $options['headers']['Authorization']
                = 'Token token=' . $this->authentication_options['http_token'];
        }
        // OAuth2 token
        else if ( !empty( $this->authentication_options['oauth2_token'] ) ) {
            $options['headers']['Authorization']
                = 'Bearer ' . $this->authentication_options['oauth2_token'];
        }
        else {
            throw new \RuntimeException('No authentication options available');
        }

        try {
            $response = parent::request( $method, $uri, $options );
        }
        catch ( \GuzzleHttp\Exception\TransferException $e ) {
            $response = $e->getResponse();
        }

        return $response;
    }

public
function
request
(
$
method
,
$
uri
=
''
,
array
$
options
=
[
]
)
{
//
// Add authentication options
//
// Username and password
if
(
!
empty
(
$
this
->
authentication_options
[
'username'
]
)
&&
!
empty
(
$
this
->
authentication_options
[
'password'
]
)
)
{
$
options
[
'auth'
]
=
[
$
this
->
authentication_options
[
'username'
]
,
$
this
->
authentication_options
[
'password'
]
,
]
;
}
// HTTP token
else
if
(
!
empty
(
$
this
->
authentication_options
[
'http_token'
]
)
)
{
$
options
[
'headers'
]
[
'Authorization'
]
=
'Token token='
.
$
this
->
authentication_options
[
'http_token'
]
;
}
// OAuth2 token
else
if
(
!
empty
(
$
this
->
authentication_options
[
'oauth2_token'
]
)
)
{
$
options
[
'headers'
]
[
'Authorization'
]
=
'Bearer '
.
$
this
->
authentication_options
[
'oauth2_token'
]
;
}
else
{
throw
new
\
RuntimeException
(
'No authentication options available'
)
;
}
try
{
$
response
=
parent
::
request
(
$
method
,
$
uri
,
$
options
)
;
}
catch
(
\
GuzzleHttp
\
Exception
\
TransferException
$
e
)
{
$
response
=
$
e
->
getResponse
(
)
;
}
return
$
response
;
}

Overrides base class request method to automatically add authentication options to request.

Overrides base class request method to automatically add authentication options to request .


public function getTicketArticles()
    {
        $this->clearError();

        if ( empty( $this->getID() ) ) {
            return [];
        }

        $ticket_articles = $this->getClient()->resource( ResourceType::TICKET_ARTICLE )->getForTicket( $this->getID() );
        if ( !is_array($ticket_articles) ) {
            $this->setError( $ticket_articles->getError() );
            return [];
        }

        return $ticket_articles;
    }

public function getTicketArticles ( ) { $ this -> clearError ( ) ; if ( empty ( $ this -> getID ( ) ) ) { return [ ] ; } $ ticket_articles = $ this -> getClient ( ) -> resource ( ResourceType :: TICKET_ARTICLE ) -> getForTicket ( $ this -> getID ( ) ) ; if ( ! is_array ( $ ticket_articles ) ) { $ this -> setError ( $ ticket_articles -> getError ( ) ) ; return [ ] ; } return $ ticket_articles ; }

Fetches TicketArticle objects of this Ticket object.

@return Array of TicketArticle objects   Returns array of ZammadAPIClient\Resource\TicketArticle objects or an empty array.

Fetches TicketArticle objects of this Ticket object .