text:
<?php
/**
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 * PHP Version 5
 *
 * @category EasyBib
 * @package  EasyBib_Form
 * @author   Michael Scholl <michael@sch0ll.de>
 * @license  http://www.opensource.org/licenses/mit-license.html MIT License
 * @version  git: $id$
 * @link     https://github.com/easybib/EasyBib_Form_Decorator
 */

/**
 * Default Decorators Set
 *
 * General usage:
 * EasyBib_Form_Decorator::setFormDecorator($form, 'div', 'submit', 'cancel');
 * EasyBib_Form_Decorator::setFormDecorator(
 *   Instance of form,
 *   Decorator Mode - 3 different options:
 *      - EasyBib_Form_Decorator::TABLE     (html table style)
 *      - EasyBib_Form_Decorator::DIV       (div style)
 *      - EasyBib_Form_Decorator::BOOTSTRAP (twitter bootstrap style)
 *   Name of submit button,
 *   Name of cancel button
 * );
 *
 * @category EasyBib
 * @package  EasyBib_Form
 * @author   Michael Scholl <michael@sch0ll.de>
 * @license  http://www.opensource.org/licenses/mit-license.html MIT License
 * @version  Release: @package_version@
 * @link     https://github.com/easybib/EasyBib_Form_Decorator
 */
class EasyBib_Form_Decorator
{
    /**
     * Constants Definition for Decorator
     */
    const TABLE = 'table';

    const DIV = 'div';

    const BOOTSTRAP = 'bootstrap';

    /**
     * Element Decorator
     *
     * @staticvar array
     */
    protected static $_ElementDecorator = array(
        'table' => array(
            'ViewHelper',
            array(
                'Description',
                array(
                    'tag' => '',
                    'escape' => false,
                    'image' => '/images/icons/information.png'
                )
            ),
            'Errors',
            array(
                array(
                    'data' => 'HtmlTag'
                ),
                array(
                    'tag' => 'td'
                )
            ),
            array(
                'Label',
                array(
                    'tag' => 'td'
                )
            ),
            array(
                array(
                    'row' => 'HtmlTag'
                ),
                array(
                    'tag' => 'tr'
                )
            )
        ),
        'div' => array(
            array(
                'ViewHelper'
            ),
            array(
                'Errors'
            ),
            array(
                'Description',
                array(
                    'tag'   => 'span',
                    'class' => 'hint'
                )
            ),
            array(
                'Label'
            ),
            array(
                'HtmlTag',
                array(
                    'tag' => 'div'
                )
            )
        ),
        'bootstrap' => array(
            array(
                'ViewHelper'
            ),
            array(
                'BootstrapErrors'
            ),
            array(
                'Description',
                array(
                    'tag'   => 'span',
                    'class' => 'help-inline'
                )
            ),
            array(
                'BootstrapTag',
                array(
                    'class' => 'input'
                )
            ),
            array(
                'Label'
            ),
            array(
                'HtmlTag',
                array(
                    'tag'   => 'div',
                    'class' => 'clearfix'
                )
            )
        )
    );

    /**
     * Submit Element Decorator
     *
     * @staticvar array
     */
    protected static $_SubmitDecorator = array(
        'table' => array(
            'ViewHelper'
        ),
        'div' => array(
            'ViewHelper'
        ),
        'bootstrap' => array(
            'ViewHelper',
            array(
                'HtmlTag',
                array(
                    'tag'   => 'div',
                    'class' => 'actions',
                    'openOnly' => false
                )
            )
        )
    );

    /**
     * Reset Element Decorator
     *
     * @staticvar array
     */
    protected static $_ResetDecorator = array(
        'table' => array(
            'ViewHelper'
        ),
        'div' => array(
            'ViewHelper'
        ),
        'bootstrap' => array(
            'ViewHelper',
            array(
                'HtmlTag',
                array(
                    'closeOnly' => false
                )
            )
        )
    );

    /**
     * Hiden Element Decorator
     *
     * @staticvar array
     */
    protected static $_HiddenDecorator = array(
        'table' => array(
            'ViewHelper'
        ),
        'div' => array(
            'ViewHelper'
        ),
        'bootstrap' => array(
            'ViewHelper'
        )
    );

    /**
     * Form Element Decorator
     *
     * @staticvar array
     */
    protected static $_FormDecorator = array(
        'table' => array(
            'FormElements',
            'Form'
        ),
        'div' => array(
            'FormElements',
            'Form'
        ),
        'bootstrap' => array(
            'FormElements',
            'Form'
        )
    );

    /**
     * DisplayGroup Decorator
     *
     * @staticvar array
     */
    protected static $_DisplayGroupDecorator = array(
        'table' => array(
            'FormElements',
            array(
                'HtmlTag',
                array(
                    'tag' => 'table',
                    'summary' => ''
                )
            ),
            'Fieldset'
        ),
        'div' => array(
            'FormElements',
            'Fieldset'
        ),
        'bootstrap' => array(
            'FormElements',
            'Fieldset'
        )

    );

    /**
     * Set the form decorators by the given string format or by the default div style
     *
     * @param object $objForm        Zend_Form pointer-reference
     * @param string $constFormat    Project_Plugin_FormDecoratorDefinition constants
     * @return NULL
     */
    public static function setFormDecorator(Zend_Form $form, $format = self::BOOTSTRAP, $submit_str = 'submit', $cancel_str = 'cancel') {
        /**
         * - disable default decorators
         * - set form & displaygroup decorators
         */
        $form->setDisableLoadDefaultDecorators(true);
        $form->setDisplayGroupDecorators(self::$_DisplayGroupDecorator[$format]);
        $form->setDecorators(self::$_FormDecorator[$format]);

        // set needed prefix path for bootstrap decorators
        if ($format == self::BOOTSTRAP) {
            $form->addElementPrefixPath(
                'EasyBib_Form_Decorator',
                'EasyBib/Form/Decorator',
                Zend_Form::DECORATOR
            );
        }

        // set form element decorators
        $form->setElementDecorators(self::$_ElementDecorator[$format]);

        // set submit button decorators
        if ($form->getElement($submit_str)) {
            $form->getElement($submit_str)->setDecorators(self::$_SubmitDecorator[$format]);
            if ($format == self::BOOTSTRAP) {
                $attribs = $form->getElement($submit_str)->getAttrib('class');
                if (empty($attribs)) {
                    $attribs = array('btn', 'primary');
                } else {
                    if (is_string($attribs)) {
                        $attribs = array($attribs);
                    }
                    $attribs = array_unique(array_merge(array('btn'), $attribs));
                }
                $form->getElement($submit_str)
                    ->setAttrib('class', $attribs)
                    ->setAttrib('type', 'submit');
                if ($form->getElement($cancel_str)) {
                    $form->getElement($submit_str)->getDecorator('HtmlTag')
                        ->setOption('openOnly', true);
                }
            }
        }

        // set cancel button decorators
        if ($form->getElement($cancel_str)) {
            $form->getElement($cancel_str)->setDecorators(self::$_ResetDecorator[$format]);
            if ($format == self::BOOTSTRAP) {
                $attribs = $form->getElement($cancel_str)->getAttrib('class');
                if (empty($attribs)) {
                    $attribs = array('btn');
                } else {
                    if (is_string($attribs)) {
                        $attribs = array($attribs);
                    }
                    $attribs = array_unique(array_merge(array('btn'), $attribs));
                }
                $form->getElement($cancel_str)
                    ->setAttrib('class', $attribs)
                    ->setAttrib('type', 'reset');
                if ($form->getElement($submit_str)) {
                    $form->getElement($cancel_str)->getDecorator('HtmlTag')
                        ->setOption('closeOnly', true);
                }
            }
        }

        // set hidden input decorators
        foreach ($form->getElements() as $e) {
            if ($e->getType() == 'Zend_Form_Element_Hidden') {
                $e->setDecorators(self::$_HiddenDecorator[$format]);
            }
        }
    }
}


text:
<?php
/**
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 * PHP Version 5
 *
 * @category   EasyBib
 * @package    EasyBib_Form
 * @subpackage Decorator
 * @author     Michael Scholl <michael@sch0ll.de>
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @version    git: $id$
 * @link       https://github.com/easybib/EasyBib_Form_Decorator
 */

/**
 * Ez_Form_Decorator_BootstrapTag
 *
 * Wraps content in an HTML block tag.
 *
 * Options accepted are:
 * - tag: tag to use in decorator
 * - noAttribs: do not render attributes in the opening tag
 * - placement: 'append' or 'prepend'. If 'append', renders opening and
 *   closing tag after content; if prepend, renders opening and closing tag
 *   before content.
 * - openOnly: render opening tag only
 * - closeOnly: render closing tag only
 *
 * Any other options passed are processed as HTML attributes of the tag.
 *
 * @category   EasyBib
 * @package    EasyBib_Form
 * @subpackage Decorator
 * @author     Michael Scholl <michael@sch0ll.de>
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @version    Release: @package_version@
 * @link       https://github.com/easybib/EasyBib_Form_Decorator
 */
class EasyBib_Form_Decorator_BootstrapTag extends Zend_Form_Decorator_HtmlTag
{
    /**
     * Render content wrapped in an HTML tag
     *
     * @param  string $content
     * @return string
     */
    public function render($content)
    {
        $tag       = $this->getTag();
        $placement = $this->getPlacement();
        $noAttribs = $this->getOption('noAttribs');
        $openOnly  = $this->getOption('openOnly');
        $closeOnly = $this->getOption('closeOnly');
        $this->removeOption('noAttribs');
        $this->removeOption('openOnly');
        $this->removeOption('closeOnly');

        $attribs = null;
        if (!$noAttribs) {
            $attribs = $this->getOptions();
        }

        switch ($placement) {
            case self::APPEND:
                if ($closeOnly) {
                    return $content . $this->_getCloseTag($tag);
                }
                if ($openOnly) {
                    return $content . $this->_getOpenTag($tag, $attribs);
                }
                return $content
                     . $this->_getOpenTag($tag, $attribs)
                     . $this->_getCloseTag($tag);
            case self::PREPEND:
                if ($closeOnly) {
                    return $this->_getCloseTag($tag) . $content;
                }
                if ($openOnly) {
                    return $this->_getOpenTag($tag, $attribs) . $content;
                }
                return $this->_getOpenTag($tag, $attribs)
                     . $this->_getCloseTag($tag)
                     . $content;
            default:
                return (($openOnly || !$closeOnly) ? $this->_getOpenTag($tag, $attribs) : '')
                     . $content
                     . (($closeOnly || !$openOnly) ? $this->_getCloseTag($tag) : '');
        }
    }

}

repo_name: michael-romer/zf-boilerplate

repo_language: PHP

mime_type: text/html


text:
<?php
/**
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 * PHP Version 5
 *
 * @category   EasyBib
 * @package    EasyBib_Form
 * @subpackage Decorator
 * @author     Michael Scholl <michael@sch0ll.de>
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @version    git: $id$
 * @link       https://github.com/easybib/EasyBib_Form_Decorator
 */

/**
 * Ez_Form_Decorator_BootstrapErrors
 *
 * Wraps errors in span with class help-inline
 *
 * @category   EasyBib
 * @package    EasyBib_Form
 * @subpackage Decorator
 * @author     Michael Scholl <michael@sch0ll.de>
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @version    Release: @package_version@
 * @link       https://github.com/easybib/EasyBib_Form_Decorator
 */
