<commit_before><?php
/**
 * This file is part of the BEAR.Resource package
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 */
namespace BEAR\Resource;

use BEAR\Resource\Exception;
use BEAR\Resource\Uri;
use Guzzle\Cache\CacheAdapterInterface;
use SplObjectStorage;
use Ray\Di\Di\Scope;
use Ray\Di\Di\Inject;
use Ray\Di\Di\Named;

/**
 * Resource client
 *
 * @SuppressWarnings(PHPMD.TooManyMethods)
 *
 * @Scope("singleton")
 */
class Resource implements ResourceInterface
{
    /**
     * Resource factory
     *
     * @var Factory
     */
    private $factory;

    /**
     * Resource request invoker
     *
     * @var Invoker
     */
    private $invoker;

    /**
     * Resource request
     *
     * @var Request
     */
    private $request;

    /**
     * Requests
     *
     * @var \SplObjectStorage
     */
    private $requests;

    /**
     * Cache
     *
     * @var CacheAdapterInterface
     */
    private $cache;

    /**
     * @var string
     */
    private $appName = '';

    /**
     * @param $appName
     *
     * @Inject(optional = true)
     * @Named("app_name")
     *
     */
    public function setAppName($appName)
    {
        $this->appName = $appName;
    }

    /**
     * Set cache adapter
     *
     * @param CacheAdapterInterface $cache
     *
     * @Inject(optional = true)
     * @Named("resource_cache")
     */
    public function setCacheAdapter(CacheAdapterInterface $cache)
    {
        $this->cache = $cache;
    }

    /**
     * Set scheme collection
     *
     * @param SchemeCollectionInterface $scheme
     *
     * @Inject(optional = true)
     */
    public function setSchemeCollection(SchemeCollectionInterface $scheme)
    {
        $this->factory->setSchemeCollection($scheme);
    }

    /**
     * @param Factory          $factory resource object factory
     * @param InvokerInterface $invoker resource request invoker
     * @param Request          $request resource request
     *
     * @Inject
     */
    public function __construct(Factory $factory, InvokerInterface $invoker, Request $request)
    {
        $this->factory = $factory;
        $this->invoker = $invoker;
        $this->newRequest = $request;
        $this->requests = new SplObjectStorage;
        $this->invoker->setResourceClient($this);
    }

    /**
     * {@inheritDoc}
     */
    public function newInstance($uri)
    {
        if (substr($uri, -1) === '/') {
            $uri .= 'index';
        }
        $useCache = $this->cache instanceof CacheAdapterInterface;
        if ($useCache === true) {
            $key = $this->appName . 'res-' . str_replace('/', '-', $uri);
            $cached = $this->cache->fetch($key);
            if ($cached) {
                return $cached;
            }
        }
        $instance = $this->factory->newInstance($uri);
        if ($useCache === true) {
            /** @noinspection PhpUndefinedVariableInspection */
            $this->cache->save($key, $instance);
        }

        return $instance;
    }

