<?php
/*
 * Copyright (c) 2012-2016, Hofmänner New Media.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This file is part of the N2N FRAMEWORK.
 *
 * The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
 * the GNU Lesser General Public License as published by the Free Software Foundation, either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
 *
 * The following people participated in this project:
 *
 * Andreas von Burg.....: Architect, Lead Developer
 * Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
 * Thomas Günther.......: Developer, Hangar
 */
namespace n2n\impl\persistence\orm\property;

use n2n\persistence\orm\criteria\compare\CustomComparable;
use n2n\persistence\meta\data\QueryComparator;
use n2n\persistence\orm\criteria\compare\ComparisonStrategy;
use n2n\persistence\orm\criteria\CriteriaConflictException;
use n2n\persistence\orm\query\from\MetaTreePoint;
use n2n\persistence\orm\query\from\TreePath;
use n2n\util\type\ValueIncompatibleWithConstraintsException;
use n2n\persistence\orm\property\EntityProperty;
use n2n\persistence\orm\criteria\compare\QueryComparatorBuilder;
use n2n\util\ex\IllegalStateException;
use n2n\util\type\TypeUtils;

class EmbeddedCustomComparable implements CustomComparable {
	private $metaTreePoint;
	private $embeddedEntityProperty;

	public function __construct(MetaTreePoint $metaTreePoint, EmbeddedEntityProperty $embeddedEntityProperty) {
		$this->metaTreePoint = $metaTreePoint;
		$this->embeddedEntityProperty = $embeddedEntityProperty;
	}
	/**
	 * @return MetaTreePoint
	 */
	public function getMetaTreePoint() {
		return $this->metaTreePoint;
	}
	/**
	 * @return EmbeddedEntityProperty
	 */
	public function getEmbeddedEntityProperty() {
		return $this->embeddedEntityProperty;
	}
	/* (non-PHPdoc)
	 * @see \n2n\persistence\orm\criteria\compare\CustomComparable::compareWithValue()
	 */
	public function compareWithValue(QueryComparator $queryComparator, $operator, $object) {
		if ($object !== null && !is_a($object, $this->embeddedEntityProperty->getTargetClass()->getName())) {
			throw new CriteriaConflictException('Type ' . $this->embeddedEntityProperty->getTargetClass()->getName()
					. ' required. Given: ' . TypeUtils::getTypeInfo($object));
		}

		$queryComparator = $queryComparator->andGroup();
		foreach ($this->embeddedEntityProperty->getEntityProperties() as $entityProperty) {
			$this->applyComparisonWithValue($queryComparator, $object, $entityProperty, $operator);
		}
	}

	private function applyComparisonWithValue(QueryComparator $queryComparator, $object, EntityProperty $entityProperty, $operator) {
		$propertyComparisonStrategy = $this->metaTreePoint->requestPropertyComparisonStrategy(new TreePath(array($entityProperty->getName())));
		$propertyValue = null;
		if ($object !== null) {
			$propertyValue = $entityProperty->readValue($object);
		}

		$previousE = null;
		try {
			QueryComparatorBuilder::applyPropertyValueComparison($queryComparator, $propertyComparisonStrategy, $operator, $propertyValue, true);
			return;
		} catch (ValueIncompatibleWithConstraintsException $e) {
			$previousE = $e;
		} catch (CriteriaConflictException $e) {
			$previousE = $e;
		}

		throw new CriteriaConflictException('Property ' . $entityProperty->toPropertyString() . ' can not be compared with value: <'
				. TypeUtils::getTypeInfo($propertyValue) . '>');
	}
	/* (non-PHPdoc)
	 * @see \n2n\persistence\orm\criteria\compare\CustomComparable::compareWith()
	 */
	public function compareWith(QueryComparator $queryComparator, $operator, ComparisonStrategy $comparisonStrategy) {
		$customComparable = null;
		$previousE = null;
		try {
			$customComparable = $comparisonStrategy->getCustomComparable();
		} catch (IllegalStateException $e) {
			$previousE = $e;
		}

		if (!($customComparable instanceof EmbeddedCustomComparable)
				|| $this->embeddedEntityProperty->getTargetClass() != $customComparable->getEmbeddedEntityProperty()->getTargetClass()) {
			$customComparable = null;
		}

		if ($customComparable === null) {
			throw new CriteriaConflictException($this->embeddedEntityProperty->toPropertyString()
					. ' can only be compared to other embedded properties of the same type.', 0, $previousE);
		}

		foreach ($this->embeddedEntityProperty->getEntityProperties() as $entityProperty) {
			$this->applyComparison($queryComparator, $entityProperty, $operator, $customComparable);
		}
	}

	private function applyComparison(QueryComparator $queryComparator,
			EntityProperty $entityProperty, $operator, EmbeddedCustomComparable $customComparable) {
		$propertyComparisonStrategy1 = $this->metaTreePoint->requestPropertyComparisonStrategy(
				new TreePath(array($entityProperty->getName())));
		$propertyComparisonStrategy2 = $customComparable->getMetaTreePoint()->requestPropertyComparisonStrategy(
				new TreePath(array($entityProperty->getName())));

		$previousE = null;
		try {
			QueryComparatorBuilder::applyComparison($queryComparator, $propertyComparisonStrategy1, $operator, $propertyComparisonStrategy2, true);
			return;
		} catch (CriteriaConflictException $e) {
			// @todo
			throw new CriteriaConflictException('Property ' . $entityProperty->toPropertyString()
					. ' can not be compared... make better exception here');
		}
	}
}


<?php

namespace Zumba\Swivel;

use Zumba\Swivel\BucketInterface;
use Zumba\Swivel\Behavior;

class Builder implements BuilderInterface
{
    use \Psr\Log\LoggerAwareTrait;

    const DEFAULT_SLUG = '__swivel_default';
    const DEFAULT_STRATEGY = '__swivel_default_strategy';

    /**
     * Arguments to be passed to the behavior.
     *
     * @var array
     */
    protected $args;

    /**
     * The behavior to be executed.
     *
     * @var \Zumba\Swivel\Behavior
     */
    protected $behavior;

    /**
     * The user's Bucket.
     *
     * @var Zumba\Swivel\BucketInterface
     */
    protected $bucket;

    /**
     * Whether this feature requires a default behavior.
     *
     * @var bool
     */
    protected $defaultWaived;

    /**
     * Keys used in metrics.
     *
     * @var array
     */
    private $keys = [
        'FIRST', 'SECOND', 'THIRD', 'FOURTH', 'FIFTH',
        'SIXTH', 'SEVENTH', 'EIGHTH', 'NINTH', 'TENTH',
    ];

    /**
     * A Metrics object.
     *
     * @var \Zumba\Swivel\MetricsInterface
     */
    protected $metrics;

    /**
     * Parent Feature slug.
     *
     * @var string
     */
    protected $slug;

    /**
     * Zumba\Swivel\Builder.
     *
     * @param string          $slug
     * @param BucketInterface $bucket
     */
    public function __construct($slug, BucketInterface $bucket)
    {
        $this->slug = $slug;
        $this->bucket = $bucket;
    }

    /**
     * Add a behavior to be executed later.
     *
     * Behavior will only be added if it is enabled for the user's bucket.
     *
     * @param string $slug
     * @param mixed  $strategy
     * @param array  $args
     *
     * @return \Zumba\Swivel\BuilderInterface
     */
    public function addBehavior($slug, $strategy, array $args = [])
    {
        $behavior = $this->getBehavior($slug, $strategy);
        if ($this->bucket->enabled($behavior)) {
            $this->setBehavior($behavior, $args);
        }

        return $this;
    }