class EasyBib_Form_Decorator_BootstrapErrors extends Zend_Form_Decorator_HtmlTag
{
    /**
     * Render content wrapped in an HTML tag
     *
     * @param  string $content
     * @return string
     */
    public function render($content)
    {
        $element = $this->getElement();
        $view    = $element->getView();
        if (null === $view) {
            return $content;
        }

        $errors = $element->getMessages();
        if (empty($errors)) {
            return $content;
        }

        $separator = $this->getSeparator();
        $placement = $this->getPlacement();
        $formErrorHelper = $view->getHelper('formErrors');
        $formErrorHelper->setElementStart('')
            ->setElementSeparator('
')
            ->setElementSeparator('');
        $errors = $formErrorHelper->formErrors($errors, array('class' => 'help-inline'));

        switch ($placement) {
            case 'PREPEND':
                return $errors . $separator . $content;
            case 'APPEND':
            default:
                return $content . $separator . $errors;
        }
    }

}


text:
<?php
namespace App\Entity;

/**
 * @Entity(repositoryClass="App\Repository\Quote")
 * @Table(name="quote")
 */
class Quote
{
    /**
     * @Id @Column(type="integer", name="id")
     * @GeneratedValue
     */
    private $_id;
    /** @Column(type="string", name="wording") */
    private $_wording;
    /** @Column(type="string", name="author") */
    private $_author;

    public function getId()
    {
        return $this->_id;
    }

    public function getWording()
    {
        return $this->_wording;
    }

    public function setWording($wording)
    {
        $this->_wording = $wording;
        return $this;
    }

    public function getAuthor()
    {
        return $this->_author;
    }

    public function setAuthor($author)
    {
        $this->_author = $author;
        return $this;
    }

    public function __toString()
    {
        return $this->getWording();
    }

}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Michael
 * Date: 15.09.11
 * Time: 06:44
 * To change this template use File | Settings | File Templates.
 */
namespace App\Webservice;

class Calls
{
    /**
     * Returns a random quote using the RandomQuote Service
     * @param App_Webservice_Types_Request_RandomQuoteRequest $request
     * @return  App_Webservice_Types_Response_RandomQuoteResponse $response
     */
    public function randomQuote($request)
    {
        $sc = \Zend_Registry::get('sc');
        $srv = $sc->getService('randomQuote');
        $quote = $srv->getQuote();
        $response = new \App_Webservice_Types_Response_RandomQuoteResponse();
        $response->quote->wording = $quote[0];
        $response->quote->author = $quote[1];
        return $response;
    }

    /**
     * Returns a quote from the Database using an ID given
     * @param App_Webservice_Types_Request_QuoteRequest $request
     * @return  App_Webservice_Types_Response_QuoteResponse $response
     */
    public function quote($request)
    {
        $em = \Zend_Registry::get('em');
        $quote = $em->getRepository("\App\Entity\Quote")->find($request->id);
        $response = new \App_Webservice_Types_Response_QuoteResponse();

        if (!is_null($quote)) {
            $response->quote->wording = $quote->getWording();
            $response->quote->author = $quote->getAuthor();
            return $response;
        } else {
            return new \SoapFault(
                (string) "404", "Quote with ID " .
                ($request->id) . " not found in DB."
            );
        }
    }
}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Michael
 * Date: 05.10.11
 * Time: 20:16
 * To change this template use File | Settings | File Templates.
 */

class App_Webservice_Types_Complex_Quote
{

    /**
     * @var string
     */
    public $wording;

    /**
     * @var string
     */
    public $author;

}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Michael
 * Date: 17.09.11
 * Time: 06:52
 * To change this template use File | Settings | File Templates.
 */

class App_Webservice_Types_Response_RandomQuoteResponse
{
    /**
     * @var App_Webservice_Types_Complex_Quote
     */
    public $quote;
}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Michael
 * Date: 17.09.11
 * Time: 06:52
 * To change this template use File | Settings | File Templates.
 */

class App_Webservice_Types_Response_QuoteResponse
{
    /**
     * @var App_Webservice_Types_Complex_Quote
     */
    public $quote;
}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Michael
 * Date: 17.09.11
 * Time: 06:51
 * To change this template use File | Settings | File Templates.
 */

class App_Webservice_Types_Request_QuoteRequest
{
    /**
     * @var int
     */
    public $id;
}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Michael
 * Date: 17.09.11
 * Time: 06:51
 * To change this template use File | Settings | File Templates.
 */

class App_Webservice_Types_Request_RandomQuoteRequest
{
}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Michael
 * Date: 07.10.11
 * Time: 04:43
 * To change this template use File | Settings | File Templates.
 */

namespace App\Form;

class AddQuote extends \EasyBib_Form
{
    public function init()
    {
        // $this->setDefaultTranslator(\Zend_Registry::get('Zend_Translate')); ???
        $this->setMethod('POST');
        $this->setAction($this->getView()->baseUrl('/index/add-custom'));
        $this->setAttrib('id', 'addQuote');

        $quote = new \Zend_Form_Element_Textarea('quote');
        $name = new \Zend_Form_Element_Text('name');
        $submit = new \Zend_Form_Element_Button('submit');

        $quote->setLabel('Your wise words:')
            ->setRequired(true)
            ->setAttrib('rows', '4')
            ->setTranslator(\Zend_Registry::get('Zend_Translate'));

        $name->setLabel('Your name:')
            ->setRequired(true);

        $submit->setLabel('List my quote');
        $this->addElements(array($quote, $name, $submit));

        \EasyBib_Form_Decorator::setFormDecorator(
            $this, \EasyBib_Form_Decorator::BOOTSTRAP, 'submit'
        );
    }

    public function isValid($data)
    {
        if (!is_array($data)) {
            require_once 'Zend/Form/Exception.php';
            throw new \Zend_Form_Exception(__METHOD__ . ' expects an array');
        }
        return parent::isValid($data);
    }
}


text:
<?php
namespace App\Repository;

use Doctrine\ORM\EntityRepository;

class Quote extends EntityRepository
{
    public function findThemAll()
    {
        $stmt = 'SELECT q FROM App\Entity\Quote q ORDER BY q._id DESC';
        return $this->_em->createQuery($stmt)->getResult();
    }
}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Michael
 * Date: 14.03.11
 * Time: 13:57
 * To change this template use File | Settings | File Templates.
 */
namespace App\Service;

class RandomQuote
{
    protected $_randomizer;
    private $_quotes = array(
        array("There are only two ways to live your life. One is as
              though nothing is a miracle. The other is as though
              everything is a miracle.", "Albert Einstein"),
        array("One of the most tragic things I know about human nature
              is that all of us tend to put off living. We are all
              dreaming of some magical rose garden over the
              horizon-instead of enjoying the roses blooming outside
              our windows today.", "Dale Carnegie"),
        array("Never let your memories be greater than your dreams.",
              "Doug Ivester"),
        array("The most important thing about goals is having one.",
              "Geoffry F. Abert"),
        array("All great changes are preceded by chaos.", "Deepak Chopra"),
        array("Don’t go around saying the world owes you a living.
              The world owes you nothing. It was here first.", "Mark Twain"),
        array("Take care of your body. It’s the only place you have to live.",
              "Jim Rohn"),
        array("One person with a belief is equal to a force of 99 who have
              only interests.", "John Stuart Mill"),
        array("Do what you love and the money will follow.", "Marsha Sinetar"),
        array("The world makes way for the man who knows where he is going.",
              "Ralph Waldo Emerson"),
        array("You will not do incredible things without an incredible dream.",
              "John Eliot"),
        array("You are never too old to set another goal or to dream a new
              dream.", "Les Brown")
        );

    public function __construct($randomizer)
    {
        $this->_randomizer = $randomizer;
    }

    public function getQuote()
    {
        $n = $this->_randomizer->getNumber(0, count($this->_quotes)-1);
        return $this->_quotes[$n];
    }
}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Michael
 * Date: 14.03.11
 * Time: 13:57
 * To change this template use File | Settings | File Templates.
 */
namespace App\Service;

class Randomizer
{
    public function getNumber($low, $high)
    {
        return rand($low, $high);
    }
}


text:
<?php
require_once('bootstrap.php');
echo exec('php doctrine.php orm:schema-tool:drop --force') . PHP_EOL;
echo exec('php doctrine.php orm:schema-tool:create') . PHP_EOL;


text:
<?php
require_once('bootstrap.php');
passthru('php doctrine.php migrations:migrate');


text:
<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Tool
 * @subpackage Framework
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */

/**
 * ZF
 *
 * @category   Zend
 * @package    Zend_Tool
 * @subpackage Framework
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class ZF
{

    /**
     * @var bool
     */
    protected $_clientLoaded = false;

    /**
     * @var string
     */
    protected $_mode = 'runTool';

    /**
     * @var array of messages
     */
    protected $_messages = array();

    /**
     * @var string
     */
    protected $_homeDirectory = null;

    /**
     * @var string
     */
    protected $_storageDirectory = null;

    /**
     * @var string
     */
    protected $_configFile = null;

    /**
     * main()
     *
     * @return void
     */
    public static function main()
    {
        $zf = new self();
        $zf->bootstrap();
        $zf->run();
    }

    /**
     * bootstrap()
     *
     * @return ZF
     */
    public function bootstrap()
    {
        // detect settings
        $this->_mode             = $this->_detectMode();
        $this->_homeDirectory    = $this->_detectHomeDirectory();
        $this->_storageDirectory = $this->_detectStorageDirectory();
        $this->_configFile       = $this->_detectConfigFile();

        // setup
        $this->_setupPHPRuntime();
        $this->_setupToolRuntime();
    }

    /**
     * run()
     *
     * @return ZF
     */
    public function run()
    {
        switch ($this->_mode) {
            case 'runError':
                $this->_runError();
                $this->_runInfo();
                break;
            case 'runSetup':
                if ($this->_runSetup() === false) {
                    $this->_runInfo();
                }
                break;
            case 'runInfo':
                $this->_runInfo();
                break;
            case 'runTool':
            default:
                $this->_runTool();
                break;
        }

        return $this;
    }

    /**
     * _detectMode()
     *
     * @return ZF
     */
    protected function _detectMode()
    {
        $arguments = $_SERVER['argv'];

        $mode = 'runTool';

        if (!isset($arguments[0])) {
            return $mode;
        }

        if ($arguments[0] == $_SERVER['PHP_SELF']) {
            $this->_executable = array_shift($arguments);
        }

        if (!isset($arguments[0])) {
            return $mode;
        }

        if ($arguments[0] == '--setup') {
            $mode = 'runSetup';
        } elseif ($arguments[0] == '--info') {
            $mode = 'runInfo';
        }

        return $mode;
    }

    /**
     * _detectHomeDirectory() - detect the home directory in a variety of different places
     *
     * @param bool $mustExist Should the returned value already exist in the file system
     * @param bool $returnMessages Should it log messages for output later
     * @return string
     */
    protected function _detectHomeDirectory($mustExist = true, $returnMessages = true)
    {
        $homeDirectory = null;

        $homeDirectory = getenv('ZF_HOME'); // check env var ZF_HOME
        if ($homeDirectory) {
            $this->_logMessage('Home directory found in environment variable ZF_HOME with value ' . $homeDirectory, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($homeDirectory))) {
                return $homeDirectory;
            } else {
                $this->_logMessage('Home directory does not exist at ' . $homeDirectory, $returnMessages);
            }
        }

        $homeDirectory = getenv('HOME'); // HOME environment variable

        if ($homeDirectory) {
            $this->_logMessage('Home directory found in environment variable HOME with value ' . $homeDirectory, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($homeDirectory))) {
                return $homeDirectory;
            } else {
                $this->_logMessage('Home directory does not exist at ' . $homeDirectory, $returnMessages);
            }

        }

        $homeDirectory = getenv('HOMEPATH');

        if ($homeDirectory) {
            $this->_logMessage('Home directory found in environment variable HOMEPATH with value ' . $homeDirectory, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($homeDirectory))) {
                return $homeDirectory;
            } else {
                $this->_logMessage('Home directory does not exist at ' . $homeDirectory, $returnMessages);
            }
        }

        $homeDirectory = getenv('USERPROFILE');

        if ($homeDirectory) {
            $this->_logMessage('Home directory found in environment variable USERPROFILE with value ' . $homeDirectory, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($homeDirectory))) {
                return $homeDirectory;
            } else {
                $this->_logMessage('Home directory does not exist at ' . $homeDirectory, $returnMessages);
            }
        }

        return false;
    }

