<commit_before><?php namespace TopLog\Toplogger\Handlers;

/*
 * This file is part of the Monolog package.
 *
 * (c) <NAME> <<EMAIL>>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Monolog\Logger;
use Monolog\Handler\SocketHandler;

/**
 * Sends notifications through Slack API
 *
 * @author <NAME> <<EMAIL>>
 * @see    https://api.slack.com/
 */
class SlackHandler extends SocketHandler
{
    /**
     * Slack API token
     * @var string
     */
    private $token;

    /**
     * Slack channel (encoded ID or name)
     * @var string
     */
    private $channel;

    /**
     * Name of a bot
     * @var string
     */
    private $username;

    /**
     * Emoji icon name
     * @var string
     */
    private $iconEmoji;

    /**
     * Whether the message should be added to Slack as attachment (plain text otherwise)
     * @var bool
     */
    private $useAttachment;

    /**
     * @param string      $token         Slack API token
     * @param string      $channel       Slack channel (encoded ID or name)
     * @param string      $username      Name of a bot
     * @param bool        $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise)
     * @param string|null $iconEmoji     The emoji name to use (or null)
     * @param int         $level         The minimum logging level at which this handler will be triggered
     * @param bool        $bubble        Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct($token, $channel, $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $level = Logger::CRITICAL, $bubble = true)
    {
        if (!extension_loaded('openssl')) {
            throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler');
        }

        parent::__construct('ssl://slack.com:443', $level, $bubble);

        $this->token = $token;
        $this->channel = $channel;
        $this->username = $username;
        $this->iconEmoji = trim($iconEmoji, ':');
        $this->useAttachment = $useAttachment;
    }

    /**
     * {@inheritdoc}
     *
     * @param  array  $record
     * @return string
     */
    protected function generateDataStream($record)
    {
        $content = $this->buildContent($record);

        return $this->buildHeader($content) . $content;
    }

    /**
     * Builds the body of API call
     *
     * @param  array  $record
     * @return string
     */
    private function buildContent($record)
    {
        $dataArray = array(
            'token' => $this->token,
            'channel' => $this->channel,
            'username' => $this->username,
            'text' => '',
            'attachments' => array()
        );

        if ($this->useAttachment) {
            //get the datetime object and convert it to a string
            $newDate = $record['datetime'];
            $newDate = $newDate->format('[d/M/Y:H:i:s O]');
            
            $dataArray['attachments'] = json_encode(
                array(
                    array(
                        'fallback' => $record['message'],
                        'color' => $this->getAttachmentColor($record['level']),
                        'fields' => array(
                            array(
                                //'title' => 'Message',
                                'value' => $newDate.' '.$record['channel'].' '.$record['level_name'].' '.$record['message'],
                                'short' => false
                            )//,
                            // array(
                            //     'title' => 'Level',
                            //     'value' => $record['level_name'],
                            //     'short' => true
                            // )
                        )
                    )
                )
            );
        } else {
            $dataArray['text'] = $record['message'];
        }

        if ($this->iconEmoji) {
            $dataArray['icon_emoji'] = ":{$this->iconEmoji}:";
        }

        return http_build_query($dataArray);
    }

    /**
     * Builds the header of the API Call
     *
     * @param  string $content
     * @return string
     */
    private function buildHeader($content)
    {
        $header = "POST /api/chat.postMessage HTTP/1.1\r\n";<commit_msg>log line formatted to display in slack<commit_after><?php namespace TopLog\Toplogger\Handlers;

/*
 * This file is part of the Monolog package.
 *
 * (c) <NAME> <<EMAIL>>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Monolog\Logger;
use Monolog\Handler\SocketHandler;

/**
 * Sends notifications through Slack API
 *
 * @author <NAME> <<EMAIL>>
 * @see    https://api.slack.com/
 */
class SlackHandler extends SocketHandler
{
    /**
     * Slack API token
     * @var string
     */
    private $token;

    /**
     * Slack channel (encoded ID or name)
     * @var string
     */
    private $channel;

    /**
     * Name of a bot
     * @var string
     */
    private $username;

    /**
     * Emoji icon name
     * @var string
     */
    private $iconEmoji;

    /**
     * Whether the message should be added to Slack as attachment (plain text otherwise)
     * @var bool
     */
    private $useAttachment;

    /**
     * @param string      $token         Slack API token
     * @param string      $channel       Slack channel (encoded ID or name)
     * @param string      $username      Name of a bot
     * @param bool        $useAttachment Whether the message should be added to Slack as attachment (plain text otherwise)
     * @param string|null $iconEmoji     The emoji name to use (or null)
     * @param int         $level         The minimum logging level at which this handler will be triggered
     * @param bool        $bubble        Whether the messages that are handled can bubble up the stack or not
     */
    public function __construct($token, $channel, $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $level = Logger::CRITICAL, $bubble = true)
    {
        if (!extension_loaded('openssl')) {
            throw new MissingExtensionException('The OpenSSL PHP extension is required to use the SlackHandler');
        }

        parent::__construct('ssl://slack.com:443', $level, $bubble);

        $this->token = $token;
        $this->channel = $channel;
        $this->username = $username;
        $this->iconEmoji = trim($iconEmoji, ':');
        $this->useAttachment = $useAttachment;
    }

    /**
     * {@inheritdoc}
     *
     * @param  array  $record
     * @return string
     */
    protected function generateDataStream($record)
    {
        $content = $this->buildContent($record);

        return $this->buildHeader($content) . $content;
    }

    /**
     * Builds the body of API call
     *
     * @param  array  $record
     * @return string
     */
    private function buildContent($record)
    {
        $dataArray = array(
            'token' => $this->token,
            'channel' => $this->channel,
            'username' => $this->username,
            'text' => '',
            'attachments' => array()
        );

        if ($this->useAttachment)
        {
            //get the datetime object and convert it to a string
            $newDate = $record['datetime'];
            $newDate = $newDate->format('[d/M/Y:H:i:s O]');

            //check if it is production and change the format if necessary
            if (getenv("ENV") === 'production')
            {
                $logLine = $newDate.' '.$record['channel'].' '.$record['level_name'].' '.$record['message'];
            }
            else
            {
                $logLine = $newDate.' '.$record['channel'].' '.$record['level_name'].' '.$record['message'].' '.$record['context'];
            }

            $dataArray['attachments'] = json_encode(
                array(
                    array(
                        'fallback' => $record['message'],
                        'color' => $this->getAttachmentColor($record['level']),
                        'fields' => array(
                            array(
                                'value' => $logLine,
                                'short' => false
                            )
                        )
                    )
                )
            );
        }
        else
        {
            $dataArray['text'] = $record['message'];
        }

        if ($this->iconEmoji)
        {
            $dataArray['icon_emoji'] = ":{$this->iconEmoji}:";
        }

        return http_build_query($dataArray);
    }

    /**
     * Builds the header of the API Call
     *
     * @param  string $content
     * @return string
     */
    private function buildHeader($content)
    {
        $header = "POST /api/chat.postMessage HTTP/1.1\r\n";
{'fraction_non_alphanumeric': 0.12710736468500444, 'fraction_numerical': 0.0011091393078970719, 'mean_word_length': 1.628096764791606, 'pattern_counts': {'":': 2, '<': 17, '<?xml version=': 0, '>': 69, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '218268', 'n_tokens_mistral': 2475, 'n_tokens_neox': 2444, 'n_words': 679}