    /**
     * Add a value to be returned when the builder is executed.
     *
     * Value will only be returned if it is enabled for the user's bucket.
     *
     * @param string $slug
     * @param mixed  $value
     *
     * @return \Zumba\Swivel\BuilderInterface
     */
    public function addValue($slug, $value)
    {
        $behavior = $this->getBehavior($slug, function () use ($value) {
            return $value;
        });
        if ($this->bucket->enabled($behavior)) {
            $this->setBehavior($behavior);
        }

        return $this;
    }

    /**
     * Add a default behavior.
     *
     * Will be used if all other behaviors and values are not enabled for the user's bucket.
     *
     * @param callable $strategy
     * @param array    $args
     *
     * @return \Zumba\Swivel\BuilderInterface
     */
    public function defaultBehavior($strategy, array $args = [])
    {
        if ($this->defaultWaived) {
            $exception = new \LogicException('Defined a default behavior after `noDefault` was called.');
            $this->logger->critical('Swivel', compact('exception'));
            throw $exception;
        }
        if (!$this->behavior) {
            $this->setBehavior($this->getBehavior($strategy), $args);
        }

        return $this;
    }

    /**
     * Add a default value.
     *
     * Will be used if all other behaviors and values are not enabled for the user's bucket.
     *
     * @param mixed $value
     *
     * @return \Zumba\Swivel\BuilderInterface
     */
    public function defaultValue($value)
    {
        if ($this->defaultWaived) {
            $exception = new \LogicException('Defined a default value after `noDefault` was called.');
            $this->logger->critical('Swivel', compact('exception'));
            throw $exception;
        }
        if (!$this->behavior) {
            $callable = function () use ($value) {
                return $value;
            };
            $this->setBehavior($this->getBehavior($callable));
        }

        return $this;
    }

    /**
     * Execute the feature.
     *
     * @return mixed
     */
    public function execute()
    {
        $behavior = $this->behavior ?: $this->getBehavior(function () {
            return;
        });
        $behaviorSlug = $behavior->getSlug();

        $this->metrics && $this->startMetrics($behaviorSlug);
        $result = $behavior->execute($this->args ?: []);
        $this->metrics && $this->stopMetrics($behaviorSlug);

        return $result;
    }

    /**
     * Create and return a new Behavior.
     *
     * The $strategy parameter must be a valid callable.
     *
     * @param string   $slug
     * @param callable $strategy
     *
     * @return \Zumba\Swivel\BehaviorInterface
     */
    public function getBehavior($slug, $strategy = self::DEFAULT_STRATEGY)
    {
        $this->logger->debug('Swivel - Creating new behavior.', compact('slug'));
        if ($strategy === static::DEFAULT_STRATEGY) {
            $strategy = $slug;
            $slug = static::DEFAULT_SLUG;
        }

        if (!is_callable($strategy)) {
            if (is_string($strategy)) {
                $strategy = explode('::', $strategy);
            }
            if (!isset($strategy[0], $strategy[1]) || !method_exists($strategy[0], $strategy[1])) {
                throw new \LogicException('Invalid callable passed to Zumba\Swivel\Builder::getBehavior');
            }
            $closure = function () use ($strategy) {
                return call_user_func_array($strategy, func_get_args());
            };
            $strategy = $closure->bindTo(null, $strategy[0]);
        }
        $slug = empty($slug) ? $this->slug : $this->slug.Map::DELIMITER.$slug;

        return new Behavior($slug, $strategy, $this->logger);
    }

    /**
     * Waive the default behavior for this feature.
     *
     * @return \Zumba\Swivel\BuilderInterface
     */
    public function noDefault()
    {
        if ($this->behavior && $this->behavior->getSlug() === static::DEFAULT_SLUG) {
            $exception = new \LogicException('Called `noDefault` after a default behavior was defined.');
            $this->logger->critical('Swivel', compact('exception'));
            throw $exception;
        }
        $this->defaultWaived = true;

        return $this;
    }

    /**
     * Set the behavior and it's args.
     *
     * @param \Zumba\Swivel\Behavior $behavior
     * @param array                  $args
     */
    protected function setBehavior(Behavior $behavior, array $args = [])
    {
        $slug = $behavior->getSlug();
        $this->logger->debug('Swivel - Setting behavior.', compact('slug', 'args'));
        $this->behavior = $behavior;
        $this->args = $args;
    }

    /**
     * Set a metrics object.
     *
     * @param \Zumba\Swivel\MetricsInterface $metrics
     */
    public function setMetrics(MetricsInterface $metrics)
    {
        $this->metrics = $metrics;
    }

    /**
     * Start collecting metrics about this feature.
     *
     * @param string $behaviorSlug
     */
    protected function startMetrics($behaviorSlug)
    {
        $metrics = $this->metrics;
        $bucketIndex = $this->bucket->getIndex();

        // Increment counters
        $metrics->increment('Features', $behaviorSlug);
        $metrics->increment('Buckets', $this->keys[$bucketIndex - 1], $behaviorSlug);

        // Start timers
        $metrics->startTiming('Features', $behaviorSlug);
        $metrics->startMemoryProfile('Features', $behaviorSlug);
    }

    /**
     * Stop collecting metrics about this feature.
     *
     * @param string $behaviorSlug
     */
    protected function stopMetrics($behaviorSlug)
    {
        $metrics = $this->metrics;
        $metrics->endMemoryProfile('Features', $behaviorSlug);
        $metrics->endTiming('Features', $behaviorSlug);
    }
}


<?php

namespace Zumba\Swivel;

use Zumba\Swivel\MapInterface;
use Psr\Log\LoggerInterface;
use Zumba\Swivel\Logging\NullLogger;

class Bucket implements BucketInterface
{
    use \Psr\Log\LoggerAwareTrait;

    /**
     * Ordinal Bitmasks.
     */
    const FIRST = 0b0000000001;
    const SECOND = 0b0000000010;
    const THIRD = 0b0000000100;
    const FOURTH = 0b0000001000;
    const FIFTH = 0b0000010000;
    const SIXTH = 0b0000100000;
    const SEVENTH = 0b0001000000;
    const EIGHTH = 0b0010000000;
    const NINTH = 0b0100000000;
    const TENTH = 0b1000000000;
    const ALL = 0b1111111111;

    /**
     * The feature map.
     *
     * @var Zumba\Swivel\MapInterface
     */
    protected $featureMap;

    /**
     * The user's index.
     *
     * @var int Binary
     */
    protected $index;

    /**
     * Callback to handle a missing slug from Map
     *
     * @var callable
     */
    protected $callback;

    /**
     * Zumba\Swivel\Bucket.
     *
     * @param \Zumba\Swivel\MapInterface $featureMap
     * @param int|null                   $index
     * @param \Psr\Log\LoggerInterface   $logger
     */
    public function __construct(
        MapInterface $featureMap,
        $index = null,
        LoggerInterface $logger = null,
        callable $callback = null
    ) {
        $this->setLogger($logger ?: new NullLogger());
        $this->featureMap = $featureMap;
        $this->index = $index === null ? $this->randomIndex() : $index;
        $this->callback = !is_null($callback) ? $callback : function () {
        };
    }

    /**
     * Check if a behavior is enabled for a particular context/bucket combination.
     *
     * @param \Zumba\Swivel\BehaviorInterface $behavior
     *
     * @return bool
     *
     * @see \Zumba\Swivel\BucketInterface
     */
    public function enabled(BehaviorInterface $behavior)
    {
        $slug = $behavior->getSlug();

        if (!$this->featureMap->slugExists($slug)) {
            call_user_func($this->callback, $slug);
        }
        return $this->featureMap->enabled($slug, $this->index);
    }