    /**
     * _detectStorageDirectory() - Detect where the storage directory is from a variaty of possiblities
     *
     * @param bool $mustExist Should the returned value already exist in the file system
     * @param bool $returnMessages Should it log messages for output later
     * @return string
     */
    protected function _detectStorageDirectory($mustExist = true, $returnMessages = true)
    {
        $storageDirectory = false;

        $storageDirectory = getenv('ZF_STORAGE_DIR');
        if ($storageDirectory) {
            $this->_logMessage('Storage directory path found in environment variable ZF_STORAGE_DIR with value ' . $storageDirectory, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($storageDirectory))) {
                return $storageDirectory;
            } else {
                $this->_logMessage('Storage directory does not exist at ' . $storageDirectory, $returnMessages);
            }
        }

        $homeDirectory = ($this->_homeDirectory) ? $this->_homeDirectory : $this->_detectHomeDirectory(true, false);

        if ($homeDirectory) {
            $storageDirectory = $homeDirectory . '/.zf/';
            $this->_logMessage('Storage directory assumed in home directory at location ' . $storageDirectory, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($storageDirectory))) {
                return $storageDirectory;
            } else {
                $this->_logMessage('Storage directory does not exist at ' . $storageDirectory, $returnMessages);
            }
        }

        return false;
    }

    /**
     * _detectConfigFile() - Detect config file location from a variety of possibilities
     *
     * @param bool $mustExist Should the returned value already exist in the file system
     * @param bool $returnMessages Should it log messages for output later
     * @return string
     */
    protected function _detectConfigFile($mustExist = true, $returnMessages = true)
    {
        $configFile = null;

        $configFile = getenv('ZF_CONFIG_FILE');
        if ($configFile) {
            $this->_logMessage('Config file found environment variable ZF_CONFIG_FILE at ' . $configFile, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($configFile))) {
                return $configFile;
            } else {
                $this->_logMessage('Config file does not exist at ' . $configFile, $returnMessages);
            }
        }

        $homeDirectory = ($this->_homeDirectory) ? $this->_homeDirectory : $this->_detectHomeDirectory(true, false);
        if ($homeDirectory) {
            $configFile = $homeDirectory . '/.zf.ini';
            $this->_logMessage('Config file assumed in home directory at location ' . $configFile, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($configFile))) {
                return $configFile;
            } else {
                $this->_logMessage('Config file does not exist at ' . $configFile, $returnMessages);
            }
        }

        $storageDirectory = ($this->_storageDirectory) ? $this->_storageDirectory : $this->_detectStorageDirectory(true, false);
        if ($storageDirectory) {
            $configFile = $storageDirectory . '/zf.ini';
            $this->_logMessage('Config file assumed in storage directory at location ' . $configFile, $returnMessages);
            if (!$mustExist || ($mustExist && file_exists($configFile))) {
                return $configFile;
            } else {
                $this->_logMessage('Config file does not exist at ' . $configFile, $returnMessages);
            }
        }

        return false;
    }

    /**
     * _setupPHPRuntime() - parse the config file if it exists for php ini values to set
     *
     * @return void
     */
    protected function _setupPHPRuntime()
    {
        // set php runtime settings
        ini_set('display_errors', true);

        // support the changing of the current working directory, necessary for some providers
        $cwd = getenv('ZEND_TOOL_CURRENT_WORKING_DIRECTORY');
        if ($cwd != '' && realpath($cwd)) {
            chdir($cwd);
        }

        if (!$this->_configFile) {
            return;
        }
        $zfINISettings = parse_ini_file($this->_configFile);
        $phpINISettings = ini_get_all();
        foreach ($zfINISettings as $zfINIKey => $zfINIValue) {
            if (substr($zfINIKey, 0, 4) === 'php.') {
                $phpINIKey = substr($zfINIKey, 4);
                if (array_key_exists($phpINIKey, $phpINISettings)) {
                    ini_set($phpINIKey, $zfINIValue);
                }
            }
        }
    }

    /**
     * _setupToolRuntime() - setup the tools include_path and load the proper framwork parts that
     * enable Zend_Tool to work.
     *
     * @return void
     */
    protected function _setupToolRuntime()
    {

        $includePathPrepend = getenv('ZEND_TOOL_INCLUDE_PATH_PREPEND');
        $includePathFull = getenv('ZEND_TOOL_INCLUDE_PATH');

        // check if the user has not provided anything
        if (!($includePathPrepend || $includePathFull)) {
            if ($this->_tryClientLoad()) {
                return;
            }
        }

        // if ZF is not in the include_path, but relative to this file, put it in the include_path
        if ($includePathPrepend || $includePathFull) {
            if (isset($includePathPrepend) && ($includePathPrepend !== false)) {
                set_include_path($includePathPrepend . PATH_SEPARATOR . get_include_path());
            } elseif (isset($includePathFull) && ($includePathFull !== false)) {
                set_include_path($includePathFull);
            }
        }

        if ($this->_tryClientLoad()) {
            return;
        }

        $zfIncludePath['relativePath'] = dirname(__FILE__) . '/../library/';
        if (file_exists($zfIncludePath['relativePath'] . 'Zend/Tool/Framework/Client/Console.php')) {
            set_include_path(realpath($zfIncludePath['relativePath']) . PATH_SEPARATOR . get_include_path());
        }

        if (!$this->_tryClientLoad()) {
            $this->_mode = 'runError';
            return;
        }
    }

    /**
     * _tryClientLoad() - Attempt to load the Zend_Tool_Framework_Client_Console to enable the tool to run.
     *
     * This method will return false if its not loaded to allow the consumer to alter the environment in such
     * a way that it can be called again to try loading the proper file/class.
     *
     * @return bool if the client is actuall loaded or not
     */
    protected function _tryClientLoad()
    {
        $this->_clientLoaded = false;
        $fh = @fopen('Zend/Tool/Framework/Client/Console.php', 'r', true);
        if (!$fh) {
            return $this->_clientLoaded; // false
        } else {
            fclose($fh);
            unset($fh);
            include 'Zend/Tool/Framework/Client/Console.php';
            $this->_clientLoaded = class_exists('Zend_Tool_Framework_Client_Console');
        }

        return $this->_clientLoaded;
    }

    /**
     * _runError() - Output the error screen that tells the user that the tool was not setup
     * in a sane way
     *
     * @return void
     */
    protected function _runError()
    {

        echo <<<EOS

***************************** ZF ERROR ********************************
In order to run the zf command, you need to ensure that Zend Framework
is inside your include_path.  There are a variety of ways that you can
ensure that this zf command line tool knows where the Zend Framework
library is on your system, but not all of them can be described here.

The easiest way to get the zf command running is to give it the include
path via an environment variable ZEND_TOOL_INCLUDE_PATH or
ZEND_TOOL_INCLUDE_PATH_PREPEND with the proper include path to use,
then run the command "zf --setup".  This command is designed to create
a storage location for your user, as well as create the zf.ini file
that the zf command will consult in order to run properly on your
system.

Example you would run:

$ ZEND_TOOL_INCLUDE_PATH=/path/to/library zf --setup

Your are encourged to read more in the link that follows.

EOS;

    }

    /**
     * _runInfo() - this command will produce information about the setup of this script and
     * Zend_Tool
     *
     * @return void
     */
    protected function _runInfo()
    {
        echo 'Zend_Tool & CLI Setup Information' . PHP_EOL
           . '(available via the command line "zf --info")'
           . PHP_EOL;

        echo '   * ' . implode(PHP_EOL . '   * ', $this->_messages) . PHP_EOL;

        echo PHP_EOL;

        echo 'To change the setup of this tool, run: "zf --setup"';

        echo PHP_EOL;

    }

    /**
     * _runSetup() - parse the request to see which setup command to run
     *
     * @return void
     */
    protected function _runSetup()
    {
        $setupCommand = (isset($_SERVER['argv'][2])) ? $_SERVER['argv'][2] : null;

        switch ($setupCommand) {
            case 'storage-directory':
                $this->_runSetupStorageDirectory();
                break;
            case 'config-file':
                $this->_runSetupConfigFile();
                break;
            default:
                $this->_runSetupMoreInfo();
                break;
        }
    }

    /**
     * _runSetupStorageDirectory() - if the storage directory does not exist, create it
     *
     * @return void
     */
    protected function _runSetupStorageDirectory()
    {
        $storageDirectory = $this->_detectStorageDirectory(false, false);

        if (file_exists($storageDirectory)) {
            echo 'Directory already exists at ' . $storageDirectory . PHP_EOL
               . 'Cannot create storage directory.';
            return;
        }

        mkdir($storageDirectory);

        echo 'Storage directory created at ' . $storageDirectory . PHP_EOL;
    }

    /**
     * _runSetupConfigFile()
     *
     * @return void
     */
    protected function _runSetupConfigFile()
    {
        $configFile = $this->_detectConfigFile(false, false);

        if (file_exists($configFile)) {
            echo 'File already exists at ' . $configFile . PHP_EOL
               . 'Cannot write new config file.';
            return;
        }

        $includePath = get_include_path();

        $contents = 'php.include_path = "' . $includePath . '"';

        file_put_contents($configFile, $contents);

        $iniValues = ini_get_all();
        if ($iniValues['include_path']['global_value'] != $iniValues['include_path']['local_value']) {
            echo 'NOTE: the php include_path to be used with the tool has been written' . PHP_EOL
               . 'to the config file, using ZEND_TOOL_INCLUDE_PATH (or other include_path setters)' . PHP_EOL
               . 'is no longer necessary.' . PHP_EOL . PHP_EOL;
        }

        echo 'Config file written to ' . $configFile . PHP_EOL;
    }

    /**
     * _runSetupMoreInfo() - return more information about what can be setup, and what is setup
     *
     * @return void
     */
    protected function _runSetupMoreInfo()
    {
        $homeDirectory    = $this->_detectHomeDirectory(false, false);
        $storageDirectory = $this->_detectStorageDirectory(false, false);
        $configFile       = $this->_detectConfigFile(false, false);

        echo <<<EOS

ZF Command Line Tool - Setup
----------------------------

Current Paths (Existing or not):
    Home Directory: {$homeDirectory}
    Storage Directory: {$storageDirectory}
    Config File: {$configFile}

Important Environment Variables:
    ZF_HOME
        - the directory this tool will look for a home directory
        - directory must exist
    ZF_STORAGE_DIR
        - where this tool will look for a storage directory
        - directory must exist
    ZF_CONFIG_FILE
        - where this tool will look for a configuration file
    ZF_TOOL_INCLUDE_PATH
        - set the include_path for this tool to use this value
    ZF_TOOL_INCLUDE_PATH_PREPEND
        - prepend the current php.ini include_path with this value

Search Order:
    Home Directory:
        - ZF_HOME, then HOME (*nix), then HOMEPATH (windows)
    Storage Directory:
        - ZF_STORAGE_DIR, then {home}/.zf/
    Config File:
        - ZF_CONFIG_FILE, then {home}/.zf.ini, then {home}/zf.ini,
          then {storage}/zf.ini

Commands:
    zf --setup storage-directory
        - setup the storage directory, directory will be created
    zf --setup config-file
        - create the config file with some default values

EOS;
    }

    /**
     * _runTool() - This is where the magic happens, dispatch Zend_Tool
     *
     * @return void
     */
    protected function _runTool()
    {

        $configOptions = array();
        if (isset($this->_configFile) && $this->_configFile) {
            $configOptions['configOptions']['configFilepath'] = $this->_configFile;
        }
        if (isset($this->_storageDirectory) && $this->_storageDirectory) {
            $configOptions['storageOptions']['directory'] = $this->_storageDirectory;
        }

        // ensure that zf.php loads the Zend_Tool_Project features
        $configOptions['classesToLoad'] = 'Zend_Tool_Project_Provider_Manifest';

        $console = new Zend_Tool_Framework_Client_Console($configOptions);
        $console->dispatch();
    }

    /**
     * _logMessage() - Internal method used to log setup and information messages.
     *
     * @param string $message
     * @param bool   $storeMessage
     * @return void
     */
    protected function _logMessage($message, $storeMessage = true)
    {
        if (!$storeMessage) {
            return;
        }

        $this->_messages[] = $message;
    }

}