    /**
     * {@inheritDoc}
     */
    public function object($ro)
    {
        $this->request->ro = $ro;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function uri($uri)
    {
        if (is_string($uri)) {
            if (!$this->request) {
                throw new Exception\BadRequest('Request method (get/put/post/delete/options) required before uri()');
            }
            if (!preg_match('|^[a-z]+?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $uri)) {
                throw new Exception\Uri($uri);
            }
            // uri with query parsed
            if (strpos($uri, '?') !== false) {
                $parsed = parse_url($uri);
                $uri = $parsed['scheme'] . '://' . $parsed['host'] . $parsed['path'];
                if (isset($parsed['query'])) {
                    parse_str($parsed['query'], $query);
                    $this->withQuery($query);
                }
            }
            $this->request->ro = $this->newInstance($uri);
            $this->request->uri = $uri;

            return $this;
        }
        if ($uri instanceof Uri) {
            $this->request->ro = $this->newInstance($uri->uri);
            $this->withQuery($uri->query);

            return $this;
        }
        throw new Exception\Uri;
    }

    /**
     * {@inheritDoc}
     */
    public function withQuery(array $query)
    {
        $this->request->query = $query;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function addQuery(array $query)
    {
        $this->request->query = array_merge($this->request->query, $query);

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function linkSelf($linkKey)
    {
        $link = new LinkType;
        $link->key = $linkKey;
        $link->type = LinkType::SELF_LINK;
        $this->request->links[] = $link;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function linkNew($linkKey)
    {
        $link = new LinkType;
        $link->key = $linkKey;
        $link->type = LinkType::NEW_LINK;
        $this->request->links[] = $link;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function linkCrawl($linkKey)
    {
        $link = new LinkType;
        $link->key = $linkKey;
        $link->type = LinkType::CRAWL_LINK;
        $this->request->links[] = $link;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function request()
    {
        $this->request->ro->uri = $this->request->toUri();
        if (isset($this->request->options['sync'])) {
            $this->requests->attach($this->request);
            $this->request = clone $this->newRequest;

            return $this;
        }
        if ($this->request->in !== 'eager') {

            return $this->request;
        }
        $result = $this->invoke();

        if (!($result instanceof ObjectInterface) && isset($this->request->ro)) {
            $this->request->ro->body = $result;
            $result = $this->request->ro;
        }

        return $result;
    }

    /**
     * @return AbstractObject|mixed
     */
    private function invoke()
    {
        if ($this->requests->count() === 0) {
            return $this->invoker->invoke($this->request);
        }
        $this->requests->attach($this->request);
        return $this->invoker->invokeSync($this->requests);
    }


    /**
     * {@inheritDoc}
     */
    public function attachParamProvider($varName, ParamProviderInterface $provider)
    {
        $this->invoker->attachParamProvider($varName, $provider);
<commit_msg>remove dubbed procedure<commit_after><?php
/**
 * This file is part of the BEAR.Resource package
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 */
namespace BEAR\Resource;

use BEAR\Resource\Exception;
use BEAR\Resource\Uri;
use Guzzle\Cache\CacheAdapterInterface;
use SplObjectStorage;
use Ray\Di\Di\Scope;
use Ray\Di\Di\Inject;
use Ray\Di\Di\Named;

/**
 * Resource client
 *
 * @SuppressWarnings(PHPMD.TooManyMethods)
 *
 * @Scope("singleton")
 */
class Resource implements ResourceInterface
{
    /**
     * Resource factory
     *
     * @var Factory
     */
    private $factory;

    /**
     * Resource request invoker
     *
     * @var Invoker
     */
    private $invoker;

    /**
     * Resource request
     *
     * @var Request
     */
    private $request;

    /**
     * Requests
     *
     * @var \SplObjectStorage
     */
    private $requests;

    /**
     * Cache
     *
     * @var CacheAdapterInterface
     */
    private $cache;

    /**
     * @var string
     */
    private $appName = '';

    /**
     * @param $appName
     *
     * @Inject(optional = true)
     * @Named("app_name")
     *
     */
    public function setAppName($appName)
    {
        $this->appName = $appName;
    }

    /**
     * Set cache adapter
     *
     * @param CacheAdapterInterface $cache
     *
     * @Inject(optional = true)
     * @Named("resource_cache")
     */
    public function setCacheAdapter(CacheAdapterInterface $cache)
    {
        $this->cache = $cache;
    }

    /**
     * Set scheme collection
     *
     * @param SchemeCollectionInterface $scheme
     *
     * @Inject(optional = true)
     */
    public function setSchemeCollection(SchemeCollectionInterface $scheme)
    {
        $this->factory->setSchemeCollection($scheme);
    }

    /**
     * @param Factory          $factory resource object factory
     * @param InvokerInterface $invoker resource request invoker
     * @param Request          $request resource request
     *
     * @Inject
     */
    public function __construct(Factory $factory, InvokerInterface $invoker, Request $request)
    {
        $this->factory = $factory;
        $this->invoker = $invoker;
        $this->newRequest = $request;
        $this->requests = new SplObjectStorage;
        $this->invoker->setResourceClient($this);
    }

    /**
     * {@inheritDoc}
     */
    public function newInstance($uri)
    {
        if (substr($uri, -1) === '/') {
            $uri .= 'index';
        }
        $useCache = $this->cache instanceof CacheAdapterInterface;
        if ($useCache === true) {
            $key = $this->appName . 'res-' . str_replace('/', '-', $uri);
            $cached = $this->cache->fetch($key);
            if ($cached) {
                return $cached;
            }
        }
        $instance = $this->factory->newInstance($uri);
        if ($useCache === true) {
            /** @noinspection PhpUndefinedVariableInspection */
            $this->cache->save($key, $instance);
        }

        return $instance;
    }

    /**
     * {@inheritDoc}
     */
    public function object($ro)
    {
        $this->request->ro = $ro;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function uri($uri)
    {
        if (is_string($uri)) {
            if (!$this->request) {
                throw new Exception\BadRequest('Request method (get/put/post/delete/options) required before uri()');
            }
            if (!preg_match('|^[a-z]+?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $uri)) {
                throw new Exception\Uri($uri);
            }
            // uri with query parsed
            if (strpos($uri, '?') !== false) {
                $parsed = parse_url($uri);
                $uri = $parsed['scheme'] . '://' . $parsed['host'] . $parsed['path'];
                if (isset($parsed['query'])) {
                    parse_str($parsed['query'], $query);
                    $this->withQuery($query);
                }
            }
            $this->request->ro = $this->newInstance($uri);
            $this->request->uri = $uri;

            return $this;
        }
        if ($uri instanceof Uri) {
            $this->request->ro = $this->newInstance($uri->uri);
            $this->withQuery($uri->query);

            return $this;
        }
        throw new Exception\Uri;
    }

    /**
     * {@inheritDoc}
     */
    public function withQuery(array $query)
    {
        $this->request->query = $query;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function addQuery(array $query)
    {
        $this->request->query = array_merge($this->request->query, $query);

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function linkSelf($linkKey)
    {
        $link = new LinkType;
        $link->key = $linkKey;
        $link->type = LinkType::SELF_LINK;
        $this->request->links[] = $link;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function linkNew($linkKey)
    {
        $link = new LinkType;
        $link->key = $linkKey;
        $link->type = LinkType::NEW_LINK;
        $this->request->links[] = $link;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function linkCrawl($linkKey)
    {
        $link = new LinkType;
        $link->key = $linkKey;
        $link->type = LinkType::CRAWL_LINK;
        $this->request->links[] = $link;

        return $this;
    }

    /**
     * {@inheritDoc}
     */
    public function request()
    {
        $this->request->ro->uri = $this->request->toUri();
        if (isset($this->request->options['sync'])) {
            $this->requests->attach($this->request);
            $this->request = clone $this->newRequest;

            return $this;
        }
        if ($this->request->in !== 'eager') {
            return $this->request;
        }

        return $this->invoke();
    }

    /**
     * @return AbstractObject|mixed
     */
    private function invoke()
    {
        if ($this->requests->count() === 0) {
            return $this->invoker->invoke($this->request);
        }
        $this->requests->attach($this->request);
        return $this->invoker->invokeSync($this->requests);
    }


    /**
     * {@inheritDoc}
     */
    public function attachParamProvider($varName, ParamProviderInterface $provider)
    {
        $this->invoker->attachParamProvider($varName, $provider);

{'fraction_non_alphanumeric': 0.15974075486084635, 'fraction_numerical': 0.0012199771254288983, 'mean_word_length': 1.767672504747837, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 170, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6588650', 'n_tokens_mistral': 3945, 'n_tokens_neox': 3866, 'n_words': 719}