    /**
     * Get the bucket index.
     *
     * Useful for metrics.
     *
     * @return int
     */
    public function getIndex()
    {
        return $this->index;
    }

    /**
     * Get a random index.
     *
     * @return int
     */
    protected function randomIndex()
    {
        return mt_rand(1, 10);
    }
}


<?php

namespace Zumba\Swivel;

class Behavior implements BehaviorInterface
{
    use \Psr\Log\LoggerAwareTrait;

    /**
     * Fully qualified feature slug.
     *
     * E.g. "Feature.New.VersionA"
     *
     * @var string
     */
    protected $slug;

    /**
     * The strategy to be executed.
     *
     * @var callable
     */
    protected $strategy;

    /**
     * Zumba\Swivel\Behavior.
     *
     * @param string   $slug
     * @param callable $strategy
     */
    public function __construct($slug, callable $strategy)
    {
        $this->slug = $slug;
        $this->strategy = $strategy;
    }

    /**
     * Execute the behavior's callable and return the result.
     *
     * @param array $args
     *
     * @return mixed
     *
     * @see \Zumba\Swivel\BehaviorInterface
     */
    public function execute(array $args = [])
    {
        $slug = $this->slug;
        if ($this->logger) {
            $this->logger->debug('Swivel - Executing behavior.', compact('slug', 'args'));
        }

        return call_user_func_array($this->strategy, $args);
    }

    /**
     * Get the behavior's slug.
     *
     * @return string
     *
     * @see \Zumba\Swivel\BehaviorInterface
     */
    public function getSlug()
    {
        return $this->slug;
    }
}


<?php

namespace Collection;

use Countable;
use ArrayAccess;
use ArrayIterator;
use CachingIterator;
use JsonSerializable;
use IteratorAggregate;
use InvalidArgumentException;
use Collection\Traits\Macroable;
use Collection\Contracts\Jsonable;
use Collection\Contracts\Arrayable;

class Collection implements ArrayAccess, Arrayable, Countable, IteratorAggregate, Jsonable, JsonSerializable
{
    use Macroable;

    /**
     * The items contained in the collection.
     *
     * @var array
     */
    protected $items = [];

    /**
     * Create a new collection.
     *
     * @param  mixed $items
     *
     * @return void
     */
    public function __construct($items = [])
    {
        $this->items = is_array($items) ? $items : $this->getArrayableItems($items);
    }

    /**
     * Create a new collection instance if the value isn't one already.
     *
     * @param  mixed $items
     *
     * @return static
     */
    public static function make($items = [])
    {
        return new static($items);
    }

    /**
     * Get all of the items in the collection.
     *
     * @return array
     */
    public function all()
    {
        return $this->items;
    }

    /**
     * Get the average value of a given key.
     *
     * @param  string|null $key
     *
     * @return mixed
     */
    public function avg($key = null)
    {
        if ($count = $this->count()) {
            return $this->sum($key) / $count;
        }
    }

    /**
     * Alias for the "avg" method.
     *
     * @param  string|null $key
     *
     * @return mixed
     */
    public function average($key = null)
    {
        return $this->avg($key);
    }

    /**
     * Collapse the collection of items into a single array.
     *
     * @return static
     */
    public function collapse()
    {
        return new static(Arr::collapse($this->items));
    }

    /**
     * Determine if an item exists in the collection.
     *
     * @param  mixed $key
     * @param  mixed $value
     *
     * @return bool
     */
    public function contains($key, $value = null)
    {
        if (func_num_args() == 2) {
            return $this->contains(function ($k, $item) use ($key, $value) {
                return data_get($item, $key) == $value;
            });
        }

        if ($this->useAsCallable($key)) {
            return !is_null($this->first($key));
        }

        return in_array($key, $this->items);
    }

    /**
     * Get the items in the collection that are not present in the given items.
     *
     * @param  mixed $items
     *
     * @return static
     */
    public function diff($items)
    {
        return new static(array_diff($this->items, $this->getArrayableItems($items)));
    }

    /**
     * Execute a callback over each item.
     *
     * @param  callable $callback
     *
     * @return $this
     */
    public function each(callable $callback)
    {
        foreach ($this->items as $key => $item) {
            if ($callback($item, $key) === false) {
                break;
            }
        }

        return $this;
    }

    /**
     * Create a new collection consisting of every n-th element.
     *
     * @param  int $step
     * @param  int $offset
     *
     * @return static
     */
    public function every($step, $offset = 0)
    {
        $new = [];

        $position = 0;

        foreach ($this->items as $key => $item) {
            if ($position % $step === $offset) {
                $new[] = $item;
            }

            $position++;
        }

        return new static($new);
    }

    /**
     * Get all items except for those with the specified keys.
     *
     * @param  mixed $keys
     *
     * @return static
     */
    public function except($keys)
    {
        $keys = is_array($keys) ? $keys : func_get_args();

        return new static(Arr::except($this->items, $keys));
    }

    /**
     * Fetch a nested element of the collection.
     *
     * @param  string $key
     *
     * @return static
     *
     * @deprecated since version 5.1. Use pluck instead.
     */
    public function fetch($key)
    {
        return new static(Arr::fetch($this->items, $key));
    }

    /**
     * Run a filter over each of the items.
     *
     * @param  callable|null $callback
     *
     * @return static
     */
    public function filter(callable $callback = null)
    {
        if ($callback) {
            return new static(array_filter($this->items, $callback));
        }

        return new static(array_filter($this->items));
    }

    /**
     * Filter items by the given key value pair.
     *
     * @param  string $key
     * @param  mixed  $value
     * @param  bool   $strict
     *
     * @return static
     */
    public function where($key, $value, $strict = true)
    {
        return $this->filter(function ($item) use ($key, $value, $strict) {
            return $strict ? data_get($item, $key) === $value
                : data_get($item, $key) == $value;
        });
    }

    /**
     * Filter items by the given key value pair using loose comparison.
     *
     * @param  string $key
     * @param  mixed  $value
     *
     * @return static
     */
    public function whereLoose($key, $value)
    {
        return $this->where($key, $value, false);
    }

    /**
     * Get the first item from the collection.
     *
     * @param  callable|null $callback
     * @param  mixed         $default
     *
     * @return mixed
     */
    public function first(callable $callback = null, $default = null)
    {
        if (is_null($callback)) {
            return count($this->items) > 0 ? reset($this->items) : null;
        }

        return Arr::first($this->items, $callback, $default);
    }

    /**
     * Get a flattened array of the items in the collection.
     *
     * @return static
     */
    public function flatten()
    {
        return new static(Arr::flatten($this->items));
    }

    /**
     * Flip the items in the collection.
     *
     * @return static
     */
    public function flip()
    {
        return new static(array_flip($this->items));
    }

    /**
     * Remove an item from the collection by key.
     *
     * @param  string|array $keys
     *
     * @return $this
     */
    public function forget($keys)
    {
        foreach ((array)$keys as $key) {
            $this->offsetUnset($key);
        }

        return $this;
    }

    /**
     * Get an item from the collection by key.
     *
     * @param  mixed $key
     * @param  mixed $default
     *
     * @return mixed
     */
    public function get($key, $default = null)
    {
        if ($this->offsetExists($key)) {
            return $this->items[$key];
        }

        return value($default);
    }

    /**
     * Group an associative array by a field or using a callback.
     *
     * @param  callable|string $groupBy
     * @param  bool            $preserveKeys
     *
     * @return static
     */
    public function groupBy($groupBy, $preserveKeys = false)
    {
        $groupBy = $this->valueRetriever($groupBy);

        $results = [];

        foreach ($this->items as $key => $value) {
            $groupKey = $groupBy($value, $key);

            if (!array_key_exists($groupKey, $results)) {
                $results[$groupKey] = new static;
            }

            $results[$groupKey]->offsetSet($preserveKeys ? $key : null, $value);
        }

        return new static($results);
    }