if (!getenv('ZF_NO_MAIN')) {
    ZF::main();
}


text:
<?php
require_once('bootstrap.php');
echo exec('php doctrine.php orm:schema-tool:drop --force') . PHP_EOL;
echo exec('php doctrine.php orm:schema-tool:create') . PHP_EOL;
$container = $application->getBootstrap()->getResource('doctrine');
$em = $container->getEntityManager();
echo "Database fixtures loaded successfully!" . PHP_EOL;
require_once('../data/fixtures/fixtures.php');


text:
<?php
require_once('bootstrap.php');

define('INDEX_LABEL', 'quotes');

$client = Zend_Registry::get('es');

try {
    $index = $client->getIndex(INDEX_LABEL);
    $index->delete(array(), true);
    echo "Index " . INDEX_LABEL . " successfully dropped." . PHP_EOL;
} catch (Exception $e) {
    echo "Index " . INDEX_LABEL . " could not dropped (maybe already gone?)" . PHP_EOL;
}

try {
    $index = $client->getIndex(INDEX_LABEL);
    $index->create(array(), true);
    echo "Index " . INDEX_LABEL . " successfully created." . PHP_EOL;
} catch (Exception $e) {
    echo "Index " . INDEX_LABEL . " could not be created." . PHP_EOL;
}


text:
<?php
$folders = array('../library/App', '../application');
$path = implode(' ', $folders);
echo shell_exec('phpcs -v --standard=zend ' . $path) . PHP_EOL;


text:
<?php
require_once('bootstrap.php');
passthru('php doctrine.php migrations:migrate --dry-run');


text:
<?php
require_once('bootstrap.php');
// FIX ME: Not cross-platform compatible hack
echo exec('sudo service memcached restart') . PHP_EOL;
echo "Memcached succesfully cleared!" . PHP_EOL;


text:
<?php
echo PHP_EOL . "#####################" . PHP_EOL;
echo "#  PHP LOC Results  #" . PHP_EOL;
echo "#####################" . PHP_EOL;
echo shell_exec("phploc ../application ../library/App") . PHP_EOL;

echo PHP_EOL . "####################" . PHP_EOL;
echo "#  PHP MD Results  #" . PHP_EOL;
echo "####################" . PHP_EOL;
echo shell_exec("phpmd ../application,../library/App text design,codesize,unusedcode,naming");

echo PHP_EOL . "#####################" . PHP_EOL;
echo "#  PHP CPD Results  #" . PHP_EOL;
echo "#####################" . PHP_EOL;
echo shell_exec("phpcpd ../application ../library/App");

echo PHP_EOL . "########################" . PHP_EOL;
echo "#  PHP Depend Results  #" . PHP_EOL;
echo "########################" . PHP_EOL;
echo shell_exec("pdepend --summary-xml=codemetrics/summary.xml --jdepend-chart=codemetrics/jdepend.svg --overview-pyramid=codemetrics/pyramid.svg ../application,../library/App");


text:
<?php

require_once('bootstrap.php');

// Retrieve Doctrine Container resource
$container = $application->getBootstrap()->getResource('doctrine');

// Console
$cli = new \Symfony\Component\Console\Application(
    'Doctrine Command Line Interface',
    \Doctrine\Common\Version::VERSION
);

try {
    // Bootstrapping Console HelperSet
    $helperSet = array();

    if (($dbal = $container->getConnection(getenv('CONN') ?: $container->defaultConnection)) !== null) {
        $helperSet['db'] = new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($dbal);
    }

    if (($em = $container->getEntityManager(getenv('EM') ?: $container->defaultEntityManager)) !== null) {
        $helperSet['em'] = new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em);
    }

    $helperSet['dialog'] = new \Symfony\Component\Console\Helper\DialogHelper();

} catch (\Exception $e) {
    $cli->renderException($e, new \Symfony\Component\Console\Output\ConsoleOutput());
}

$cli->setCatchExceptions(true);
$cli->setHelperSet(new \Symfony\Component\Console\Helper\HelperSet($helperSet));

$cli->addCommands(array(
    new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(),
    new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(),
    new \Doctrine\DBAL\Migrations\Tools\Console\Command\DiffCommand(),
    new \Doctrine\DBAL\Migrations\Tools\Console\Command\ExecuteCommand(),
    new \Doctrine\DBAL\Migrations\Tools\Console\Command\GenerateCommand(),
    new \Doctrine\DBAL\Migrations\Tools\Console\Command\MigrateCommand(),
    new \Doctrine\DBAL\Migrations\Tools\Console\Command\StatusCommand(),
    new \Doctrine\DBAL\Migrations\Tools\Console\Command\VersionCommand(),
    new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(),
    new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(),
    new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(),
    new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(),
    new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(),
    new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(),
    new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(),
    new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(),
    new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(),
    new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(),
    new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(),
    new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(),
    new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(),
));

$cli->run();


text:
<?php
require_once('bootstrap.php');
passthru('php doctrine.php migration:diff') . PHP_EOL;


text:
<?php

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path(),
)));

include "Zend/Loader/Autoloader.php";
Zend_Loader_Autoloader::getInstance();

// Creating application
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);

// Bootstrapping resources
$application->bootstrap();


text:
<?xml version="1.0" encoding="UTF-8"?>

<project name="name-of-project" default="build" basedir=".">
 <property name="source" value="src"/>

 <target name="clean"
         description="Clean up and create artifact directories">
  <delete dir="${basedir}/build/api"/>
  <delete dir="${basedir}/build/code-browser"/>
  <delete dir="${basedir}/build/coverage"/>
  <delete dir="${basedir}/build/logs"/>
  <delete dir="${basedir}/build/pdepend"/>

  <mkdir dir="${basedir}/build/api"/>
  <mkdir dir="${basedir}/build/code-browser"/>
  <mkdir dir="${basedir}/build/coverage"/>
  <mkdir dir="${basedir}/build/logs"/>
  <mkdir dir="${basedir}/build/pdepend"/>
 </target>

 <target name="phpunit"
         description="Run unit tests using PHPUnit and generates junit.xml and clover.xml">
  <exec executable="phpunit" failonerror="true"/>
 </target>

 <target name="parallelTasks"
         description="Run the pdepend, phpmd, phpcpd, phpcs, phpdoc and phploc tasks in parallel using a maximum of 2 threads.">
  <parallel threadCount="2">
   <sequential>
    <antcall target="pdepend"/>
    <antcall target="phpmd"/>
   </sequential>
   <antcall target="phpcpd"/>
   <antcall target="phpcs"/>
   <antcall target="phpdoc"/>
   <antcall target="phploc"/>
  </parallel>
 </target>

 <target name="pdepend"
         description="Generate jdepend.xml and software metrics charts using PHP_Depend">
  <exec executable="pdepend">
   <arg line="--jdepend-xml=${basedir}/build/logs/jdepend.xml
              --jdepend-chart=${basedir}/build/pdepend/dependencies.svg
              --overview-pyramid=${basedir}/build/pdepend/overview-pyramid.svg
              ${source}" />
  </exec>
 </target>

 <target name="phpmd"
         description="Generate pmd.xml using PHPMD">
  <exec executable="phpmd">
   <arg line="${source}
              xml
              build/phpmd.xml
              --reportfile ${basedir}/build/logs/pmd.xml" />
  </exec>
 </target>

 <target name="phpcpd"
         description="Generate pmd-cpd.xml using PHPCPD">
  <exec executable="phpcpd">
   <arg line="--log-pmd ${basedir}/build/logs/pmd-cpd.xml ${source}" />
  </exec>
 </target>

 <target name="phploc"
         description="Generate phploc.csv">
  <exec executable="phploc">
   <arg line="--log-csv ${basedir}/build/logs/phploc.csv ${source}" />
  </exec>
 </target>

 <target name="phpcs"
         description="Generate checkstyle.xml using PHP_CodeSniffer">
  <exec executable="phpcs" output="/dev/null">
   <arg line="--report=checkstyle
              --report-file=${basedir}/build/logs/checkstyle.xml
              --standard=build/phpcs.xml
              ${source}" />
  </exec>
 </target>

 <target name="phpdoc"
         description="Generate API documentation using PHPDocumentor">
  <exec executable="phpdoc">
   <arg line="-d ${source} -t ${basedir}/build/api" />
  </exec>
 </target>

 <target name="phpcb"
         description="Aggregate tool output with PHP_CodeBrowser">
  <exec executable="phpcb">
   <arg line="--log    ${basedir}/build/logs
              --source ${source}
              --output ${basedir}/build/code-browser" />
  </exec>
 </target>

 <target name="build" depends="clean,parallelTasks,phpunit,phpcb"/>
</project>


text:
#!/bin/sh

#############################################################################
# Zend Framework
#
# LICENSE
#
# This source file is subject to the new BSD license that is bundled
# with this package in the file LICENSE.txt.
# It is also available through the world-wide-web at this URL:
# http://framework.zend.com/license/new-bsd
# If you did not receive a copy of the license and are unable to
# obtain it through the world-wide-web, please send an email
# to license@zend.com so we can send you a copy immediately.
#
# Zend
# Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
# http://framework.zend.com/license/new-bsd     New BSD License
#############################################################################

# find php: pear first, command -v second, straight up php lastly
if test "@php_bin@" != '@'php_bin'@'; then
    PHP_BIN="@php_bin@"
elif command -v php 1>/dev/null 2>/dev/null; then
    PHP_BIN=`command -v php`
