Returns an array of lines to send back to IRC when the http request is successful

@param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
@param string $apiResponse

@return array
161990
public function getSuccessLines(Event $event, $apiResponse)
    {
        $json = json_decode($apiResponse);
        $json = $json->responseData;

        if (isset($json->cursor->estimatedResultCount) && $json->cursor->estimatedResultCount > 0) {
            $messages = [];
            $messages[] = sprintf(
                "%s [ %s ]",
                $json->results[0]->titleNoFormatting,
                $json->results[0]->url
            );
            $messages[] = sprintf("More results: %s", $json->cursor->moreResultsUrl);
        } else {
            $messages = $this->getNoResultsLines($event, $apiResponse);
        }

        return $messages;
    }
507135
public function onKernelException(GetResponseForExceptionEvent $event) :? Response
    {
        // You get the exception object from the received event
        $exception = $event->getException();
        $request = $event->getRequest();

        // If the event already has a response, do not override it.
        if ($event->hasResponse()) {
            return $event->getResponse();
        }

        $format = $request->getRequestFormat($this->defaultFormat);

        // If the request format is not supported, nothing more can be done
        // without the serializer throwing an exception.
        if (!$this->encoder->supportsEncoding($format)) {
            return null;
        }

        // If the normalizer cannot normalize the result, then there is nothing
        // more than can be done without the serializer throwing an exception.
        if (!$this->normalizer->supportsNormalization($exception, $format)) {
            return null;
        }

        $status = 500;
        $headers = [];
        if ($exception instanceof HttpExceptionInterface) {
            $status = $exception->getStatusCode();
            $headers = $exception->getHeaders();
        }

        $context = [
            'enable_max_depth' => true,
        ];

        $serializeEvent = new SerializeEvent($exception, $format, $context, $request);

        $this->eventDispatcher->dispatch(SerializeEvent::NAME, $serializeEvent);

        $response = new Response(
            $this->serializer->serialize(
                $serializeEvent->getData(),
                $serializeEvent->getFormat(),
                $serializeEvent->getContext()
            ),
            $status,
            $headers
        );

        // Add the default content type headers.
        if ($format !== $request->getRequestFormat() && !$response->headers->has('Content-Type')) {
            if ($mimeType = $request->getMimeType($format)) {
                $response->headers->set('Content-Type', $mimeType);
            }
        }

        $event->setResponse($response);

        return $response;
    }
146960
protected function handleEvent($event)
    {
        if (!is_null($response = $this->call('event.*', array($event)))) {
            return $response;
        }

        $event['Event'] = strtolower($event['Event']);

        return $this->call("event.{$event['Event']}", array($event));
    }
791335
public function commandParseResponse(GuzzleCreateResponseClassEvent $event)
    {
        /** @var GuzzleCommandInterface $command */
        $command = $event['command'];

        $className = $this->getClassName($command);

        // if the guzzle way fromCommand is present don't do anything
        if (!method_exists($className, 'fromCommand')) {
            $event->setResult(
                $this->serializer->deserialize($command->getResponse()->getBody(), $className, 'json')
            );
        }
    }
480734
public function sendRequest(RequestEvent $event)
    {
        switch ($event->getMethod()) {
            case 'GET':
                $response = $this->getHttpClient()->getAdapter()->get($event->getRequest());
                break;
            case 'HEAD':
                $response = $this->getHttpClient()->getAdapter()->head($event->getRequest());
                break;
            case 'POST':
                $response = $this->getHttpClient()->getAdapter()->post($event->getRequest());
                break;
            case 'PUT':
                $response = $this->getHttpClient()->getAdapter()->put($event->getRequest());
                break;
            case 'PATCH':
                $response = $this->getHttpClient()->getAdapter()->patch($event->getRequest());
                break;
            case 'DELETE':
                $response = $this->getHttpClient()->getAdapter()->delete($event->getRequest());
                break;
            default:
                throw new RuntimeException(sprintf('Unknown request method "%s".', $event->getMethod()));
        }

        return $response;
    }
30701
public function writeApiRequestingLog(Events\ApiRequesting $event)
    {
        Log::debug("Requesting To {$event->driver} Api", [$event->endpoint, $event->payload]);
    }
239972
public function onKernelViewSerialize(GetResponseForControllerResultEvent $event)
    {
        if (!$this->isEventEligible($event)) {
            return;
        }

        $annot = $this->extractAnnotation($event, 'OpenOrchestra\BaseApiBundle\Controller\Annotation\Serialize');

        if (!$annot) {
            return;
        }

        $format = $event->getRequest()->get('_format', 'json');
        $statusCode = 200;
        $controllerResult = $event->getControllerResult();
        if ($controllerResult instanceof ConstraintViolationListInterface) {
            $statusCode = 400;
        }

        $event->setResponse(
            new Response(
                $this->generateResponseContent(
                    $controllerResult,
                    $format
                ),
                $statusCode,
                array('content-type' => $this->generateContentType($format))
            )
        );
    }