    /**
     * Key an associative array by a field or using a callback.
     *
     * @param  callable|string $keyBy
     *
     * @return static
     */
    public function keyBy($keyBy)
    {
        $keyBy = $this->valueRetriever($keyBy);

        $results = [];

        foreach ($this->items as $item) {
            $results[$keyBy($item)] = $item;
        }

        return new static($results);
    }

    /**
     * Determine if an item exists in the collection by key.
     *
     * @param  mixed $key
     *
     * @return bool
     */
    public function has($key)
    {
        return $this->offsetExists($key);
    }

    /**
     * Concatenate values of a given key as a string.
     *
     * @param  string $value
     * @param  string $glue
     *
     * @return string
     */
    public function implode($value, $glue = null)
    {
        $first = $this->first();

        if (is_array($first) || is_object($first)) {
            return implode($glue, $this->pluck($value)->all());
        }

        return implode($value, $this->items);
    }

    /**
     * Intersect the collection with the given items.
     *
     * @param  mixed $items
     *
     * @return static
     */
    public function intersect($items)
    {
        return new static(array_intersect($this->items, $this->getArrayableItems($items)));
    }

    /**
     * Determine if the collection is empty or not.
     *
     * @return bool
     */
    public function isEmpty()
    {
        return empty($this->items);
    }

    /**
     * Determine if the given value is callable, but not a string.
     *
     * @param  mixed $value
     *
     * @return bool
     */
    protected function useAsCallable($value)
    {
        return !is_string($value) && is_callable($value);
    }

    /**
     * Get the keys of the collection items.
     *
     * @return static
     */
    public function keys()
    {
        return new static(array_keys($this->items));
    }

    /**
     * Get the last item from the collection.
     *
     * @param  callable|null $callback
     * @param  mixed         $default
     *
     * @return mixed
     */
    public function last(callable $callback = null, $default = null)
    {
        if (is_null($callback)) {
            return count($this->items) > 0 ? end($this->items) : value($default);
        }

        return Arr::last($this->items, $callback, $default);
    }

    /**
     * Get the values of a given key.
     *
     * @param  string      $value
     * @param  string|null $key
     *
     * @return static
     */
    public function pluck($value, $key = null)
    {
        return new static(Arr::pluck($this->items, $value, $key));
    }

    /**
     * Alias for the "pluck" method.
     *
     * @param  string      $value
     * @param  string|null $key
     *
     * @return static
     */
    public function lists($value, $key = null)
    {
        return $this->pluck($value, $key);
    }

    /**
     * Run a map over each of the items.
     *
     * @param  callable $callback
     *
     * @return static
     */
    public function map(callable $callback)
    {
        $keys = array_keys($this->items);

        $items = array_map($callback, $this->items, $keys);

        return new static(array_combine($keys, $items));
    }

    /**
     * Map a collection and flatten the result by a single level.
     *
     * @param  callable $callback
     *
     * @return static
     */
    public function flatMap(callable $callback)
    {
        return $this->map($callback)->collapse();
    }

    /**
     * Get the max value of a given key.
     *
     * @param  string|null $key
     *
     * @return mixed
     */
    public function max($key = null)
    {
        return $this->reduce(function ($result, $item) use ($key) {
            $value = data_get($item, $key);

            return is_null($result) || $value > $result ? $value : $result;
        });
    }

    /**
     * Merge the collection with the given items.
     *
     * @param  mixed $items
     *
     * @return static
     */
    public function merge($items)
    {
        return new static(array_merge($this->items, $this->getArrayableItems($items)));
    }

    /**
     * Get the min value of a given key.
     *
     * @param  string|null $key
     *
     * @return mixed
     */
    public function min($key = null)
    {
        return $this->reduce(function ($result, $item) use ($key) {
            $value = data_get($item, $key);

            return is_null($result) || $value < $result ? $value : $result;
        });
    }

    /**
     * Get the items with the specified keys.
     *
     * @param  mixed $keys
     *
     * @return static
     */
    public function only($keys)
    {
        $keys = is_array($keys) ? $keys : func_get_args();

        return new static(Arr::only($this->items, $keys));
    }

    /**
     * "Paginate" the collection by slicing it into a smaller collection.
     *
     * @param  int $page
     * @param  int $perPage
     *
     * @return static
     */
    public function forPage($page, $perPage)
    {
        return $this->slice(($page - 1) * $perPage, $perPage);
    }

    /**
     * Get and remove the last item from the collection.
     *
     * @return mixed
     */
    public function pop()
    {
        return array_pop($this->items);
    }

    /**
     * Push an item onto the beginning of the collection.
     *
     * @param  mixed $value
     * @param  mixed $key
     *
     * @return $this
     */
    public function prepend($value, $key = null)
    {
        $this->items = Arr::prepend($this->items, $value, $key);

        return $this;
    }

    /**
     * Push an item onto the end of the collection.
     *
     * @param  mixed $value
     *
     * @return $this
     */
    public function push($value)
    {
        $this->offsetSet(null, $value);

        return $this;
    }

    /**
     * Pulls an item from the collection.
     *
     * @param  mixed $key
     * @param  mixed $default
     *
     * @return mixed
     */
    public function pull($key, $default = null)
    {
        return Arr::pull($this->items, $key, $default);
    }

    /**
     * Put an item in the collection by key.
     *
     * @param  mixed $key
     * @param  mixed $value
     *
     * @return $this
     */
    public function put($key, $value)
    {
        $this->offsetSet($key, $value);

        return $this;
    }

    /**
     * Get one or more items randomly from the collection.
     *
     * @param  int $amount
     *
     * @return mixed
     *
     * @throws \InvalidArgumentException
     */
    public function random($amount = 1)
    {
        if ($amount > ($count = $this->count())) {
            throw new InvalidArgumentException("You requested {$amount} items, but there are only {$count} items in the collection");
        }

        $keys = array_rand($this->items, $amount);

        if ($amount == 1) {
            return $this->items[$keys];
        }

        return new static(array_intersect_key($this->items, array_flip($keys)));
    }

    /**
     * Reduce the collection to a single value.
     *
     * @param  callable $callback
     * @param  mixed    $initial
     *
     * @return mixed
     */
    public function reduce(callable $callback, $initial = null)
    {
        return array_reduce($this->items, $callback, $initial);
    }

    /**
     * Create a collection of all elements that do not pass a given truth test.
     *
     * @param  callable|mixed $callback
     *
     * @return static
     */
    public function reject($callback)
    {
        if ($this->useAsCallable($callback)) {
            return $this->filter(function ($item) use ($callback) {
                return !$callback($item);
            });
        }

        return $this->filter(function ($item) use ($callback) {
            return $item != $callback;
        });
    }

    /**
     * Reverse items order.
     *
     * @return static
     */
    public function reverse()
    {
        return new static(array_reverse($this->items));
    }

    /**
     * Search the collection for a given value and return the corresponding key if successful.
     *
     * @param  mixed $value
     * @param  bool  $strict
     *
     * @return mixed
     */
    public function search($value, $strict = false)
    {
        if (!$this->useAsCallable($value)) {
            return array_search($value, $this->items, $strict);
        }

        foreach ($this->items as $key => $item) {
            if (call_user_func($value, $item, $key)) {
                return $key;
            }
        }

        return false;
    }

    /**
     * Get and remove the first item from the collection.
     *
     * @return mixed
     */
    public function shift()
    {
        return array_shift($this->items);
    }