else
    PHP_BIN=php
fi

# find zf.php: pear first, same directory 2nd,
if test "@php_dir@" != '@'php_dir'@'; then
    PHP_DIR="@php_dir@"
else
    SELF_LINK="$0"
    SELF_LINK_TMP="$(readlink "$SELF_LINK")"
    while test -n "$SELF_LINK_TMP"; do
        SELF_LINK="$SELF_LINK_TMP"
        SELF_LINK_TMP="$(readlink "$SELF_LINK")"
    done
    PHP_DIR="$(dirname "$SELF_LINK")"
fi

"$PHP_BIN" -d safe_mode=Off -f "$PHP_DIR/zf.php" -- "$@"


text:
<?php
require_once('bootstrap.php');
passthru('php doctrine.php migration:status') . PHP_EOL;


text:
<?php
require_once('bootstrap.php');
require_once('create-searchindex.php');

try {
    $client = Zend_Registry::get('es');
    $index = $client->getIndex(INDEX_LABEL);
    $type = $index->getType('quote');

    $em = Zend_Registry::get('em');
    $quotes = $em->getRepository("\App\Entity\Quote")->findAll();

    foreach($quotes as $quote)
    {
        $doc = new Elastica_Document(1,
           array('id' => $quote->getId(), 'wording' => $quote->getWording(), 'author' => $quote->getAuthor())
        );

        $type->addDocument($doc);
    }

    $index->refresh();
    echo "Fixtures successfully loaded." . PHP_EOL;
} catch (Exception $e) {
    echo "Fixtures could not be loaded." . PHP_EOL;
}


text:
@ECHO off
REM Zend Framework
REM
REM LICENSE
REM
REM This source file is subject to the new BSD license that is bundled
REM with this package in the file LICENSE.txt.
REM It is also available through the world-wide-web at this URL:
REM http://framework.zend.com/license/new-bsd
REM If you did not receive a copy of the license and are unable to
REM obtain it through the world-wide-web, please send an email
REM to license@zend.com so we can send you a copy immediately.
REM
REM Zend
REM Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
REM http://framework.zend.com/license/new-bsd     New BSD License

REM Test to see if this was installed via pear
SET ZTMPZTMPZTMPZ=@ph
SET TMPZTMPZTMP=%ZTMPZTMPZTMPZ%p_bin@
REM below @php_bin@
FOR %%x IN ("@php_bin@") DO (if %%x=="%TMPZTMPZTMP%" GOTO :NON_PEAR_INSTALLED)

GOTO PEAR_INSTALLED

:NON_PEAR_INSTALLED
REM Assume php.exe is executable, and that zf.php will reside in the
REM same file as this one
SET PHP_BIN=php.exe
SET PHP_DIR=%~dp0
GOTO RUN

:PEAR_INSTALLED
REM Assume this was installed via PEAR and use replacements php_bin & php_dir
SET PHP_BIN=@php_bin@
SET PHP_DIR=@php_dir@
GOTO RUN

:RUN
SET ZF_SCRIPT=%PHP_DIR%\zf.php
"%PHP_BIN%" -d safe_mode=Off -f "%ZF_SCRIPT%" -- %*


text:
name: Doctrine Migrations
migrations_namespace: DoctrineMigrations
table_name: doctrine_migration_versions
migrations_directory: ../data/migrations