675398
public function handleJoinCommand(CommandEvent $event, EventQueueInterface $queue)
    {
        $params = $event->getCustomParams();
        if (!$params) {
            $this->handleJoinHelp($event, $queue);
        } else {
            $channels = $params[0];
            $keys = isset($params[1]) ? $params[1] : null;
            $queue->ircJoin($channels, $keys);
        }
    }
124283
protected function generateDocs($apiName, $operation, $api = [], $method = '')
    {

        $row = [];
        $row['method'] = $this->getMDApiName($apiName, $operation, $api, $method);
        $row['endpoint'] = $this->getMDApiEndpoint($apiName, $operation, $api, $method);
        $row['parameters'] = $this->getMDApiParams($apiName, $operation, $api, $method);
        $row['defaults'] = $this->getMDApiParamDefaults($apiName, $operation, $api, $method);
        $row['description'] = $this->getMDDescription($apiName, $operation, $api, $method);

        return $row;

    }
810431
public function process(ServerRequestInterface $request, DelegateInterface $delegate)
    {
        $operation = $this->getOperation($request);

        $arguments = [];
        foreach ($operation->getParameters() as $parameter) {
            $arguments[] = $request->getAttribute($parameter->getName());
        }

        $result = call_user_func_array($this->commands[$operation->getId()], $arguments);

        return $delegate->process($request->withAttribute(self::ATTRIBUTE, $result));
    }
662303
public function invokeCommandCallback($method, CommandInterface $command)
    {
        $mixer = $this->getMixer();

        if($mixer instanceof CommandCallbackDelegate) {
            $result = $mixer->invokeCommandCallback($method, $command);
        } else {
            $result = $mixer->$method($command);
        }

        return $result;
    }
283104
private function prepareApiResponse(
        ResponseContextAbstract $responseContext,
        string $apiClassMethod
    ): ApiResponseInterface {
        $prepareApiResponse = sprintf("prepare%sResponse", ucfirst($apiClassMethod));

        $this->assertMethodExists($prepareApiResponse);

        $apiResponse = $this->{$prepareApiResponse}($responseContext);

        return $apiResponse;
    }
425580
public function process(array $event)
    {
        $remoteAddress = null;

        /** @noinspection UnSafeIsSetOverArrayInspection */
        if (isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP'])) {
            $remoteAddress = $_SERVER['HTTP_CLIENT_IP'];
        } /** @noinspection UnSafeIsSetOverArrayInspection */
        elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $remoteAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } /** @noinspection UnSafeIsSetOverArrayInspection */
        elseif (isset($_SERVER['REMOTE_ADDR']) && !empty($_SERVER['REMOTE_ADDR'])) {
            $remoteAddress = $_SERVER['REMOTE_ADDR'];
        }

        if (!array_key_exists('extra', $event)) {
            $event['extra'] = [];
        }

        $event['extra']['ip'] = $remoteAddress;

        return $event;
    }
936403
public function onKernelView(GetResponseForControllerResultEvent $event) :? Response
    {
        $request = $event->getRequest();
        $result = $event->getControllerResult();

        // If the event already has a response, do not override it.
        if ($event->hasResponse()) {
            return $event->getResponse();
        }

        // If the request format is not supported, nothing more can be done
        // without the serializer throwing an exception.
        if (!$this->encoder->supportsEncoding($request->getRequestFormat())) {
            return null;
        }

        if (is_iterable($result)) {
            $data = $result;

            // Convert objects to arrays.
            if ($result instanceof \Traversable) {
                $data = iterator_to_array($result);
            }

            // Determine if array is a collection or just a standard array.
            $bad = array_filter($data, function ($item) use ($request) {
                if (!is_object($item)) {
                    return true;
                }

                if (!$this->normalizer->supportsNormalization($item, $request->getRequestFormat())) {
                    return true;
                }

                return false;
            });

            // If array is a collection and everything can be normalized,
            // normalize each item before serialization.
            if (!count($bad)) {
                $result = array_map(function ($item) use ($request) {
                    return $this->normalizer->normalize($item, $request->getRequestFormat(), [
                        'groups' => $this->groupResolver->resolve($request, $item),
                        'enable_max_depth' => true,
                    ]);
                }, $data);
            }
        }

        // If the normalizer cannot normalize the result, then there is nothing
        // more than can be done without the serializer throwing an exception.
        if (is_object($result) && !$this->normalizer->supportsNormalization($result, $request->getRequestFormat())) {
            return null;
        }

        $status = Response::HTTP_OK;
        switch ($request->getMethod()) {
            case Request::METHOD_POST:
                $status = Response::HTTP_CREATED;
                break;
            case Request::METHOD_DELETE:
                $status = Response::HTTP_NO_CONTENT;
                break;
        }

        $groups = null;
        if (is_object($result)) {
            $groups = $this->groupResolver->resolve($request, $result);
        }

        $serializeEvent = new SerializeEvent(
            $result,
            $request->getRequestFormat(),
            [
                'groups' => $groups,
                'enable_max_depth' => true,
            ],
            $request
        );

        $this->eventDispatcher->dispatch(SerializeEvent::NAME, $serializeEvent);

        $response = new Response(
            $this->serializer->serialize(
                $serializeEvent->getData(),
                $serializeEvent->getFormat(),
                $serializeEvent->getContext()
            ),
            $status
        );
        $event->setResponse($response);

        return $response;
    }