    /**
     * Shuffle the items in the collection.
     *
     * @return static
     */
    public function shuffle()
    {
        $items = $this->items;

        shuffle($items);

        return new static($items);
    }

    /**
     * Slice the underlying collection array.
     *
     * @param  int  $offset
     * @param  int  $length
     * @param  bool $preserveKeys
     *
     * @return static
     */
    public function slice($offset, $length = null, $preserveKeys = false)
    {
        return new static(array_slice($this->items, $offset, $length, $preserveKeys));
    }

    /**
     * Chunk the underlying collection array.
     *
     * @param  int  $size
     * @param  bool $preserveKeys
     *
     * @return static
     */
    public function chunk($size, $preserveKeys = false)
    {
        $chunks = [];

        foreach (array_chunk($this->items, $size, $preserveKeys) as $chunk) {
            $chunks[] = new static($chunk);
        }

        return new static($chunks);
    }

    /**
     * Sort through each item with a callback.
     *
     * @param  callable|null $callback
     *
     * @return static
     */
    public function sort(callable $callback = null)
    {
        $items = $this->items;

        $callback ? uasort($items, $callback) : uasort($items, function ($a, $b) {

            if ($a == $b) {
                return 0;
            }

            return ($a < $b) ? -1 : 1;
        });

        return new static($items);
    }

    /**
     * Sort the collection using the given callback.
     *
     * @param  callable|string $callback
     * @param  int             $options
     * @param  bool            $descending
     *
     * @return static
     */
    public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
    {
        $results = [];

        $callback = $this->valueRetriever($callback);

        // First we will loop through the items and get the comparator from a callback
        // function which we were given. Then, we will sort the returned values and
        // and grab the corresponding values for the sorted keys from this array.
        foreach ($this->items as $key => $value) {
            $results[$key] = $callback($value, $key);
        }

        $descending ? arsort($results, $options)
            : asort($results, $options);

        // Once we have sorted all of the keys in the array, we will loop through them
        // and grab the corresponding model so we can set the underlying items list
        // to the sorted version. Then we'll just return the collection instance.
        foreach (array_keys($results) as $key) {
            $results[$key] = $this->items[$key];
        }

        return new static($results);
    }

    /**
     * Sort the collection in descending order using the given callback.
     *
     * @param  callable|string $callback
     * @param  int             $options
     *
     * @return static
     */
    public function sortByDesc($callback, $options = SORT_REGULAR)
    {
        return $this->sortBy($callback, $options, true);
    }

    /**
     * Splice a portion of the underlying collection array.
     *
     * @param  int      $offset
     * @param  int|null $length
     * @param  mixed    $replacement
     *
     * @return static
     */
    public function splice($offset, $length = null, $replacement = [])
    {
        if (func_num_args() == 1) {
            return new static(array_splice($this->items, $offset));
        }

        return new static(array_splice($this->items, $offset, $length, $replacement));
    }

    /**
     * Get the sum of the given values.
     *
     * @param  callable|string|null $callback
     *
     * @return mixed
     */
    public function sum($callback = null)
    {
        if (is_null($callback)) {
            return array_sum($this->items);
        }

        $callback = $this->valueRetriever($callback);

        return $this->reduce(function ($result, $item) use ($callback) {
            return $result += $callback($item);
        }, 0);
    }

    /**
     * Take the first or last {$limit} items.
     *
     * @param  int $limit
     *
     * @return static
     */
    public function take($limit)
    {
        if ($limit < 0) {
            return $this->slice($limit, abs($limit));
        }

        return $this->slice(0, $limit);
    }

    /**
     * Transform each item in the collection using a callback.
     *
     * @param  callable $callback
     *
     * @return $this
     */
    public function transform(callable $callback)
    {
        $this->items = $this->map($callback)->all();

        return $this;
    }

    /**
     * Return only unique items from the collection array.
     *
     * @param  string|callable|null $key
     *
     * @return static
     */
    public function unique($key = null)
    {
        if (is_null($key)) {
            return new static(array_unique($this->items, SORT_REGULAR));
        }

        $key = $this->valueRetriever($key);

        $exists = [];

        return $this->reject(function ($item) use ($key, &$exists) {
            if (in_array($id = $key($item), $exists)) {
                return true;
            }

            $exists[] = $id;
        });
    }

    /**
     * Reset the keys on the underlying array.
     *
     * @return static
     */
    public function values()
    {
        return new static(array_values($this->items));
    }

    /**
     * Get a value retrieving callback.
     *
     * @param  string $value
     *
     * @return callable
     */
    protected function valueRetriever($value)
    {
        if ($this->useAsCallable($value)) {
            return $value;
        }

        return function ($item) use ($value) {
            return data_get($item, $value);
        };
    }

    /**
     * Zip the collection together with one or more arrays.
     *
     * e.g. new Collection([1, 2, 3])->zip([4, 5, 6]);
     *      => [[1, 4], [2, 5], [3, 6]]
     *
     * @param  mixed ...$items
     *
     * @return static
     */
    public function zip($items)
    {
        $arrayableItems = array_map(function ($items) {
            return $this->getArrayableItems($items);
        }, func_get_args());

        $params = array_merge([
            function () {
                return new static(func_get_args());
            },
            $this->items
        ], $arrayableItems);

        return new static(call_user_func_array('array_map', $params));
    }

    /**
     * Get the collection of items as a plain array.
     *
     * @return array
     */
    public function toArray()
    {
        return array_map(function ($value) {
            return ($value instanceof Arrayable || instance_of_laravel_arrayable($value)) ? $value->toArray() : $value;

        }, $this->items);
    }

    /**
     * Convert the object into something JSON serializable.
     *
     * @return array
     */
    public function jsonSerialize()
    {
        return $this->toArray();
    }

    /**
     * Get the collection of items as JSON.
     *
     * @param  int $options
     *
     * @return string
     */
    public function toJson($options = 0)
    {
        return json_encode($this->toArray(), $options);
    }

    /**
     * Get an iterator for the items.
     *
     * @return \ArrayIterator
     */
    public function getIterator()
    {
        return new ArrayIterator($this->items);
    }

    /**
     * Get a CachingIterator instance.
     *
     * @param  int $flags
     *
     * @return \CachingIterator
     */
    public function getCachingIterator($flags = CachingIterator::CALL_TOSTRING)
    {
        return new CachingIterator($this->getIterator(), $flags);
    }

    /**
     * Count the number of items in the collection.
     *
     * @return int
     */
    public function count()
    {
        return count($this->items);
    }

    /**
     * Determine if an item exists at an offset.
     *
     * @param  mixed $key
     *
     * @return bool
     */
    public function offsetExists($key)
    {
        return array_key_exists($key, $this->items);
    }

    /**
     * Get an item at a given offset.
     *
     * @param  mixed $key
     *
     * @return mixed
     */
    public function offsetGet($key)
    {
        return $this->items[$key];
    }

    /**
     * Set the item at a given offset.
     *
     * @param  mixed $key
     * @param  mixed $value
     *
     * @return void
     */
    public function offsetSet($key, $value)
    {
        if (is_null($key)) {
            $this->items[] = $value;
        } else {
            $this->items[$key] = $value;
        }
    }

    /**
     * Unset the item at a given offset.
     *
     * @param  string $key
     *
     * @return void
     */
    public function offsetUnset($key)
    {
        unset($this->items[$key]);
    }

    /**
     * Convert the collection to its string representation.
     *
     * @return string
     */
    public function __toString()
    {
        return $this->toJson();
    }