text:
<?xml version="1.0" encoding="UTF-8"?>
<metrics generated="2011-10-08T20:17:59" pdepend="0.10.6" ahh="0.61538461538462" andc="0" calls="128" ccn="72" ccn2="72" cloc="128" clsa="0" clsc="18" eloc="535" fanout="35" leafs="14" lloc="283" loc="813" maxDIT="2" ncloc="685" noc="18" nof="0" noi="0" nom="41" nop="6" roots="4">
  <files>
    <file name="/vagrant/application/Bootstrap.php" cloc="0" eloc="47" lloc="25" loc="60" ncloc="60"/>
    <file name="/vagrant/application/modules/admin/controllers/ErrorController.php" cloc="4" eloc="40" lloc="28" loc="57" ncloc="53"/>
    <file name="/vagrant/application/modules/admin/controllers/IndexController.php" cloc="4" eloc="16" lloc="4" loc="33" ncloc="29"/>
    <file name="/vagrant/application/modules/my/controllers/ErrorController.php" cloc="4" eloc="40" lloc="28" loc="57" ncloc="53"/>
    <file name="/vagrant/application/modules/my/controllers/IndexController.php" cloc="4" eloc="16" lloc="4" loc="33" ncloc="29"/>
    <file name="/vagrant/application/modules/site/controllers/ErrorController.php" cloc="4" eloc="38" lloc="26" loc="55" ncloc="51"/>
    <file name="/vagrant/application/modules/site/controllers/IndexController.php" cloc="10" eloc="153" lloc="93" loc="194" ncloc="184"/>
    <file name="/vagrant/library/App/Webservice/Types/Complex/Quote.php" cloc="13" eloc="6" lloc="2" loc="24" ncloc="11"/>
    <file name="/vagrant/library/App/Webservice/Types/Request/QuoteRequest.php" cloc="10" eloc="5" lloc="1" loc="17" ncloc="7"/>
    <file name="/vagrant/library/App/Webservice/Types/Request/RandomQuoteRequest.php" cloc="7" eloc="4" lloc="0" loc="13" ncloc="6"/>
    <file name="/vagrant/library/App/Webservice/Types/Response/QuoteResponse.php" cloc="10" eloc="5" lloc="1" loc="17" ncloc="7"/>
    <file name="/vagrant/library/App/Webservice/Types/Response/RandomQuoteResponse.php" cloc="10" eloc="5" lloc="1" loc="17" ncloc="7"/>
    <file name="/vagrant/library/App/Entity/Quote.php" cloc="10" eloc="34" lloc="18" loc="51" ncloc="41"/>
    <file name="/vagrant/library/App/Form/AddQuote.php" cloc="7" eloc="32" lloc="18" loc="47" ncloc="40"/>
    <file name="/vagrant/library/App/Repository/Quote.php" cloc="0" eloc="11" lloc="5" loc="14" ncloc="14"/>
    <file name="/vagrant/library/App/Service/RandomQuote.php" cloc="7" eloc="43" lloc="8" loc="54" ncloc="47"/>
    <file name="/vagrant/library/App/Service/Randomizer.php" cloc="7" eloc="9" lloc="3" loc="18" ncloc="11"/>
    <file name="/vagrant/library/App/Webservice/Calls.php" cloc="17" eloc="31" lloc="18" loc="52" ncloc="35"/>
  </files>
  <package name="+global" cr="0.15" noc="12" nof="0" noi="0" nom="27" rcr="0.15">
    <class name="Bootstrap" ca="0" cbo="10" ce="10" cis="4" cloc="0" cr="0.15" csz="4" dit="2" eloc="39" impl="0" lloc="21" loc="58" ncloc="58" noam="4" nocc="0" nom="4" noom="0" npm="4" rcr="0.2775" vars="0" varsi="0" varsnp="0" wmc="4" wmci="4" wmcnp="4">
      <file name="/vagrant/application/Bootstrap.php"/>
      <method name="_initAutoloaderNamespaces" ccn="1" ccn2="1" cloc="0" eloc="20" lloc="10" loc="27" ncloc="27" npath="1"/>
      <method name="_initModuleLayout" ccn="1" ccn2="1" cloc="0" eloc="9" lloc="5" loc="12" ncloc="12" npath="1"/>
      <method name="_initServices" ccn="1" ccn2="1" cloc="0" eloc="6" lloc="4" loc="7" ncloc="7" npath="1"/>
      <method name="_initElasticSearch" ccn="1" ccn2="1" cloc="0" eloc="4" lloc="2" loc="5" ncloc="5" npath="1"/>
    </class>
    <class name="Admin_ErrorController" ca="0" cbo="1" ce="1" cis="2" cloc="4" cr="0.15" csz="2" dit="2" eloc="34" impl="0" lloc="26" loc="53" ncloc="49" noam="2" nocc="0" nom="2" noom="0" npm="2" rcr="0.17125" vars="0" varsi="0" varsnp="0" wmc="8" wmci="8" wmcnp="8">
      <file name="/vagrant/application/modules/admin/controllers/ErrorController.php"/>
      <method name="errorAction" ccn="6" ccn2="6" cloc="4" eloc="26" lloc="21" loc="37" ncloc="33" npath="16"/>
      <method name="getLog" ccn="2" ccn2="2" cloc="0" eloc="8" lloc="5" loc="9" ncloc="9" npath="2"/>
    </class>
    <class name="Admin_IndexController" ca="0" cbo="0" ce="0" cis="4" cloc="4" cr="0.15" csz="4" dit="2" eloc="8" impl="0" lloc="0" loc="25" ncloc="21" noam="4" nocc="0" nom="4" noom="0" npm="4" rcr="0.17125" vars="0" varsi="0" varsnp="0" wmc="4" wmci="4" wmcnp="4">
      <file name="/vagrant/application/modules/admin/controllers/IndexController.php"/>
      <method name="init" ccn="1" ccn2="1" cloc="1" eloc="2" lloc="0" loc="4" ncloc="3" npath="1"/>
      <method name="indexAction" ccn="1" ccn2="1" cloc="1" eloc="2" lloc="0" loc="4" ncloc="3" npath="1"/>
      <method name="headerAction" ccn="1" ccn2="1" cloc="1" eloc="2" lloc="0" loc="4" ncloc="3" npath="1"/>
      <method name="footerAction" ccn="1" ccn2="1" cloc="1" eloc="2" lloc="0" loc="4" ncloc="3" npath="1"/>
    </class>
    <class name="My_ErrorController" ca="0" cbo="1" ce="1" cis="2" cloc="4" cr="0.15" csz="2" dit="2" eloc="34" impl="0" lloc="26" loc="53" ncloc="49" noam="2" nocc="0" nom="2" noom="0" npm="2" rcr="0.17125" vars="0" varsi="0" varsnp="0" wmc="8" wmci="8" wmcnp="8">
      <file name="/vagrant/application/modules/my/controllers/ErrorController.php"/>
      <method name="errorAction" ccn="6" ccn2="6" cloc="4" eloc="26" lloc="21" loc="37" ncloc="33" npath="16"/>
      <method name="getLog" ccn="2" ccn2="2" cloc="0" eloc="8" lloc="5" loc="9" ncloc="9" npath="2"/>
    </class>
    <class name="My_IndexController" ca="0" cbo="0" ce="0" cis="4" cloc="4" cr="0.15" csz="4" dit="2" eloc="8" impl="0" lloc="0" loc="25" ncloc="21" noam="4" nocc="0" nom="4" noom="0" npm="4" rcr="0.17125" vars="0" varsi="0" varsnp="0" wmc="4" wmci="4" wmcnp="4">
      <file name="/vagrant/application/modules/my/controllers/IndexController.php"/>
      <method name="init" ccn="1" ccn2="1" cloc="1" eloc="2" lloc="0" loc="4" ncloc="3" npath="1"/>
      <method name="indexAction" ccn="1" ccn2="1" cloc="1" eloc="2" lloc="0" loc="4" ncloc="3" npath="1"/>
      <method name="headerAction" ccn="1" ccn2="1" cloc="1" eloc="2" lloc="0" loc="4" ncloc="3" npath="1"/>
      <method name="footerAction" ccn="1" ccn2="1" cloc="1" eloc="2" lloc="0" loc="4" ncloc="3" npath="1"/>
    </class>
    <class name="Site_ErrorController" ca="0" cbo="1" ce="1" cis="2" cloc="4" cr="0.15" csz="2" dit="2" eloc="32" impl="0" lloc="24" loc="51" ncloc="47" noam="2" nocc="0" nom="2" noom="0" npm="2" rcr="0.17125" vars="0" varsi="0" varsnp="0" wmc="9" wmci="9" wmcnp="9">
      <file name="/vagrant/application/modules/site/controllers/ErrorController.php"/>
      <method name="errorAction" ccn="7" ccn2="7" cloc="4" eloc="24" lloc="19" loc="35" ncloc="31" npath="20"/>
      <method name="getLog" ccn="2" ccn2="2" cloc="0" eloc="8" lloc="5" loc="9" ncloc="9" npath="2"/>
    </class>
    <class name="Site_IndexController" ca="0" cbo="9" ce="9" cis="7" cloc="10" cr="0.15" csz="12" dit="2" eloc="137" impl="0" lloc="81" loc="192" ncloc="182" noam="9" nocc="0" nom="9" noom="0" npm="7" rcr="0.17125" vars="3" varsi="3" varsnp="0" wmc="19" wmci="19" wmcnp="16">
      <file name="/vagrant/application/modules/site/controllers/IndexController.php"/>
      <method name="init" ccn="1" ccn2="1" cloc="0" eloc="3" lloc="1" loc="4" ncloc="4" npath="1"/>
      <method name="searchAction" ccn="4" ccn2="4" cloc="0" eloc="26" lloc="20" loc="32" ncloc="32" npath="5"/>
      <method name="addRandomAction" ccn="2" ccn2="2" cloc="0" eloc="17" lloc="11" loc="20" ncloc="20" npath="2"/>
      <method name="addCustomAction" ccn="4" ccn2="4" cloc="0" eloc="27" lloc="18" loc="33" ncloc="33" npath="4"/>
      <method name="indexAction" ccn="2" ccn2="2" cloc="0" eloc="13" lloc="8" loc="15" ncloc="15" npath="2"/>
      <method name="checkSearchindex" ccn="2" ccn2="2" cloc="0" eloc="10" lloc="7" loc="11" ncloc="11" npath="2"/>
      <method name="indexQuote" ccn="1" ccn2="1" cloc="0" eloc="13" lloc="7" loc="16" ncloc="16" npath="1"/>
      <method name="headerAction" ccn="1" ccn2="1" cloc="0" eloc="17" lloc="2" loc="19" ncloc="19" npath="1"/>
      <method name="footerAction" ccn="2" ccn2="2" cloc="0" eloc="11" lloc="7" loc="14" ncloc="14" npath="2"/>
    </class>
    <class name="App_Webservice_Types_Complex_Quote" ca="2" cbo="0" ce="0" cis="2" cloc="6" cr="0.15" csz="2" dit="0" eloc="0" impl="0" lloc="0" loc="14" ncloc="8" noam="0" nocc="0" nom="0" noom="0" npm="0" rcr="0.15" vars="2" varsi="2" varsnp="2" wmc="0" wmci="0" wmcnp="0">
      <file name="/vagrant/library/App/Webservice/Types/Complex/Quote.php"/>
    </class>
    <class name="App_Webservice_Types_Request_QuoteRequest" ca="0" cbo="0" ce="0" cis="1" cloc="3" cr="0.15" csz="1" dit="0" eloc="0" impl="0" lloc="0" loc="7" ncloc="4" noam="0" nocc="0" nom="0" noom="0" npm="0" rcr="0.15" vars="1" varsi="1" varsnp="1" wmc="0" wmci="0" wmcnp="0">
      <file name="/vagrant/library/App/Webservice/Types/Request/QuoteRequest.php"/>
    </class>
    <class name="App_Webservice_Types_Request_RandomQuoteRequest" ca="0" cbo="0" ce="0" cis="0" cloc="0" cr="0.15" csz="0" dit="0" eloc="0" impl="0" lloc="0" loc="3" ncloc="3" noam="0" nocc="0" nom="0" noom="0" npm="0" rcr="0.15" vars="0" varsi="0" varsnp="0" wmc="0" wmci="0" wmcnp="0">
      <file name="/vagrant/library/App/Webservice/Types/Request/RandomQuoteRequest.php"/>
    </class>
    <class name="App_Webservice_Types_Response_QuoteResponse" ca="1" cbo="1" ce="1" cis="1" cloc="3" cr="0.15" csz="1" dit="0" eloc="0" impl="0" lloc="0" loc="7" ncloc="4" noam="0" nocc="0" nom="0" noom="0" npm="0" rcr="0.15" vars="1" varsi="1" varsnp="1" wmc="0" wmci="0" wmcnp="0">
      <file name="/vagrant/library/App/Webservice/Types/Response/QuoteResponse.php"/>
    </class>
    <class name="App_Webservice_Types_Response_RandomQuoteResponse" ca="1" cbo="1" ce="1" cis="1" cloc="3" cr="0.15" csz="1" dit="0" eloc="0" impl="0" lloc="0" loc="7" ncloc="4" noam="0" nocc="0" nom="0" noom="0" npm="0" rcr="0.15" vars="1" varsi="1" varsnp="1" wmc="0" wmci="0" wmcnp="0">
      <file name="/vagrant/library/App/Webservice/Types/Response/RandomQuoteResponse.php"/>
    </class>
  </package>
  <package name="App\Entity" cr="0.15" noc="1" nof="0" noi="0" nom="6" rcr="0.15">
    <class name="Quote" ca="1" cbo="0" ce="0" cis="6" cloc="6" cr="0.15" csz="9" dit="0" eloc="20" impl="0" lloc="8" loc="44" ncloc="38" noam="0" nocc="0" nom="6" noom="0" npm="6" rcr="0.15" vars="3" varsi="3" varsnp="0" wmc="6" wmci="6" wmcnp="6">
      <file name="/vagrant/library/App/Entity/Quote.php"/>
      <method name="getId" ccn="1" ccn2="1" cloc="0" eloc="3" lloc="1" loc="4" ncloc="4" npath="1"/>
      <method name="getWording" ccn="1" ccn2="1" cloc="0" eloc="3" lloc="1" loc="4" ncloc="4" npath="1"/>
      <method name="setWording" ccn="1" ccn2="1" cloc="0" eloc="4" lloc="2" loc="5" ncloc="5" npath="1"/>
      <method name="getAuthor" ccn="1" ccn2="1" cloc="0" eloc="3" lloc="1" loc="4" ncloc="4" npath="1"/>
      <method name="setAuthor" ccn="1" ccn2="1" cloc="0" eloc="4" lloc="2" loc="5" ncloc="5" npath="1"/>
      <method name="__toString" ccn="1" ccn2="1" cloc="0" eloc="3" lloc="1" loc="4" ncloc="4" npath="1"/>
    </class>
  </package>
  <package name="App\Form" cr="0.15" noc="1" nof="0" noi="0" nom="2" rcr="0.2775">
    <class name="AddQuote" ca="1" cbo="5" ce="5" cis="2" cloc="0" cr="0.15" csz="2" dit="2" eloc="25" impl="0" lloc="15" loc="36" ncloc="36" noam="2" nocc="0" nom="2" noom="0" npm="2" rcr="0.2775" vars="0" varsi="0" varsnp="0" wmc="3" wmci="3" wmcnp="3">
      <file name="/vagrant/library/App/Form/AddQuote.php"/>
      <method name="init" ccn="1" ccn2="1" cloc="0" eloc="18" lloc="11" loc="24" ncloc="24" npath="1"/>
      <method name="isValid" ccn="2" ccn2="2" cloc="0" eloc="7" lloc="4" loc="8" ncloc="8" npath="2"/>
    </class>
  </package>
  <package name="App\Repository" cr="0.15" noc="1" nof="0" noi="0" nom="1" rcr="0.2775">
    <class name="Quote" ca="0" cbo="0" ce="0" cis="1" cloc="0" cr="0.15" csz="1" dit="2" eloc="4" impl="0" lloc="2" loc="8" ncloc="8" noam="1" nocc="0" nom="1" noom="0" npm="1" rcr="0.2775" vars="0" varsi="0" varsnp="0" wmc="1" wmci="1" wmcnp="1">
      <file name="/vagrant/library/App/Repository/Quote.php"/>
      <method name="findThemAll" ccn="1" ccn2="1" cloc="0" eloc="4" lloc="2" loc="5" ncloc="5" npath="1"/>
    </class>
  </package>
  <package name="App\Service" cr="0.15" noc="2" nof="0" noi="0" nom="3" rcr="0.15">
    <class name="RandomQuote" ca="1" cbo="0" ce="0" cis="2" cloc="0" cr="0.15" csz="4" dit="0" eloc="7" impl="0" lloc="3" loc="43" ncloc="43" noam="0" nocc="0" nom="2" noom="0" npm="2" rcr="0.15" vars="2" varsi="2" varsnp="0" wmc="2" wmci="2" wmcnp="2">
      <file name="/vagrant/library/App/Service/RandomQuote.php"/>
      <method name="__construct" ccn="1" ccn2="1" cloc="0" eloc="3" lloc="1" loc="4" ncloc="4" npath="1"/>
      <method name="getQuote" ccn="1" ccn2="1" cloc="0" eloc="4" lloc="2" loc="5" ncloc="5" npath="1"/>
    </class>
    <class name="Randomizer" ca="0" cbo="0" ce="0" cis="1" cloc="0" cr="0.15" csz="1" dit="0" eloc="3" impl="0" lloc="1" loc="7" ncloc="7" noam="0" nocc="0" nom="1" noom="0" npm="1" rcr="0.15" vars="0" varsi="0" varsnp="0" wmc="1" wmci="1" wmcnp="1">
      <file name="/vagrant/library/App/Service/Randomizer.php"/>
      <method name="getNumber" ccn="1" ccn2="1" cloc="0" eloc="3" lloc="1" loc="4" ncloc="4" npath="1"/>
    </class>
  </package>
  <package name="App\Webservice" cr="0.15" noc="1" nof="0" noi="0" nom="2" rcr="0.15">
    <class name="Calls" ca="0" cbo="6" ce="6" cis="2" cloc="10" cr="0.15" csz="2" dit="0" eloc="24" impl="0" lloc="15" loc="41" ncloc="31" noam="0" nocc="0" nom="2" noom="0" npm="2" rcr="0.15" vars="0" varsi="0" varsnp="0" wmc="3" wmci="3" wmcnp="3">
      <file name="/vagrant/library/App/Webservice/Calls.php"/>
      <method name="randomQuote" ccn="1" ccn2="1" cloc="0" eloc="9" lloc="7" loc="10" ncloc="10" npath="1"/>
      <method name="quote" ccn="2" ccn2="2" cloc="0" eloc="15" lloc="8" loc="17" ncloc="17" npath="2"/>
    </class>
  </package>
</metrics>


text:
<?php

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'development'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path(),
)));

include "Zend/Loader/Autoloader.php";
$l = Zend_Loader_Autoloader::getInstance();
$l->registerNamespace('Bisna_');
// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);

$application->bootstrap();