831194
public function handleDnsCommand(CommandEventInterface $event, EventQueueInterface $queue)
    {
        if (get_class($event) !== '\Phergie\Irc\Plugin\React\Command\CommandEvent' &&
            get_class($event) !== 'Phergie\Irc\Plugin\React\Command\CommandEvent' &&
            !is_subclass_of($event, '\Phergie\Irc\Plugin\React\Command\CommandEvent')
        ) {
            throw new \BadMethodCallException(
                get_class($event) . ' given, expected: Phergie\Irc\Plugin\React\Command\CommandEvent'
            );
        }

        foreach ($event->getCustomParams() as $hostname) {
            $this->logDebug('Looking up: ' . $hostname);
            $this->resolveDnsQuery(
                new Query(
                    $hostname,
                    function ($ip, $hostname) use ($event, $queue) {
                        $message = $hostname . ': ' . $ip;
                        $this->logDebug($message);
                        foreach ($event->getTargets() as $target) {
                            $queue->ircPrivmsg($target, $message);
                        }
                    },
                    function ($error, $hostname) use ($event, $queue) {
                        $message = $hostname . ': error looking up hostname: ' . $error->getMessage();
                        $this->logDebug($message);
                        foreach ($event->getTargets() as $target) {
                            $queue->ircPrivmsg($target, $message);
                        }
                    }
                )
            );
        }
    }
1182390
public static function lint(Event $event, Api $api = null)
    {
        $composerTravisLintCache = getcwd()
            . DIRECTORY_SEPARATOR
            . self::CTL_CACHE;
        $io = $event->getIO();

        if (!file_exists(self::TRAVIS_CONFIGURATION)) {
            $io->writeError("Travis CI configuration doesn't exist.");

            return false;
        }

        if (self::hasStaleCacheFile() === false) {
            $message = 'Travis CI configuration has not '
                . 'changed since the last lint run and is therefore valid.';

            $io->write($message);

            return true;
        }

        $travisConfigContent = trim(
            file_get_contents(realpath(self::TRAVIS_CONFIGURATION))
        );

        if ($api === null) {
            $api = new Api();
        }

        try {
            $result = $api->post($travisConfigContent);

            if ($result->isSuccessful()) {
                $message = 'Travis CI configuration is valid.';

                $bytesWritten = file_put_contents(
                    $composerTravisLintCache,
                    md5($travisConfigContent) . "\n"
                );

                if ($bytesWritten > 0) {
                    $message .= PHP_EOL . "Created '" . self::CTL_CACHE . "' file.";
                }

                $io->write($message);

                return true;
            }

            $errorMessage = $result->getFailure();

            if (file_exists($composerTravisLintCache)) {
                unlink($composerTravisLintCache);
                $errorMessage .= PHP_EOL . "Deleted '" . self::CTL_CACHE . "' file.";
            }

            $io->writeError($errorMessage);

            return false;
        } catch (ConnectivityFailure $f) {
            $io->writeError($f->getMessage());

            return false;
        } catch (NonExpectedReponseStructure $n) {
            $io->writeError($n->getMessage());

            return false;
        }
    }
101705
public function getSuccessLines(Event $event, $apiResponse)
    {
        $data = json_decode($apiResponse);
        if (isset($data->name) && $data->name) {
            return array(
                sprintf(
                    "%s, %s | %s | Temp: %dC | Humidity: %s%% | Sunrise: %s | Sunset: %s",
                    $data->name,
                    $data->sys->country,
                    $data->weather[0]->main,
                    round($data->main->temp - 273.15),
                    $data->main->humidity,
                    date("H:i:s", $data->sys->sunrise),
                    date("H:i:s", $data->sys->sunset)
                )
            );
        } else {
            return $this->getNoResultsLines($event, $apiResponse);
        }
    }