    /**
     * Results array of items from Collection or Arrayable.
     *
     * @param  mixed $items
     *
     * @return array
     */
    protected function getArrayableItems($items)
    {
        if ($items instanceof self) {
            return $items->all();
        } elseif (($items instanceof Arrayable || instance_of_laravel_arrayable($items))) {
            return $items->toArray();
        } elseif (($items instanceof Jsonable || instance_of_laravel_jsonable($items))) {
            return json_decode($items->toJson(), true);
        }

        return (array)$items;
    }
}


<?php

namespace Zumba\Swivel;

use Psr\Log\LoggerInterface;
use Zumba\Swivel\Logging\NullLogger;

class Map implements MapInterface
{
    use \Psr\Log\LoggerAwareTrait;

    const DELIMITER = '.';

    /**
     * Map of parsed features.
     *
     * @var array
     */
    protected $map;

    /**
     * Zumba\Swivel\Map.
     *
     * Example of $map param:
     * [
     *   'FeatureA' => [1, 2, 3, 4, 5, 6],
     *   'FeatureA.Behavior1' => [1, 2, 3],
     *   'FeatureA.Behavior2' => [4, 5, 6],
     * ]
     *
     * @param array                    $map
     * @param \Psr\Log\LoggerInterface $logger
     */
    public function __construct(array $map = [], LoggerInterface $logger = null)
    {
        $this->setLogger($logger ?: new NullLogger());
        $this->map = $this->parse($map);
    }

    /**
     * For serialization, removing logger since we can't guarantee a safe serialization and unserialization.
     *
     * @return array
     */
    public function __sleep()
    {
        return ['map'];
    }

    /**
     * Ensure a null logger is in place post unserilization so there's no issues.
     */
    public function __wakeup()
    {
        $this->setLogger(new NullLogger());
    }

    /**
     * Merge this map with another map and return a new MapInterface.
     *
     * Values in $map will be added to values in this instance.  Any number of additional maps may
     * be passed to this method, i.e. $map->merge($map2, $map3, $map4, ...);
     *
     * @param MapInterface $map
     *
     * @return MapInterface
     */
    public function add(MapInterface $map)
    {
        $combine = function ($data, $map) {
            foreach ($map as $key => $mask) {
                $data[$key] = empty($data[$key]) ? $mask : ($data[$key] | $mask);
            }

            return $data;
        };

        $maps = array_slice(func_get_args(), 1);
        $data = array_reduce($maps, $combine, $combine($this->map, $map->getMapData()));

        return new self($data, $this->logger);
    }

    /**
     * SetState.
     *
     * Support reloading class via var_export definition.
     *
     * @param array $mapData Array of logger data needed to reconsturct logger
     *
     * @return string Implementaiton of logger class to be passed to the Map class
     */
    public static function __set_state($mapData)
    {
        $map = new static($mapData['map'], $mapData['logger']);

        return $map;
    }

    /**
     * Compare $map to this instance and return a new MapInterface.
     *
     * Returned object will contain only the elements that differ between the two maps. If a feature
     * with the same key has different buckets, the buckets from the passed-in $map will be in the
     * new object.
     *
     * If this map has a logger, it will be passed to the new map.
     *
     * @param MapInterface $map
     *
     * @return MapInterface
     */
    public function diff(MapInterface $map)
    {
        $otherMapData = $map->getMapData();
        $data = array_merge(
            array_diff_assoc($this->map, $otherMapData),
            array_diff_assoc($otherMapData, $this->map)
        );

        return new self($data);
    }

    /**
     * Check if a feature slug is enabled for a particular bucket index.
     *
     * @param string $slug
     * @param int    $index
     *
     * @return bool
     *
     * @see \Zumba\Swivel\MapInterface
     */
    public function enabled($slug, $index)
    {
        $map = $this->map;
        $key = '';
        $index = (int)$index == 0 ? 0 : 1 << ($index - 1);
        foreach (explode(static::DELIMITER, $slug) as $child) {
            $key = empty($key) ? $child : $key.static::DELIMITER.$child;

            $isMissing = !$this->slugExists($key);
            $isDisabled = $isMissing ?: !((int)$map[$key] & $index);

            if ($isMissing || $isDisabled) {
                $this->logger->debug('Swivel - "'.$slug.'" is not enabled for bucket '.$index);

                return false;
            }
        }
        $this->logger->debug('Swivel - "'.$slug.'" is enabled for bucket '.$index);

        return true;
    }

    /**
     * Check if a feature slug exists in the Map.
     *
     * @param string $slug
     *
     * @return bool
     */
    public function slugExists($slug)
    {
        return isset($this->map[$slug]);
    }

    /**
     * Get the internal map array used by this map object.
     *
     * @return array
     */
    public function getMapData()
    {
        return $this->map;
    }

    /**
     * Compare $map to this instance and return a new MapInterface.
     *
     * Returned object will contain only the elements that match between the two maps. If this map
     * has a logger, it will be passed to the new map.
     *
     * @param MapInterface $map
     *
     * @return MapInterface
     */
    public function intersect(MapInterface $map)
    {
        return new self(array_intersect_assoc($this->map, $map->getMapData()), $this->logger);
    }

    /**
     * Merge this map with another map and return a new MapInterface.
     *
     * Values in $map will overwrite values in this instance.  Any number of additional maps may
     * be passed to this method, i.e. $map->merge($map2, $map3, $map4, ...);
     *
     * @param MapInterface $map
     *
     * @return MapInterface
     */
    public function merge(MapInterface $map)
    {
        $maps = array_slice(func_get_args(), 1);
        $data = array_reduce($maps, 'array_merge', array_merge($this->map, $map->getMapData()));

        return new self($data, $this->logger);
    }

    /**
     * Reduce an array of integers to a bitmask if $list is an array.
     *
     * Otherwise, this method will just return $list.
     *
     * @param mixed $list
     *
     * @return int bitmask
     */
    protected function reduceToBitmask($list)
    {
        $this->logger->debug('Swivel - reducing to bitmask.', compact('list'));

        return !is_array($list) ? $list : array_reduce($list, function ($mask, $index) {
            if ((int)$index == 0) {
                return $mask;
            }
            return $mask | (1 << ($index - 1));
        });
    }

    /**
     * Parse a human readable map into a map of bitmasks.
     *
     * @param array $map
     *
     * @return array
     */
    public function parse(array $map)
    {
        $this->logger->info('Swivel - Parsing feature map.', compact('map'));

        return array_combine(array_keys($map), array_map([$this, 'reduceToBitmask'], $map));
    }
}


<?php declare(strict_types=1);

namespace Scn\EvalancheSoapStruct\Factory;

use Scn\EvalancheSoapStruct\Struct\Generic\HashMap;
use Scn\EvalancheSoapStruct\Struct\Generic\HashMapInterface;
use Scn\EvalancheSoapStruct\Struct\Generic\HashMapItem;

/**
 * Struct Factory, creates Instances of StructInterface
 *
 * @package Scn\EvalancheSoapStruct\Factory\StructFactory
 */
final class StructFactory implements StructFactoryInterface
{
    /**
     * Creates a Instance of HashMap
     *
     * [
     *  'field_name' => 'field_value',
     *  'field_name_next' => 'field_value_next',
     * ]
     *
     * Field names can be found in your pool configuration.
     *
     * @param array $items
     * @return HashMapInterface
     */
    public static function createHashMap(array $items): HashMapInterface {
        $hashMapItems = [];

        foreach ($items as $itemKey => $itemValue) {
            $hashMapItems[] = new HashMapItem($itemKey, $itemValue);
        }

        return new HashMap($hashMapItems);
    }
}


<?php

namespace Collection;

use Collection\Traits\Macroable;

class Arr
{
    use Macroable;