text:
<phpunit bootstrap="./bootstrap.php">
  <testsuites>
    <testsuite name="App">
      <directory>./library</directory>
      <directory>./application</directory>
    </testsuite>
  </testsuites>
  <filter>
    <whitelist>
        <directory suffix=".php">./library/App</directory>
    </whitelist>
  </filter>
  <logging>
    <log type="coverage-html" target="./reports/coverage" charset="UTF-8"
         yui="true" highlight="false"
         lowUpperBound="35" highLowerBound="70"/>
    <log type="testdox-text" target="./reports/testdox/testdox.txt"/>
  </logging>
</phpunit>


text:
<?php
class CachingTest extends phpRack_Test
{
    public function testPhpExtensionsExist()
    {
        $this->assert->php->extensions
            ->isLoaded('memcache');
    }
}


text:
<?php
class ElasticSearchTest extends phpRack_Test
{
    public function testPhpExtensionsExist()
    {
        $this->assert->php->extensions
            ->isLoaded('curl');
    }
}


text:
<?php
class BaseTest extends phpRack_Test
{
    public function testPhpVersionIsCorrect()
    {
        $this->assert->php->version
            ->atLeast('5.3');
    }

    public function testPhpExtensionsExist()
    {
        $this->assert->php->extensions
            ->isLoaded('simplexml')
            ->isLoaded('ctype')
            ->isLoaded('iconv')
            ->isLoaded('Reflection')
            ->isLoaded('session')
            ->isLoaded('soap')
            ->isLoaded('dom');
    }
}


text:
<?php
class SoftwareMiningTest extends phpRack_Test
{
    public function testToolsExist()
    {
        $this->assert->php->pear
            ->package('phpmd/PHP_PMD')
            ->package('pdepend/PHP_Depend')
            ->package('PHP_CodeSniffer-1.3.0')
            ->package('phpunit/phploc')
            ->package('phpunit/phpcpd')
            ->package('docblox/DocBlox')
            ->package('doc.php.net/phd');
    }
}


text:
<?php

class DatabaseTest extends phpRack_Test
{
    public function testConnectionIsAlive()
    {
        $config = Zend_Registry::get('config');

        $host = $config['resources']['doctrine']['dbal']['connections']['default']['parameters']['host'];
        $port = $config['resources']['doctrine']['dbal']['connections']['default']['parameters']['port'];
        $username = $config['resources']['doctrine']['dbal']['connections']['default']['parameters']['user'];
        $password = $config['resources']['doctrine']['dbal']['connections']['default']['parameters']['password'];
        $dbname = $config['resources']['doctrine']['dbal']['connections']['default']['parameters']['dbname'];

        $this->assert->db->mysql
            ->connect($host, $port, $username, $password)
            ->dbExists($dbname);
    }

    public function testPhpExtensionsExist()
    {
        $this->assert->php->extensions
            ->isLoaded('pdo');
    }
}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Michael
 * Date: 18.09.11
 * Time: 03:29
 * To change this template use File | Settings | File Templates.
 */

namespace App\Webservice;

require_once 'PHPUnit/Framework/TestCase.php';

class CallsTest extends \PHPUnit_Framework_TestCase {

    public function testRandomQuote()
    {
        $calls = new Calls();
        $request = new \App_Webservice_Types_Request_RandomQuoteRequest();
        $response = $calls->randomQuote($request);
        $this->assertType('App_Webservice_Types_Response_RandomQuoteResponse', $response);
        $this->assertType('string', $response->quote->wording);
        $this->assertType('string', $response->quote->author);
    }

    public function testQuote()
    {
        $calls = new Calls();
        $request = new \App_Webservice_Types_Request_QuoteRequest();
        $request->id = 1;
        $response = $calls->quote($request);
        $this->assertType('App_Webservice_Types_Response_QuoteResponse', $response);
        $this->assertType('string', $response->quote->wording);
        $this->assertType('string', $response->quote->author);
    }

}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Michael
 * Date: 14.03.11
 * Time: 13:57
 * To change this template use File | Settings | File Templates.
 */
namespace App\Service;

class RandomQuoteTest extends \PHPUnit_Framework_TestCase {

    public function testGetQuote()
    {
        $stub = $this->getMock('App\Service\Randomizer');
        $stub->expects($this->any())
             ->method('getNumber')
             ->will($this->returnValue('0'));

        $service = new RandomQuote($stub);
        $quote = $service->getQuote();
        $this->assertRegExp('/There are only two ways to live your life./', $quote[0]);
    }

}


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Michael
 * Date: 14.03.11
 * Time: 13:57
 * To change this template use File | Settings | File Templates.
 */
namespace App\Service;

class RandomizerTest extends \PHPUnit_Framework_TestCase {

    public function testGetNumber()
    {
        $service = new Randomizer();

        for($i = 0; $i <= 100; $i++)
        {
            $number = $service->getNumber(1,10);
            $this->assertRegExp('/[1-10]?/', (string) $number);
        }

    }

}


text:
<?php

require_once 'PHPUnit/Framework/TestCase.php';

class IndexControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
{

    public function setUp()
    {
        /* Setup Routine */
    }

    public function tearDown()
    {
        /* Tear Down Routine */
    }

    public function testRoutes()
    {
        $uri = "/";
        $request = $this->getFrontController()->getRouter()->route($this->getRequest()->setRequestUri($uri));
        $this->assertAction('index');
        $this->assertController('index');
        $this->assertModule('site');

        $this->resetRequest();

        $uri = "/homepage";
        $request = $this->getFrontController()->getRouter()->route($this->getRequest()->setRequestUri($uri));
        $this->assertAction('index');
        $this->assertController('index');
        $this->assertModule('site');

    }

}


text:
= DESCRIPTION:

Library provides a method to generate secure passwords for use in recipes.

= REQUIREMENTS:

OpenSSL Ruby bindings must be installed, which are a requirement for Chef anyway.

= USAGE:

Most often this will be used to generate a secure password for an attribute.

    include Opscode::OpenSSL::Password

    set_unless[:my_password] = secure_password

= LICENSE and AUTHOR:

Author:: Joshua Timberman (<joshua@opscode.com>)

Copyright:: 2009, Opscode, Inc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


text:
maintainer       "Opscode, Inc."
maintainer_email "cookbooks@opscode.com"
license          "Apache 2.0"
description      "Installs/Configures openssl"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc'))
version          "0.1"

recipe "openssl", "Empty, this cookbook provides a library, see README"


text:
#
# Cookbook Name:: openssl
# Library:: secure_password
# Author:: Joshua Timberman <joshua@opscode.com>
#
# Copyright 2009, Opscode, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

require 'openssl'

module Opscode
  module OpenSSL
    module Password
      def secure_password
        pw = String.new

        while pw.length < 20
          pw << ::OpenSSL::Random.random_bytes(1).gsub(/\W/, '')
        end

        pw
      end
    end
  end
end


text:
#
# Cookbook Name:: openssl
# Recipe:: default
#
# Copyright 2009, Opscode, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


text:
require_recipe "php"
require_recipe "php::module_mysql"
require_recipe "php::module_apc"
require_recipe "php::module_memcache"
require_recipe "php::module_curl"

package "php-pear" do
  action :install
end

php_pear_channel "pear.phpunit.de" do
  action :discover
end

php_pear_channel "components.ez.no" do
  action :discover
end

php_pear_channel "pear.symfony-project.com" do
  action :discover
end

php_pear_channel "pear.phpmd.org" do
  action :discover
end

php_pear_channel "pear.pdepend.org" do
  action :discover
end

php_pear_channel "pear.docblox-project.org" do
  action :discover
end

php_pear_channel "pear.michelf.com" do
  action :discover
end

# using apt
package "phpunit" do
  action :install
end

# XSL needed by DocBlox
package "php5-xsl" do
  action :install
end

# Graphviz needed by DocBlox
package "graphviz" do
  action :install
end

# Sqlite needed by PHD (Docbook)
package "php5-sqlite" do
  action :install
end

# Using PEAR installer

execute "PEAR: upgrade all packages" do
  command "pear upgrade-all"
end

execute "PEAR: install phpmd/PHP_PMD" do
  command "pear install -f phpmd/PHP_PMD"
end

execute "PEAR: install pdepend/PHP_Depend" do
  command "pear install -f pdepend/PHP_Depend"
end

execute "PEAR: install PHP_CodeSniffer-1.3.0" do
  command "pear install -f PHP_CodeSniffer-1.3.0"
end

execute "PEAR: install phploc-1.5.0" do
  command "pear install -f phpunit/phploc"
end

execute "PECL: install xdebug" do
  command "pecl install xdebug"
end

execute "PEAR: install phpcpd" do
  command "pear install -f phpunit/phpcpd"
end

execute "PEAR: install docblox" do
  command "pear install -f docblox/DocBlox"
end

execute "PEAR: install phd" do
  command "pear install -f --alldeps doc.php.net/phd"
end

# Install xDebug
php_pear "xdebug" do
  # Specify that xdebug.so must be loaded as a zend extension
  zend_extensions ['xdebug.so']
  action :install
end

# Install the php packages we need
## Upgrade existing packages
execute "PEAR: upgrade all packages" do
  command "pear upgrade-all"
end


text:
require_recipe "apt"
require_recipe "build-essential"
require_recipe "networking_basic"
require_recipe "apache2"
include_recipe "apache2::mod_php5"
include_recipe "apache2::mod_rewrite"
include_recipe "apache2::mod_deflate"
include_recipe "apache2::mod_headers"
require_recipe "mysql::server"
require_recipe "vagrant_main::custom_php"
require_recipe "elasticsearch"
require_recipe "ant"
require_recipe "memcached"

# Install mysql gem
gem_package "mysql" do
  action :install
end

ruby_block "Create database + execute grants" do
  block do
    require 'rubygems'
    Gem.clear_paths
    require 'mysql'
    m = Mysql.new("localhost", "root", "")
    m.query("CREATE DATABASE IF NOT EXISTS app CHARACTER SET utf8")
    m.reload
  end
end

# Initialize web app
web_app "default" do
    template "default.conf.erb"
    server_name "localhost"
    server_aliases [node['fqdn'], "localhost"]
    docroot "#{node[:vagrant][:directory]}/public"
end


text:
<VirtualHost *:80>
  ServerName <%= @params[:server_name] %>
  ServerAlias <% @params[:server_aliases].each do |a| %><%= "#{a}" %> <% end %>
  DocumentRoot <%= @params[:docroot] %>

  <Directory <%= @params[:docroot] %>>
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
  </Directory>

  LogLevel info
  ErrorLog <%= node['apache']['log_dir'] %>/<%= @params[:name] %>-error.log
  CustomLog <%= node['apache']['log_dir'] %>/<%= @params[:name] %>-access.log combined

  RewriteEngine On
  RewriteLog <%= node['apache']['log_dir'] %>/<%= @application_name %>-rewrite.log
  RewriteLogLevel 0

</VirtualHost>


text:
= DESCRIPTION:

Installs and configures ElasticSearch.

= REQUIREMENTS:

== Platform:

Tested on Ubuntu 9.10 on EC2 only. YMMV on other platforms.

==Cookbooks:

Requires Opscode's runit and java cookbooks.

= ATTRIBUTES:

It's a good idea to change the cluster_name attribute to something
meaningful, like "production".

Production deployments should also increase the heap_size and fd_ulimit
attributes.

To use the s3 gateway, set the s3_gateway_bucket attribute to the name of an
existing bucket. You'll also need to add aws credentials to the aws databag
(see below)

= USAGE:

