<commit_before><?php
/**
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Nodrew\Bundle\DfpBundle\EventListener;

use Nodrew\Bundle\DfpBundle\Model\Collection,
    Nodrew\Bundle\DfpBundle\Model\Settings,
    Nodrew\Bundle\DfpBundle\Model\AdUnit,
    Symfony\Component\HttpKernel\Event\FilterResponseEvent,
    Symfony\Component\HttpFoundation\Response;

/**
 * @package     NodrewDfpBundle
 * @author      <NAME> <<EMAIL>>
 * @copyright	(c) 2012 <NAME>
 * @license     http://www.opensource.org/licenses/mit-license.php
 */
class ControlCodeListener
{
    /**
     * The template placeholder where the DFP code is to be inserted.
     */
    const PLACEHOLDER = '<!-- NodrewDfpBundle Control Code -->';

    /**
     * @var Nodrew\Bundle\DfpBundle\Model\Collection
     */
    protected $collection;

    /**
     * @var Nodrew\Bundle\DfpBundle\Model\Settings
     */
    protected $settings;


    /**
     * Constructor.
     *
     * @param Nodrew\Bundle\DfpBundle\Model\Collection $collection
     * @param Nodrew\Bundle\DfpBundle\Model\Settings $settings
     */
    public function __construct(Collection $collection, Settings $settings)
    {
        $this->settings   = $settings;
        $this->collection = $collection;
    }

    /**
     * Switch out the Control Code placeholder for the Google DFP control code html,
     * based upon the included ads.
     *
     * @param Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
     */
    public function onKernelResponse(FilterResponseEvent $event)
    {
        $response = $event->getResponse();

        $controlCode = '';
        if (count($this->collection) > 0) {
            $controlCode .= $this->getMainControlCode();
            
            foreach ($this->collection as $unit) {
                $controlCode .= $this->getAdControlBlock($unit);
            }
        }

        $response->setContent(str_replace(self::PLACEHOLDER, $controlCode, $response->getContent()));
    }

    /**
     * Get the main google dfp control code block.
     *
     * This inserts the main google script.
     *
     * @return string
     */
    protected function getMainControlCode()
    {
        return <<< CONTROL

<script type="text/javascript">
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
(function() {
var gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
var useSSL = 'https:' == document.location.protocol;
gads.src = (useSSL ? 'https:' : 'http:') +
'//www.googletagservices.com/tag/js/gpt.js';
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);
})();
</script>

CONTROL;
    }
    
    /**
     * Get the control block for an individual ad.
     *
     * @return string
     */
    protected function getAdControlBlock(AdUnit $unit)
    {
        $publisherId = $this->settings->getPublisherId();
        $targets     = $this->getTargetsBlock($unit->getTargets());
        $sizes       = $this->printSizes($unit->getSizes());
        $divId       = $unit->getDivId();
        $path        = $unit->getPath();

        return <<< BLOCK

<script type="text/javascript">
googletag.cmd.push(function() {
googletag.defineSlot('/{$publisherId}/{$path}', {$sizes}, '{$divId}').addService(googletag.pubads());
googletag.pubads().enableSingleRequest();
googletag.enableServices();{$targets}
});
</script>

BLOCK;
    }
    
    /**
     * Print the sizes array in it's json equivalent.
     *
     * @param array $sizes
     * @return string
     */
    protected function printSizes(array $sizes)<commit_msg>Added the trim for slashes around the publisher id, to get rid of extra slashes, since we add them in the template.<commit_after><?php
/**
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Nodrew\Bundle\DfpBundle\EventListener;

use Nodrew\Bundle\DfpBundle\Model\Collection,
    Nodrew\Bundle\DfpBundle\Model\Settings,
    Nodrew\Bundle\DfpBundle\Model\AdUnit,
    Symfony\Component\HttpKernel\Event\FilterResponseEvent,
    Symfony\Component\HttpFoundation\Response;

/**
 * @package     NodrewDfpBundle
 * @author      <NAME> <<EMAIL>>
 * @copyright	(c) 2012 <NAME>
 * @license     http://www.opensource.org/licenses/mit-license.php
 */
class ControlCodeListener
{
    /**
     * The template placeholder where the DFP code is to be inserted.
     */
    const PLACEHOLDER = '<!-- NodrewDfpBundle Control Code -->';

    /**
     * @var Nodrew\Bundle\DfpBundle\Model\Collection
     */
    protected $collection;

    /**
     * @var Nodrew\Bundle\DfpBundle\Model\Settings
     */
    protected $settings;


    /**
     * Constructor.
     *
     * @param Nodrew\Bundle\DfpBundle\Model\Collection $collection
     * @param Nodrew\Bundle\DfpBundle\Model\Settings $settings
     */
    public function __construct(Collection $collection, Settings $settings)
    {
        $this->settings   = $settings;
        $this->collection = $collection;
    }

    /**
     * Switch out the Control Code placeholder for the Google DFP control code html,
     * based upon the included ads.
     *
     * @param Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
     */
    public function onKernelResponse(FilterResponseEvent $event)
    {
        $response = $event->getResponse();

        $controlCode = '';
        if (count($this->collection) > 0) {
            $controlCode .= $this->getMainControlCode();
            
            foreach ($this->collection as $unit) {
                $controlCode .= $this->getAdControlBlock($unit);
            }
        }

        $response->setContent(str_replace(self::PLACEHOLDER, $controlCode, $response->getContent()));
    }

    /**
     * Get the main google dfp control code block.
     *
     * This inserts the main google script.
     *
     * @return string
     */
    protected function getMainControlCode()
    {
        return <<< CONTROL

<script type="text/javascript">
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
(function() {
var gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
var useSSL = 'https:' == document.location.protocol;
gads.src = (useSSL ? 'https:' : 'http:') +
'//www.googletagservices.com/tag/js/gpt.js';
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);
})();
</script>

CONTROL;
    }
    
    /**
     * Get the control block for an individual ad.
     *
     * @return string
     */
    protected function getAdControlBlock(AdUnit $unit)
    {
        $publisherId = trim($this->settings->getPublisherId(), '/');
        $targets     = $this->getTargetsBlock($unit->getTargets());
        $sizes       = $this->printSizes($unit->getSizes());
        $divId       = $unit->getDivId();
        $path        = $unit->getPath();

        return <<< BLOCK

<script type="text/javascript">
googletag.cmd.push(function() {
googletag.defineSlot('/{$publisherId}/{$path}', {$sizes}, '{$divId}').addService(googletag.pubads());
googletag.pubads().enableSingleRequest();
googletag.enableServices();{$targets}
});
</script>

BLOCK;
    }
    
    /**
     * Print the sizes array in it's json equivalent.
     *
     * @param array $sizes
     * @return string
     */
    protected function printSizes(array $sizes)
{'fraction_non_alphanumeric': 0.13938260056127222, 'fraction_numerical': 0.0016036349057864494, 'mean_word_length': 2.774079677256682, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 57, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, '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': '3207423', 'n_tokens_mistral': 2275, 'n_tokens_neox': 2225, 'n_words': 478}