    /**
     * Add an element to an array using "dot" notation if it doesn't exist.
     *
     * @param  array  $array
     * @param  string $key
     * @param  mixed  $value
     *
     * @return array
     */
    public static function add($array, $key, $value)
    {
        if (is_null(static::get($array, $key))) {
            static::set($array, $key, $value);
        }

        return $array;
    }

    /**
     * Build a new array using a callback.
     *
     * @param  array    $array
     * @param  callable $callback
     *
     * @return array
     */
    public static function build($array, callable $callback)
    {
        $results = [];

        foreach ($array as $key => $value) {
            list($innerKey, $innerValue) = call_user_func($callback, $key, $value);

            $results[$innerKey] = $innerValue;
        }

        return $results;
    }

    /**
     * Collapse an array of arrays into a single array.
     *
     * @param  array|\ArrayAccess $array
     *
     * @return array
     */
    public static function collapse($array)
    {
        $results = [];

        foreach ($array as $values) {
            if ($values instanceof Collection) {
                $values = $values->all();
            }

            $results = array_merge($results, $values);
        }

        return $results;
    }

    /**
     * Divide an array into two arrays. One with keys and the other with values.
     *
     * @param  array $array
     *
     * @return array
     */
    public static function divide($array)
    {
        return [array_keys($array), array_values($array)];
    }

    /**
     * Flatten a multi-dimensional associative array with dots.
     *
     * @param  array  $array
     * @param  string $prepend
     *
     * @return array
     */
    public static function dot($array, $prepend = '')
    {
        $results = [];

        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $results = array_merge($results, static::dot($value, $prepend . $key . '.'));
            } else {
                $results[$prepend . $key] = $value;
            }
        }

        return $results;
    }

    /**
     * Get all of the given array except for a specified array of items.
     *
     * @param  array        $array
     * @param  array|string $keys
     *
     * @return array
     */
    public static function except($array, $keys)
    {
        static::forget($array, $keys);

        return $array;
    }

    /**
     * Fetch a flattened array of a nested array element.
     *
     * @param  array  $array
     * @param  string $key
     *
     * @return array
     *
     * @deprecated since version 5.1. Use pluck instead.
     */
    public static function fetch($array, $key)
    {
        foreach (explode('.', $key) as $segment) {
            $results = [];

            foreach ($array as $value) {
                if (array_key_exists($segment, $value = (array)$value)) {
                    $results[] = $value[$segment];
                }
            }

            $array = array_values($results);
        }

        return array_values($results);
    }

    /**
     * Return the first element in an array passing a given truth test.
     *
     * @param  array    $array
     * @param  callable $callback
     * @param  mixed    $default
     *
     * @return mixed
     */
    public static function first($array, callable $callback, $default = null)
    {
        foreach ($array as $key => $value) {
            if (call_user_func($callback, $key, $value)) {
                return $value;
            }
        }

        return value($default);
    }

    /**
     * Return the last element in an array passing a given truth test.
     *
     * @param  array    $array
     * @param  callable $callback
     * @param  mixed    $default
     *
     * @return mixed
     */
    public static function last($array, callable $callback, $default = null)
    {
        return static::first(array_reverse($array), $callback, $default);
    }

    /**
     * Flatten a multi-dimensional array into a single level.
     *
     * @param  array $array
     *
     * @return array
     */
    public static function flatten($array)
    {
        $return = [];

        array_walk_recursive($array, function ($x) use (&$return) {
            $return[] = $x;
        });

        return $return;
    }

    /**
     * Remove one or many array items from a given array using "dot" notation.
     *
     * @param  array        $array
     * @param  array|string $keys
     *
     * @return void
     */
    public static function forget(&$array, $keys)
    {
        $original = &$array;

        foreach ((array)$keys as $key) {
            $parts = explode('.', $key);

            while (count($parts) > 1) {
                $part = array_shift($parts);

                if (isset($array[$part]) && is_array($array[$part])) {
                    $array = &$array[$part];
                } else {
                    $parts = [];
                }
            }

            unset($array[array_shift($parts)]);

            // clean up after each pass
            $array = &$original;
        }
    }

    /**
     * Get an item from an array using "dot" notation.
     *
     * @param  array  $array
     * @param  string $key
     * @param  mixed  $default
     *
     * @return mixed
     */
    public static function get($array, $key, $default = null)
    {
        if (is_null($key)) {
            return $array;
        }

        if (isset($array[$key])) {
            return $array[$key];
        }

        foreach (explode('.', $key) as $segment) {
            if (!is_array($array) || !array_key_exists($segment, $array)) {
                return value($default);
            }

            $array = $array[$segment];
        }

        return $array;
    }

    /**
     * Check if an item exists in an array using "dot" notation.
     *
     * @param  array  $array
     * @param  string $key
     *
     * @return bool
     */
    public static function has($array, $key)
    {
        if (empty($array) || is_null($key)) {
            return false;
        }

        if (array_key_exists($key, $array)) {
            return true;
        }

        foreach (explode('.', $key) as $segment) {
            if (!is_array($array) || !array_key_exists($segment, $array)) {
                return false;
            }

            $array = $array[$segment];
        }

        return true;
    }

    /**
     * Determines if an array is associative.
     *
     * An array is "associative" if it doesn't have sequential numerical keys beginning with zero.
     *
     * @param  array $array
     *
     * @return bool
     */
    public static function isAssoc(array $array)
    {
        $keys = array_keys($array);

        return array_keys($keys) !== $keys;
    }

    /**
     * Get a subset of the items from the given array.
     *
     * @param  array        $array
     * @param  array|string $keys
     *
     * @return array
     */
    public static function only($array, $keys)
    {
        return array_intersect_key($array, array_flip((array)$keys));
    }

    /**
     * Pluck an array of values from an array.
     *
     * @param  array             $array
     * @param  string|array      $value
     * @param  string|array|null $key
     *
     * @return array
     */
    public static function pluck($array, $value, $key = null)
    {
        $results = [];

        list($value, $key) = static::explodePluckParameters($value, $key);

        foreach ($array as $item) {
            $itemValue = data_get($item, $value);

            // If the key is "null", we will just append the value to the array and keep
            // looping. Otherwise we will key the array using the value of the key we
            // received from the developer. Then we'll return the final array form.
            if (is_null($key)) {
                $results[] = $itemValue;
            } else {
                $itemKey = data_get($item, $key);

                $results[$itemKey] = $itemValue;
            }
        }

        return $results;
    }

    /**
     * Explode the "value" and "key" arguments passed to "pluck".
     *
     * @param  string|array      $value
     * @param  string|array|null $key
     *
     * @return array
     */
    protected static function explodePluckParameters($value, $key)
    {
        $value = is_string($value) ? explode('.', $value) : $value;

        $key = is_null($key) || is_array($key) ? $key : explode('.', $key);

        return [$value, $key];
    }

    /**
     * Push an item onto the beginning of an array.
     *
     * @param  array $array
     * @param  mixed $value
     * @param  mixed $key
     *
     * @return array
     */
    public static function prepend($array, $value, $key = null)
    {
        if (is_null($key)) {
            array_unshift($array, $value);
        } else {
            $array = [$key => $value] + $array;
        }

        return $array;
    }

    /**
     * Get a value from the array, and remove it.
     *
     * @param  array  $array
     * @param  string $key
     * @param  mixed  $default
     *
     * @return mixed
     */
    public static function pull(&$array, $key, $default = null)
    {
        $value = static::get($array, $key, $default);

        static::forget($array, $key);

        return $value;
    }

    /**
     * Set an array item to a given value using "dot" notation.
     *
     * If no key is given to the method, the entire array will be replaced.
     *
     * @param  array  $array
     * @param  string $key
     * @param  mixed  $value
     *
     * @return array
     */
    public static function set(&$array, $key, $value)
    {
        if (is_null($key)) {
            return $array = $value;
        }

        $keys = explode('.', $key);

        while (count($keys) > 1) {
            $key = array_shift($keys);

            // If the key doesn't exist at this depth, we will just create an empty array
            // to hold the next value, allowing us to create the arrays to hold final
            // values at the correct depth. Then we'll keep digging into the array.
            if (!isset($array[$key]) || !is_array($array[$key])) {
                $array[$key] = [];
            }

            $array = &$array[$key];
        }

        $array[array_shift($keys)] = $value;

        return $array;
    }

    /**
     * Sort the array using the given callback.
     *
     * @param  array    $array
     * @param  callable $callback
     *
     * @return array
     */
    public static function sort($array, callable $callback)
    {
        return Collection::make($array)->sortBy($callback)->all();
    }

    /**
     * Recursively sort an array by keys and values.
     *
     * @param  array $array
     *
     * @return array
     */
    public static function sortRecursive($array)
    {
        foreach ($array as &$value) {
            if (is_array($value)) {
                $value = static::sortRecursive($value);
            }
        }

        if (static::isAssoc($array)) {
            ksort($array);
        } else {
            sort($array);
        }

        return $array;
    }

    /**
     * Filter the array using the given callback.
     *
     * @param  array    $array
     * @param  callable $callback
     *
     * @return array
     */
    public static function where($array, callable $callback)
    {
        $filtered = [];

        foreach ($array as $key => $value) {
            if (call_user_func($callback, $key, $value)) {
                $filtered[$key] = $value;
            }
        }

        return $filtered;
    }
}