This cookbook makes a few assumptions about where files live:

/etc/elasticsearch: configuration files
/var/lib/elasticsearch: elasticsearch runtime files
/var/log/elasticsearch: elasticsearch log directory

Use elasticsearch::autoconf to automatically discover nodes in the cluster. Use
elasticsearch::default for a more static deployment.

Both options will configure ElasticSearch and start the ElasticSearch runit
service.

To use the s3 gateway, add your s3 credentials to a databag item with id "main"
in the "aws" databag. The schema of this item is:
{
  "aws_access_key_id":
  "aws_secret_access_key":
  "aws_account_id":
  "ec2_cert":
  "ec2_private_key":
}

= LICENSE and AUTHOR:

Author:: Grant Rodgers (<grant@gotime.com>)

Copyright:: 2010, GoTime Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


elasticsearch

description: Installs/Configures elasticsearch

long_description:
= DESCRIPTION:

= REQUIREMENTS:

= ATTRIBUTES:

= USAGE:

maintainer: GoTime

license: Apache 2.0


text:
maintainer       "GoTime"
maintainer_email "ops@gotime.com"
license          "Apache 2.0"
description      "Installs/Configures elasticsearch"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc'))
version          "0.1"

depends "java"
depends "runit"


text:
#
# Cookbook Name:: elasticsearch
# Recipe:: autoconf
#
# Copyright 2010, GoTime
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

##TODO use a databag for configuration per cluster, similar to cassandra cookbook
#cluster = data_bag_item('elasticsearch', node[:elasticsearch][:cluster_name])
#cluster.each_pair do |k, v|
#  node[:elasticsearch][k] = v #TODO should do a deep merge here
#end
#node.save

seeds = search(:node, "elasticsearch_cluster_name:#{node[:elasticsearch][:cluster_name]} AND elasticsearch_seed:true").sort_by { |n| n.name }.collect {|n| n["ipaddress"]}
node[:elasticsearch][:seeds] = seeds

include_recipe "elasticsearch::default"


text:
#
# Cookbook Name:: elasticsearch
# Recipe:: default
#
# Copyright 2010, GoTime
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

include_recipe "java"

package "unzip" do
  action :install
end

remote_file "/tmp/elasticsearch-#{node[:elasticsearch][:version]}.zip" do
  source "http://github.com/downloads/elasticsearch/elasticsearch/elasticsearch-#{node[:elasticsearch][:version]}.zip"
  mode "0644"
  checksum node[:elasticsearch][:checksum]
end

user "elasticsearch" do
  uid 61021
  gid "nogroup"
end

["/usr/lib/elasticsearch-#{node[:elasticsearch][:version]}", "/etc/elasticsearch"].each do |dir|
  directory dir do
    owner "root"
    group "root"
    mode 0755
  end
end

["/var/log/elasticsearch", "/var/lib/elasticsearch", "/var/run/elasticsearch"].each do |dir|
  directory dir do
    owner "elasticsearch"
    group "nogroup"
    mode 0755
  end
end

bash "unzip elasticsearch" do
  user "root"
  cwd "/tmp"
  code %(unzip /tmp/elasticsearch-#{node[:elasticsearch][:version]}.zip)
  not_if { File.exists? "/tmp/elasticsearch-#{node[:elasticsearch][:version]}" }
end

bash "copy elasticsearch root" do
  user "root"
  cwd "/tmp"
  code %(cp -r /tmp/elasticsearch-#{node[:elasticsearch][:version]}/* /usr/lib/elasticsearch-#{node[:elasticsearch][:version]})
  not_if { File.exists? "/usr/lib/elasticsearch-#{node[:elasticsearch][:version]}/lib" }
end

directory "/usr/lib/elasticsearch-#{node[:elasticsearch][:version]}/plugins" do
  owner "root"
  group "root"
  mode 0755
end

link "/usr/lib/elasticsearch" do
  to "/usr/lib/elasticsearch-#{node[:elasticsearch][:version]}"
end

aws = nil
if node[:ec2]
  aws = data_bag_item('aws', 'main')

  directory "/mnt/elasticsearch" do
    owner "elasticsearch"
    group "nogroup"
    mode 0755
  end

  # put lib dir on /mnt
  mount "/var/lib/elasticsearch" do
    device "/mnt/elasticsearch"
    fstype "none"
    options "bind,rw"
    action :mount
  end
end

bash "copy elasticsearch conf" do
  user "root"
  cwd "/usr/lib/elasticsearch"
  code %(cp -R ./config/* /etc/elasticsearch)
  not_if { File.exists? "/etc/elasticsearch/logging.yml" }
end

template "/etc/elasticsearch/logging.yml" do
  source "logging.yml.erb"
  mode 0644
end

template "/etc/elasticsearch/elasticsearch.in.sh" do
  source "elasticsearch.in.sh.erb"
  mode 0644
end

template "/etc/elasticsearch/elasticsearch.yml" do
  source "elasticsearch.yml.erb"
  mode 0644
end

runit_service "elasticsearch" do
  action [ :enable, :start ]
end


text:
set_unless[:elasticsearch][:version] = "0.17.6"
set_unless[:elasticsearch][:checksum] = '67a5b6240c27db666b5d2b48cdc26b91d64e8f2e950c6383273e47a6f4020da4'

set_unless[:elasticsearch][:cluster_name] = "default"

set_unless[:elasticsearch][:home] = "/usr/lib/elasticsearch"

set_unless[:elasticsearch][:s3_gateway_bucket] = nil # s3 bucket to store gateway snapshots in

set_unless[:elasticsearch][:heap_size] = 1000
set_unless[:elasticsearch][:fd_ulimit] = nil # nofiles limit (make this something like 32768, see /etc/security/limits.conf)

set_unless[:elasticsearch][:default_replicas] = 1 # replicas are in addition to the original, so 1 replica means 2 copies of each shard
set_unless[:elasticsearch][:default_shards] = 6 # 6*2 shards per index distributes evenly across 3, 4, or 6 nodes


text:
path:
  data: /var/lib/elasticsearch/work
  logs: /var/log/elasticsearch

cluster:
  name: vm


text:
CLASSPATH=$CLASSPATH:$ES_HOME/lib/*

# Arguments to pass to the JVM
# java.net.preferIPv4Stack=true: Better OOTB experience, especially with jgroups
JAVA_OPTS=" \
        -Xms128M \
        -Xmx<%= @node[:elasticsearch][:heap_size] %>m \
        -Djline.enabled=true \
        -Djava.net.preferIPv4Stack=true \
        -XX:+AggressiveOpts \
        -XX:+UseParNewGC \
        -XX:+UseConcMarkSweepGC \
        -XX:+CMSParallelRemarkEnabled \
        -XX:+HeapDumpOnOutOfMemoryError \
        -XX:CMSInitiatingOccupancyFraction=88 \
        -Des.path.conf=/etc/elasticsearch"

<% if @node[:kernel][:machine] == 'x86_64' -%>
# run compressed pointers to save on heap
JAVA_OPTS="$JAVA_OPTS -XX:+UseCompressedOops"
<% end -%>


text:
#!/bin/bash

exec 2>&1

<%= "ulimit -n #{@node[:elasticsearch][:fd_ulimit]}" if @node[:elasticsearch][:fd_ulimit] %>

ES_HOME=<%= @node[:elasticsearch][:home] %>

. /etc/elasticsearch/elasticsearch.in.sh

exec chpst -u elasticsearch java $JAVA_OPTS $ES_JAVA_OPTS -Djava.net.preferIPv4Stack=true -Delasticsearch -Des.path.home=$ES_HOME -Des-foreground=yes -cp $CLASSPATH org.elasticsearch.bootstrap.Bootstrap


text:
rootLogger: INFO, console, file
logger:
  jgroups: WARN
  # log action execution errors for easier debugging
  action : INFO

appender:
  console:
    type: console
    layout:
      type: consolePattern
      conversionPattern: "[%d{ABSOLUTE}][%-5p][%-25c] %m%n"

  file:
    type: dailyRollingFile
    file: ${path.logs}/${cluster.name}.log
    datePattern: "'.'yyyy-MM-dd"
    layout:
      type: pattern
      conversionPattern: "[%d{ABSOLUTE}][%-5p][%-25c] %m%n"


text:
#!/bin/sh
umask 0027
exec svlogd -tt ./main


text:
## v1.0.2:

* [COOK-1098] - Add Amazon Linux platform support
* [COOK-1149] - Add OS X platform support


text:
If you would like to contribute, please open a ticket in JIRA:

* http://tickets.opscode.com

Create the ticket in the COOK project and use the cookbook name as the
component.

For all code contributions, we ask that contributors sign a
contributor license agreement (CLA). Instructions may be found here:

* http://wiki.opscode.com/display/chef/How+to+Contribute

When contributing changes to individual cookbooks, please do not
modify the version number in the metadata.rb. Also please do not
update the CHANGELOG.md for a new version. Not all changes to a
cookbook may be merged and released in the same versions. Opscode will
handle the version updates during the release process. You are welcome
to correct typos or otherwise make updates to documentation in the
README.

If a contribution adds new platforms or platform versions, indicate
such in the body of the commit message(s), and update the relevant
COOK ticket. When writing commit messages, it is helpful for others if
you indicate the COOK ticket. For example:

    git commit -m '[COOK-1041] Updated pool resource to correctly delete.'

In the ticket itself, it is also helpful if you include log output of
a successful Chef run, but this is not absolutely required.


text:
maintainer        "Opscode, Inc."
maintainer_email  "cookbooks@opscode.com"
license           "Apache 2.0"
description       "Installs C compiler / build tools"
version           "1.0.2"
recipe            "build-essential", "Installs packages required for compiling C software from source."

%w{ fedora redhat centos ubuntu debian amazon }.each do |os|
  supports os
end

supports "mac_os_x", ">= 10.6.0"


text:
DESCRIPTION
===========

Installs packages required for compiling C software from source.

LICENSE AND AUTHOR
==================

Author:: Joshua Timberman (<joshua@opscode.com>)
Author:: Seth Chisamore (<schisamo@opscode.com>)

Copyright 2009-2011, Opscode, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


text:
#
# Cookbook Name:: build-essential
# Recipe:: default
#
# Copyright 2008-2009, Opscode, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

require 'chef/shell_out'

case node['os']
when "linux"
  packages = value_for_platform(
    ["ubuntu", "debian"] => {
      "default" => ["build-essential", "binutils-doc"]
    },
    ["centos", "redhat", "fedora", "amazon"] => {
      "default" => ["gcc", "gcc-c++", "kernel-devel", "make"]
    }
  )

  packages.each do |pkg|
    package pkg do
      action :install
    end
  end

  %w{autoconf flex bison}.each do |pkg|
    package pkg do
      action :install
    end
  end
when "darwin"
  result = Chef::ShellOut.new("pkgutil --pkgs").run_command
  installed = result.stdout.split("\n").include?("com.apple.pkg.gcc4.2Leo")
  pkg_filename = File.basename(node['build_essential']['osx']['gcc_installer_url'])
  pkg_path = "#{Chef::Config[:file_cache_path]}/#{pkg_filename}"

  remote_file pkg_path do
    source node['build_essential']['osx']['gcc_installer_url']
    checksum node['build_essential']['osx']['gcc_installer_checksum']
    not_if { installed }
  end

  execute "sudo installer -pkg \"#{pkg_path}\" -target /" do
    not_if { installed }
  end
end