<?php

namespace Zumba\Swivel;

use Psr\Log\LoggerInterface;
use Zumba\Swivel\Logging\NullLogger;

class Config implements ConfigInterface
{
    use \Psr\Log\LoggerAwareTrait;

    /**
     * Index of the user's bucket.
     *
     * @var int
     */
    protected $index;

    /**
     * Map of features.
     *
     * @var \Zumba\Swivel\Map
     */
    protected $map;

    /**
     * Metrics object.
     *
     * @var \Zumba\Swivel\MetricsInterface
     */
    protected $metrics;

    /**
     * Callback to handle a missing slug from Map
     *
     * @var callable
     */
    protected $callback;

    /**
     * Zumba\Swivel\Config.
     *
     * @param mixed                         $map
     * @param int|null                      $index
     * @param \Psr\Log\LoggerInterface|null $logger
     * @param callable|null                 $callback
     */
    public function __construct($map = [], $index = null, LoggerInterface $logger = null, $callback = null)
    {
        $this->setLogger($logger ?: $this->getLogger());
        $this->setMap($map);
        $this->index = $index;
        $this->callback = $callback;
    }

    /**
     * Get a configured Bucket instance.
     *
     * @return \Zumba\Swivel\Bucket
     */
    public function getBucket()
    {
        return new Bucket($this->map, $this->index, $this->getLogger(), $this->callback);
    }

    /**
     * Get the PSR3 logger.
     *
     * @return \Psr\Log\LoggerInterface|null
     */
    public function getLogger()
    {
        return $this->logger ?: new NullLogger();
    }

    /**
     * Get the Metrics object.
     *
     * @return \Zumba\Swivel\MetricsInterface
     */
    public function getMetrics()
    {
        return $this->metrics;
    }

    /**
     * Set the bucket index for the user.
     *
     * @param int $index
     */
    public function setBucketIndex($index)
    {
        $this->index = $index;
    }

    /**
     * Set the Zumba\Swivel\Map object.
     *
     * @param mixed $map
     */
    protected function setMap($map)
    {
        $logger = $this->getLogger();
        if (is_array($map)) {
            $map = new Map($map, $logger);
        } elseif ($map instanceof DriverInterface) {
            $map = $map->getMap();
            $map->setLogger($logger);
        } elseif ($map instanceof MapInterface) {
            $map->setLogger($logger);
        } else {
            throw new \LogicException('Invalid map passed to Zumba\Swivel\Config');
        }
        $this->map = $map;
    }

    /**
     * Set the Metrics object.
     *
     * @param MetricsInterface $metrics
     */
    public function setMetrics(MetricsInterface $metrics)
    {
        $this->metrics = $metrics;
    }
}


<?php

namespace Zumba\Swivel;

class Manager implements ManagerInterface
{
    use \Psr\Log\LoggerAwareTrait;

    /**
     * A configured Bucket instance.
     *
     * @var \Zumba\Swivel\BucketInterface
     */
    protected $bucket;

    /**
     * A metrics object.
     *
     * @var \Zumba\Swivel\MetricsInterface
     */
    protected $metrics;

    /**
     * Zumba\Swivel\Manager.
     *
     * @param ConfigInterface $config
     */
    public function __construct(ConfigInterface $config)
    {
        $this->setLogger($config->getLogger());
        $this->setBucket($config->getBucket());

        if ($metrics = $config->getMetrics()) {
            $this->setMetrics($metrics);
        }

        $this->logger->debug('Swivel - Manager created.');
    }

    /**
     * Create a new Builder instance.
     *
     * @param string $slug
     *
     * @return \Zumba\Swivel\Builder
     *
     * @see \Zumba\Swivel\ManagerInterface
     */
    public function forFeature($slug)
    {
        $this->logger->debug('Swivel - Generating builder for feature "'.$slug.'"');
        $builder = new Builder($slug, $this->bucket);
        $builder->setLogger($this->logger);

        $this->metrics && $builder->setMetrics($this->metrics);

        return $builder;
    }

    /**
     * Syntactic sugar for creating simple feature toggles (ternary style).
     *
     * Uses Builder::addBehavior
     *
     * @param string   $slug
     * @param callable $a
     * @param callable $b
     *
     * @return mixed
     *
     * @see \Zumba\Swivel\ManagerInterface
     */
    public function invoke($slug, $a, $b = null)
    {
        $parts = explode(Map::DELIMITER, $slug);
        $feature = array_shift($parts);

        return $this->forFeature($feature)
            ->addBehavior(implode(Map::DELIMITER, $parts), $a)
            ->defaultBehavior($b ? $b : function () use ($b) {
                return $b;
            })
            ->execute();
    }

    /**
     * Syntactic sugar for creating simple feature toggles (ternary style).
     *
     * Uses Builder::addValue
     *
     * @param string $slug
     * @param mixed  $a
     * @param mixed  $b
     *
     * @return mixed
     *
     * @see \Zumba\Swivel\ManagerInterface
     */
    public function returnValue($slug, $a, $b = null)
    {
        $parts = explode(Map::DELIMITER, $slug);
        $feature = array_shift($parts);

        return $this->forFeature($feature)
            ->addValue(implode(Map::DELIMITER, $parts), $a)
            ->defaultValue($b)
            ->execute();
    }

    /**
     * Set the Swivel Bucket.
     *
     * @param \Zumba\Swivel\BucketInterface $bucket
     *
     * @return \Zumba\Swivel\ManagerInterface
     *
     * @see \Zumba\Swivel\ManagerInterface
     */
    public function setBucket(BucketInterface $bucket = null)
    {
        if ($bucket) {
            $this->bucket = $bucket;
            $this->logger->debug('Swivel - User bucket set.', compact('bucket'));
        }

        return $this;
    }

    /**
     * Set a metrics object.
     *
     * @param MetricsInterface $metrics
     */
    protected function setMetrics(MetricsInterface $metrics)
    {
        $this->metrics = $metrics;
    }
}