<?php
namespace Phalcon\Build;

class Util
{
    /**
     * Normalize file path, convert all slashes to Linux-style and get rid of '..', '.'.
     *
     * @param $filePath
     * @return string
     */
    public static function normalize($filePath)
    {
        $filePath = realpath($filePath);
        $filePath = str_replace('\\', '/', $filePath);
        return $filePath;
    }

    /**
     * Recursively deletes everything in the directory
     *
     * @param string $dir
     */
    public static function cleanDirectory($dir)
    {
        $iterator = new \DirectoryIterator($dir);
        foreach ($iterator as $entry) {
            /** @var $entry \DirectoryIterator */
            if ($entry->isDot()) {
                continue;
            }
            if ($entry->isDir()) {
                self::cleanDirectory($entry->getPathname());
                rmdir($entry->getPathname());
            } else {
                unlink($entry->getPathname());
            }
        }
    }
}

<?php
namespace Phalcon\Build;

class Util
{
    /**
     * Normalize file path, convert all slashes to Linux-style and get rid of '..', '.'.
     *
     * @param $filePath
     * @return string
     */
    public static function normalize($filePath)
    {
        $filePath = realpath($filePath);
        $filePath = str_replace('\\', '/', $filePath);
        return $filePath;
    }

    /**
     * Recursively deletes everything in the directory
     *
     * @param string $dir
     */
    public static function cleanDirectory($dir)
    {
        $iterator = new \DirectoryIterator($dir);
        foreach ($iterator as $entry) {
            /** @var $entry \DirectoryIterator */
            if ($entry->isDot()) {
                continue;
            }
            if ($entry->isDir() && !$entry->isLink()) {
                self::cleanDirectory($entry->getPathname());
                rmdir($entry->getPathname());
            } else {
                unlink($entry->getPathname());
            }
        }
    }
}

Determine if current DirectoryIterator item is a symbolic link


<?php

namespace RenatoMarinho\LaravelPageSpeed\Middleware;

class RemoveQuotes extends PageSpeed
{
    public function apply($buffer)
    {
        $replace = [
            '/ src="(.*?)"/' => ' src=$1',
            '/ width="(.*?)"/' => ' width=$1',
            '/ height="(.*?)"/' => ' height=$1',
            '/ name="(.*?)"/' => ' name=$1',
            '/ charset="(.*?)"/' => ' charset=$1',
            '/ align="(.*?)"/' => ' align=$1',
            '/ border="(.*?)"/' => ' border=$1',
            '/ crossorigin="(.*?)"/' => ' crossorigin=$1',
            '/ type="(.*?)"/' => ' type=$1',
            '/\/>/' => '>',
        ];

        return $this->replace($replace, $buffer);
    }
}

<?php

namespace RenatoMarinho\LaravelPageSpeed\Middleware;

class RemoveQuotes extends PageSpeed
{
    public function apply($buffer)
    {
        $replace = [
            '/ src="(.\S*?)"/' => ' src=$1',
            '/ width="(.\S*?)"/' => ' width=$1',
            '/ height="(.\S*?)"/' => ' height=$1',
            '/ name="(.\S*?)"/' => ' name=$1',
            '/ charset="(.\S*?)"/' => ' charset=$1',
            '/ align="(.\S*?)"/' => ' align=$1',
            '/ border="(.\S*?)"/' => ' border=$1',
            '/ crossorigin="(.\S*?)"/' => ' crossorigin=$1',
            '/ type="(.\S*?)"/' => ' type=$1',
            '/\/>/' => '>',
        ];

        return $this->replace($replace, $buffer);
    }
}

Remove quotes only when attributes do not contains whitespaces


<?php

/**
 * This is project's console commands configuration for Robo task runner.
 *
 * @see http://robo.li/
 */

use Robo\Tasks;

class RoboFile extends Tasks
{
    const DOCUMENTATION_BIN = 'bin/phpdoc.phar';

    const DOCUMENTATION_ROOT = 'docs';

    /**
     * Generate a new copy of the changelog.
     *
     * @link https://github.com/skywinder/github-changelog-generator
     *
     * @return void
     */
    public function generateChangelog ()
    {
        $this->_exec('github_changelog_generator');
    }
    /**
     * Returns the root path for the documentation to be generated in.
     *
     * @param null|string (optional) A custom path to generate the docs to.
     * @return string
     */
    private function documentationRoot (string $destination = null): string
    {
        $root = self::DOCUMENTATION_ROOT;

        return ($destination)
            ? rtrim($destination, '/').'/'.$root
            : "{$this->rootPath()}/{$root}";
    }

    /**
     * Returns the current root path of the repository.
     *
     * @return string
     */
    private function rootPath (): string
{
        return rtrim(realpath(__DIR__), '/');
    }
}

<?php

/**
 * This is project's console commands configuration for Robo task runner.
 *
 * @see http://robo.li/
 */

use Robo\Tasks;

class RoboFile extends Tasks
{
{
    // define public methods as commands
}

Revert "Add changelog generator method & documentation helper methods"

This reverts commit 94c037ad6c2a8a39a1b02f12cde564b17b9e7067.


<?php
/**
 * Abstract class to define form element filters
 * @author Jon Johnson <jon.johnson@ucsf.edu>
 * @license http://jazzee.org/license.txt
 * @package foundation
 * @subpackage forms
 */
abstract class Form_Filter{
  /**
   * Holds the element we are filtering
   * @var Form_Element
   */
  protected $e;

  /**
   * Holds the rule set for processing
   * @var mixed
   */
  protected $rulesSet;

  /**
   * Constructor
   * @param Form_Element $e the element we are validating
   */
  public function  __construct(Form_Element $e, $ruleSet = null){
    $this->e = $e;
    $this->ruleSet = $ruleSet;
  }

  /**
   * Filter the input
   * @param mixed $value
   * @return mixed @value
   */
  abstract public function filter($value);
}
?>

<?php
/**
 * Abstract class to define form element filters
 * @author Jon Johnson <jon.johnson@ucsf.edu>
 * @license http://jazzee.org/license.txt
 * @package foundation
 * @subpackage forms
 */
abstract class Form_Filter{
  /**
   * Holds the element we are filtering
   * @var Form_Element
   */
  protected $e;

  /**
   * Holds the rule set for processing
   * @var mixed
   */
  protected $ruleSet;

  /**
   * Constructor
   * @param Form_Element $e the element we are validating
   */
  public function  __construct(Form_Element $e, $ruleSet = null){
    $this->e = $e;
    $this->ruleSet = $ruleSet;
  }

  /**
   * Filter the input
   * @param mixed $value
   * @return mixed @value
   */
  abstract public function filter($value);
}
?>

Fix bad property name in Form_Filter.

Fix bad property name in Form_Filter.


<?php
/**
 * This file is part of the bee4/events package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Bee4 2014
 * @author Stephane HULARD <s.hulard@chstudio.fr>
 * @package Bee4\Events
 */

namespace Bee4\Events;

/**
 * Event dispatcher interface, define how to dispatch an event
 * @package Bee4\Events
 */
interface DispatcherInterface
{
    /**
     * @param string $name
     * @param EventInterface $event
     * @return EventInterface
     */
    public function dispatch($name, EventInterface $event);

    /**
     * Add a listener for the given event
     * @param string $name
     * @param Callable $listener
     * @param int $priority
     * @return DispatcherInterface
     */
    public function add($name, callable $listener, $priority = 0);

    /**
     * Remove a listener for the given event name
     * @param string $name
     * @param Callable $listener
     * @return DispatcherInterface
     */
    public function remove($name, callable $listener);

    /**
     * Retrieve the listeners for a given event name
     * @param string $name
     * @return array
     */
    public function get($name);
}

<?php
/**
 * This file is part of the bee4/events package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Bee4 2014
 * @author Stephane HULARD <s.hulard@chstudio.fr>
 * @package Bee4\Events
 */

namespace Bee4\Events;

/**
 * Event dispatcher interface, define how to dispatch an event
 * @package Bee4\Events
 */
interface DispatcherInterface
{
    /**
     * Notify all the observers from the updated state
     * @param string $name
     * @param EventInterface $event
     * @return EventInterface
     */
    public function dispatch($name, EventInterface $event);

    /**
     * Alias for the method `add`
     * @param string $name
     * @param Callable $listener
     * @param int $priority
     * @return DispatcherInterface
     * @deprecated
     */
    public function add($name, callable $listener, $priority = 0);

    /**
     * Add a listener for the given event
     * @param string $name
     * @param Callable $listener
     * @return DispatcherInterface
     */
    public function on($name, callable $listener);

    /**
     * Remove a listener for the given event name
     * @param string $name
     * @param Callable $listener
     * @return DispatcherInterface
     */
    public function remove($name, callable $listener);

    /**
     * Retrieve the listeners for a given event name
     * @param string $name
     * @return array
     */
    public function get($name);
}

Change paradigm, use `on` instead of `add`

Also deprecate the `add` which become a simple alias to the on method.


<?php

    // If the later function cannot handle autoloading, uncomment the default one as well
//    set_include_path(get_include_path().PATH_SEPARATOR.dirname(__DIR__));

//    spl_autoload_extensions('.php');
//
//    // spl_autoload needs to be passed because of PHPUnit
//    spl_autoload_register('spl_autoload');

    // This is used to handle Linux which is case sensitive
    spl_autoload_register(function ($className) {

        $className = str_replace('\\', '/', $className);

        $file = dirname(__DIR__) . DIRECTORY_SEPARATOR . $className . '.php';

        if (file_exists($file)) {
            require_once $file;
        } else {
            (new \CodeJetter\core\ErrorHandler())->logError("Class file '{$file}' does not exist");
        }
    });

<?php

    // If the later function cannot handle autoloading, uncomment the default one as well
//    set_include_path(get_include_path().PATH_SEPARATOR.dirname(__DIR__));

//    spl_autoload_extensions('.php');
//
//    // spl_autoload needs to be passed because of PHPUnit
//    spl_autoload_register('spl_autoload');

    // This is used to handle Linux which is case sensitive
    spl_autoload_register(function ($className) {

        $className = str_replace('\\', '/', $className);

        $file = dirname(__DIR__) . DIRECTORY_SEPARATOR . $className . '.php';

        // leave the file_exists commented in production, for debugging add the file_exists check
        //if (file_exists($file)) {
            require_once $file;
        //} else {
        //    (new \CodeJetter\core\ErrorHandler())->logError("Class file '{$file}' does not exist");
        //}
    });

Comment out the file exist check

Comment out the file exist check


<?php
namespace Neos\Flow\Tests\Functional\Reflection\Fixtures\Model;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Annotations as Flow;

/**
 * A model fixture which is used for testing the class schema building
 *
 * @Flow\Entity
 */
class SuperEntity extends AbstractSuperEntity
{
    /**
     * Just a normal string
     *
     * @var string|null
     */
    protected $someString;

    /**
     * Just an int that can be null
     *
     * @var null|int
     */
    protected $someNullableInt;
}

<?php
namespace Neos\Flow\Tests\Functional\Reflection\Fixtures\Model;

/*
 * This file is part of the Neos.Flow package.
 *
 * (c) Contributors of the Neos Project - www.neos.io
 *
 * This package is Open Source Software. For the full copyright and license
 * information, please view the LICENSE file which was distributed with this
 * source code.
 */

use Neos\Flow\Annotations as Flow;

/**
 * A model fixture which is used for testing the class schema building
 *
 * @Flow\Entity
 */
class SuperEntity extends AbstractSuperEntity
{
    /**
     * Just a normal string
     *
     * @var string
     */
    protected $someString;

    /**
     * Just a string that can be null
     *
     * @var string|null
     */
    protected $someNullableString;

    /**
     * Just an int that can be null
     *
     * @var null|int
     */
    protected $someNullableInt;

    /**
     * Just an array of strings that can be null
     *
     * @var array<string>|null
     */
    protected $someNullableArrayOfStrings;

}

TASK: Move nullable type to a separate property


<?php
namespace WiContact\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="contacts")
 */
class Contact
{

    /**
     *
     * @var int
     *      @ORM\Id
     *      @ORM\Column(type="integer")
     *      @ORM\GeneratedValue
     */
    protected $id;

    /**
     *
     * @var string @ORM\Column(type="string", nullable=true)
     */
    protected $name;

    /**
     *
     * @return the $id
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     *
     * @return the $name
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     *
     * @param int $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     *
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }
}

<?php
namespace WiContact\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

/**
 * @ORM\Entity
 * @ORM\Table(name="contacts")
 */
class Contact
{

    /**
     *
     * @var int @ORM\Id
     *      @ORM\Column(type="integer")
     *      @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     *
     * @var string @ORM\Column(type="string", nullable=true)
     */
    protected $name;

    /**
     *
     * @var ArrayCollection; @ORM\OneToMany(targetEntity="WiContact\Entity\ContactPhone", mappedBy="contact", cascade={"persist"})
     */
    protected $phones;

    /**
     * Never forget to initialize collections
     */
    public function __construct()
    {
        $this->phones = new ArrayCollection();
    }

    /**
     *
     * @return the $id
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     *
     * @return the $name
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     *
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * @param Collection $phones
     */
    public function addPhones(Collection $phones)
    {
        foreach ($phones as $phone) {
            $phone->setContact($this);
            $this->phones->add($phone);
        }
    }

    /**
     * @param Collection $phones
     */
    public function removePhones(Collection $phones)
    {
        foreach ($phones as $phone) {
            $phone->setContact($this);
            $this->phones->removeElement($phone);
        }
    }

    /**
     *
     * @return the $phones
     */
    public function getPhones()
    {
        return $this->phones;
    }
}

Create doctrine Annotations on Entity

Create doctrine Annotations on Entity


<?php

namespace Laraquick\Models\Traits;

use Illuminate\Database\Eloquent\Builder;

trait Helper
{

    /**
     * A shortcut to withoutGlobalScope()
     *
     * @param string|array $attributes
     * @return Builder
     */
    public function without($attributes)
    {
        return $this->withoutGlobalScope($attributes);
    }

    /**
     * Excludes the given values from being selected from the database
     * Thanks to Ikechi Michael (@mykeels)
     *
     * @param Builder $query
     * @param string|array $value
     * @return void
     */
    public function scopeExcept($query, $value)
    {
        $defaultColumns = ['id', 'created_at', 'updated_at'];
        if (in_array_('deleted_at', $this->dates)) {
            $defaultColumns[] = 'deleted_at';
        }
        if (is_string($value)) {
            $value = [$value];
        }
        return $query->select(array_diff(array_merge($defaultColumns, $this->fillable), (array) $value));
    }

    public function toArray()
    {
        $fillable = $this->fillable;
        array_unshift($fillable, 'id');
        $array = collect(parent::toArray())
            // Show only fillables
            ->only($fillable)
            // Hide hidden ones
            ->except($this->hidden)
            ->all();
        // merge with relations and return
        return array_merge($array, $this->relations);
    }
}

<?php

namespace Laraquick\Models\Traits;

use Illuminate\Database\Eloquent\Builder;

trait Helper
{

    /**
     * A shortcut to withoutGlobalScope()
     *
     * @param string|array $attributes
     * @return Builder
     */
    public function without($attributes)
    {
        return $this->withoutGlobalScope($attributes);
    }

    /**
     * Excludes the given values from being selected from the database
     * Thanks to Ikechi Michael (@mykeels)
     *
     * @param Builder $query
     * @param string|array $value
     * @return void
     */
    public function scopeExcept($query, $value)
    {
        $defaultColumns = ['id', 'created_at', 'updated_at'];
        if (in_array_('deleted_at', $this->dates)) {
            $defaultColumns[] = 'deleted_at';
        }
        if (is_string($value)) {
            $value = [$value];
        }
        return $query->select(array_diff(array_merge($defaultColumns, $this->fillable), (array) $value));
    }

    public function toArray()
    {
        $withArray = property_exists($this, 'withArray')
            ? $this->withArray : [];
        $fillable = array_merge($this->fillable, $withArray);

        array_unshift($fillable, 'id');
        $array = collect(parent::toArray())
            // Show only fillables
            ->only($fillable)
            // Hide hidden ones
            ->except($this->hidden)
            ->all();
        // merge with relations and return
        return array_merge($array, $this->relations);
    }
}

Send values of items in withArray with the model array


<?php
namespace EventFarm\Restforce\RestClient;

use Psr\Http\Message\StreamInterface;

class RestforceClientException extends \Exception
{
    public static function queryError(StreamInterface $responseBody)
    {
        return new self('Error communicating with Salesforce', 500);
    }
}

<?php
namespace EventFarm\Restforce\RestClient;

use Psr\Http\Message\StreamInterface;

class RestforceClientException extends \Exception
{
    public static function queryError(StreamInterface $responseBody)
    {
        return new self('Error communicating with Salesforce: ' . $responseBody->getContents(), 500);
    }
}

Add response contents to error message string.


<?php

	// AJAX call to fetch a new background image

	$config = json_decode(file_get_contents(dirname(__FILE__) . "/../../config.json"), true);

	$url             = "https://api.unsplash.com/photos/random?per_page=1&client_id=" . $config['unsplash_client_id'];
	$json            = json_decode(file_get_contents($url), true);
	$image_url       = $json['urls']['regular'];
	$image_user_name = $json['user']['name'];
	$image_user_url  = $json['user']['links']['html'];

	echo json_encode(array('success' => 1, 'url' => $image_url, 'image_user_name' => $image_user_name, 'image_user_url' => $image_user_url));

	die();

?>

<?php

	// AJAX call to fetch a new background image

  // http://stackoverflow.com/a/24707821 => use instead of file_get_contents for external URL's
  function curl_get_contents($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
  }

	$config = json_decode(file_get_contents(dirname(__FILE__) . "/../../config.json"), true);

	$url             = "https://api.unsplash.com/photos/random?per_page=1&client_id=" . $config['unsplash_client_id'];
	$json            = json_decode(curl_get_contents($url), true);
	$image_url       = $json['urls']['regular'];
	$image_user_name = $json['user']['name'];
	$image_user_url  = $json['user']['links']['html'];

	echo json_encode(array('success' => 1, 'url' => $image_url, 'image_user_name' => $image_user_name, 'image_user_url' => $image_user_url));

	die();

?>

Replace file_get_contents with a CURL command for external URL's


<?php

final class PhabricatorCalendarEventHeraldAdapter extends HeraldAdapter {

  private $object;

  public function getAdapterApplicationClass() {
    return 'PhabricatorCalendarApplication';
  }

  public function getAdapterContentDescription() {
    return pht('React to events being created or updated.');
  }

  protected function newObject() {
    return new PhabricatorCalendarEvent();
  }

  public function isTestAdapterForObject($object) {
    return ($object instanceof PhabricatorCalendarEvent);
  }

  public function getAdapterTestDescription() {
    return pht(
      'Test rules which run when an event is created or updated.');
  }

  public function setObject($object) {
    $this->object = $object;
    return $this;
  }

  public function getObject() {
    return $this->object;
  }

  public function getAdapterContentName() {
    return pht('Calendar Events');
  }

  public function supportsRuleType($rule_type) {
    switch ($rule_type) {
      case HeraldRuleTypeConfig::RULE_TYPE_GLOBAL:
      case HeraldRuleTypeConfig::RULE_TYPE_PERSONAL:
        return true;
      case HeraldRuleTypeConfig::RULE_TYPE_OBJECT:
      default:
        return false;
    }
  }

  public function getHeraldName() {
    return $this->getObject()->getMonogram();
  }

}

<?php

final class PhabricatorCalendarEventHeraldAdapter extends HeraldAdapter {

  private $object;

  public function getAdapterApplicationClass() {
    return 'PhabricatorCalendarApplication';
  }

  public function getAdapterContentDescription() {
    return pht('React to events being created or updated.');
  }

  protected function newObject() {
    return new PhabricatorCalendarEvent();
  }

  public function isTestAdapterForObject($object) {
    return ($object instanceof PhabricatorCalendarEvent);
  }

  public function getAdapterTestDescription() {
    return pht(
      'Test rules which run when an event is created or updated.');
  }

  public function setObject($object) {
    $this->object = $object;
    return $this;
  }

  public function getObject() {
    return $this->object;
  }

  public function getAdapterContentName() {
    return pht('Calendar Events');
  }

  public function supportsRuleType($rule_type) {
    switch ($rule_type) {
      case HeraldRuleTypeConfig::RULE_TYPE_GLOBAL:
      case HeraldRuleTypeConfig::RULE_TYPE_PERSONAL:
        return true;
      case HeraldRuleTypeConfig::RULE_TYPE_OBJECT:
      default:
        return false;
    }
  }

  public function getRepetitionOptions() {
    return array(
      HeraldRepetitionPolicyConfig::EVERY,
      HeraldRepetitionPolicyConfig::FIRST,
    );
  }

  public function getHeraldName() {
    return $this->getObject()->getMonogram();
  }

}

Allow Herald rules to apply "only the first time" to Calendar events

Summary: Fixes T12821. (Some events only happen once, so the default behavior doesn't let you pick this rule, and objects must opt into it by saying "yeah, I support multiple edits".)

Test Plan:
Note "only the first time" selected:

{F4999093}

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T12821

Differential Revision: https://secure.phabricator.com/D18117


<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Reply extends Model {

	//

}

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Reply extends Model {

	protected $fillable = [
		'body',
		'body_original',
		'user_id',
		'topic_id'
	];

	public static function boot()
	{
		parent::boot();

		static::created(function ($topic) {
			// Do something here.
		});
	}

	public function topic()
	{
		return $this->belongsTo('Topic');
	}

	public function user()
	{
		return $this->belongsTo('User');
	}

	public function votes()
	{
		return $this->morphsMany('Vote', 'votable');
	}

	public function scopeWhose($query, $user_id)
	{
		return $query->where('user_id', '=', $user_id)->with('topic');
	}

	public function scopeRecent($query)
	{
		return $query->orderBy('created_at', 'desc');
	}

}

Define some method and relate the relationships.


<?php

/* vim: set noexpandtab tabstop=4 shiftwidth=4 foldmethod=marker: */

require_once 'Swat/SwatEntry.php';

/**
 * A single line search entry widget
 *
 * @package   Swat
 * @copyright 2004-2007 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatSearch extends SwatEntry
{
	// {{{ public properties

	/**
	 * SwatSearch title value
	 *
	 * Text content of the widget, or defaults to 'Enter Search'.
	 *
	 * @var string
	 */
	public $title;

	// }}}
	// {{{ public function __construct()

	public function __construct($id = null)
	{
		parent::__construct($id);
		$this->title = Swat::_('Enter Search...');
	}

	// }}}
	// {{{ protected function getDisplayValue()

	/**
	 * Displays a value for SwatSearch
	 *
	 * The methond returns either the title or the correct search entry.
	 *
	 * @return string the display value
	 */
	protected function getDisplayValue()
	{
		$value = '';

		if ($this->value === null) {
			$value = $this->title;
		} else {
			$value = parent::getDisplayValue();
		}

		return $value;
	}

	// }}}
}

?>

<?php

/* vim: set noexpandtab tabstop=4 shiftwidth=4 foldmethod=marker: */

require_once 'Swat/SwatEntry.php';

/**
 * A single line search entry widget
 *
 * @package   Swat
 * @copyright 2004-2007 silverorange
 * @license   http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
 */
class SwatSearch extends SwatEntry
{
	// {{{ public properties

	/**
	 * SwatSearch title value
	 *
	 * Text content of the widget, or defaults to 'Enter Search …'.
	 *
	 * @var string
	 */
	public $title;

	// }}}
	// {{{ public function __construct()

	public function __construct($id = null)
	{
		parent::__construct($id);
		$this->title = Swat::_('Enter Search …');
	}

	// }}}
	// {{{ protected function getDisplayValue()

	/**
	 * Displays a value for SwatSearch
	 *
	 * The methond returns either the title or the correct search entry.
	 *
	 * @return string the display value
	 */
	protected function getDisplayValue()
	{
		$value = '';

		if ($this->value === null) {
			$value = $this->title;
		} else {
			$value = parent::getDisplayValue();
		}

		return $value;
	}

	// }}}
}

?>

Use the UTF-8 ellipsis character

Use the UTF-8 ellipsis character

svn commit r15188


<?php
namespace Spotman\Acl\ResourceRulesCollectorFactory;

use BetaKiller\Factory\NamespaceBasedFactory;
use Spotman\Acl\ResourceInterface;
use Spotman\Acl\ResourceRulesCollector\ResourceRulesCollectorInterface;

class GenericAclResourceRulesCollectorFactory implements AclResourceRulesCollectorFactoryInterface
{
    /**
     * @var \BetaKiller\Factory\NamespaceBasedFactory
     */
    private $factory;

    /**
     * GenericAclResourceRulesCollectorFactory constructor.
     *
     * @param \BetaKiller\Factory\NamespaceBasedFactory $factory
     */
    public function __construct(NamespaceBasedFactory $factory)
    {
        $this->factory = $factory
            ->setClassNamespaces('Acl', 'ResourceRulesCollector')
            ->setClassSuffix('ResourceRulesCollector')
            ->setExpectedInterface(ResourceRulesCollectorInterface::class);
    }

    /**
     * @param \Spotman\Acl\ResourceInterface $resource
     *
     * @return \Spotman\Acl\ResourceRulesCollector\ResourceRulesCollectorInterface
     */
    public function createCollector(ResourceInterface $resource)
    {
        $collectorName = $resource->getResourceId();

        return $this->factory->create($collectorName, [
            'resource' => $resource,
        ]);
    }
}

<?php
namespace Spotman\Acl\ResourceRulesCollectorFactory;

use BetaKiller\Factory\NamespaceBasedFactoryBuilder;
use Spotman\Acl\ResourceInterface;
use Spotman\Acl\ResourceRulesCollector\ResourceRulesCollectorInterface;

class GenericAclResourceRulesCollectorFactory implements AclResourceRulesCollectorFactoryInterface
{
    /**
     * @var \BetaKiller\Factory\NamespaceBasedFactory
     */
    private $factory;

    /**
     * GenericAclResourceRulesCollectorFactory constructor.
     *
     * @param \BetaKiller\Factory\NamespaceBasedFactoryBuilder $factoryBuilder
     */
    public function __construct(NamespaceBasedFactoryBuilder $factoryBuilder)
    {
        $this->factory = $factoryBuilder
            ->createFactory()
            ->setClassNamespaces('Acl', 'ResourceRulesCollector')
            ->setClassSuffix('ResourceRulesCollector')
            ->setExpectedInterface(ResourceRulesCollectorInterface::class);
    }

    /**
     * @param \Spotman\Acl\ResourceInterface $resource
     *
     * @return \Spotman\Acl\ResourceRulesCollector\ResourceRulesCollectorInterface
     * @throws \BetaKiller\Factory\FactoryException
     */
    public function createCollector(ResourceInterface $resource): ResourceRulesCollectorInterface
    {
        $collectorName = $resource->getResourceId();

        return $this->factory->create($collectorName, [
            'resource' => $resource,
        ]);
    }
}

Improve NamespaceBasedFactory + remove UrlDispatcherCache

- Prepare NamespaceBasedFactory for migrating to PHP-DI 6.0
- NamespaceBasedFactoryBuilder introduced
- Client code refactoring
- Various CS fixes


<?php
namespace Uphp\web;

use src\Inflection;
use \UPhp\ActionDispach\Routes as Route;
use \UPhp\ActionController\ActionController;

class Application
{
    public static $appConfig = [];
    public static $templateConfig = [];

    public function __construct()
    {
        //set_exception_handler("src\uphpExceptionHandler");
        //set_error_handler("src\uphpErrorHandler");
    }

    public function start($config)
    {
        //carregando os initializers
        $this->loadAppConfig();
        $this->getInitializersFiles();
        $this->getRoutes();
        $this->getLang();
        ActionController::callController($config);
    }

    private function getInitializersFiles()
    {
        $this->requireAllDir("config/initializers/");
    }

    private function getRoutes()
    {
        return require("config/routes.php");
    }

    private function getLang()
    {
        $this->requireAllDir("app/languages/");
    }

    private function loadAppConfig(){
        $config = require("config/application.php");
        if (isset($config["template"])) {
            $templateConfig = require("config/" . Inflection::tableize($config["template"]) . ".php");
            self::$templateConfig = $templateConfig;
        }
        self::$appConfig = $config;
    }

    private function requireAllDir($path)
    {
        $directory = dir($path);
        while ($file = $directory -> read()) {
            if ($file != "." && $file != "..") {
                require($path . $file);
            }
        }
        $directory->close();
    }
}

<?php
namespace Uphp\web;

use \UPhp\ActionController\ActionController;

class Application
{
    public static $appConfig = [];

    public function __construct()
    {
        set_exception_handler("src\uphpExceptionHandler");
        set_error_handler("src\uphpErrorHandler");
    }

    public function start($config)
    {
        //carregando os initializers
        $this->loadAppConfig();
        $this->getInitializersFiles();
        $this->getRoutes();
        $this->getLang();
        ActionController::callController($config);
    }

    private function getInitializersFiles()
    {
        $this->requireAllDir("config/initializers/");
    }

    private function getRoutes()
    {
        return require("config/routes.php");
    }

    private function getLang()
    {
        $this->requireAllDir("app/languages/");
    }

    private function loadAppConfig(){
        $config = require("config/application.php");
        self::$appConfig = $config;
    }

    private function requireAllDir($path)
    {
        $directory = dir($path);
        while ($file = $directory -> read()) {
            if ($file != "." && $file != "..") {
                if (is_dir($path .  $file)) {
                    $this->requireAllDir($path . $file . "/");
                } else {
                    require($path . $file);
                }
            }
        }
        $directory->close();
    }
}

Remove template language hard initialization to dynamic initialization


<?php

require('src/Message.php');
require('src/Metric.php');
require('src/Client.php');

// Register a new client
$a = new Agento\Client('127.0.0.1', 12345);

// Add a few tags describing this client
$a->addTag('hostname', 'webserver07');
$a->addTag('httphost', 'shopapi');

// We executed in 12.4 ms
$a->metric('executionTime', 1.0, 12.0);

?>

<?php

require('src/Message.php');
require('src/Metric.php');
require('src/Client.php');

// Register a new client
$a = new Agento\Client('127.0.0.1', 12345);

// Add a few tags describing this client
$a->addTag('hostname', 'webserver07');
$a->addTag('httphost', 'shopapi');

// We executed in 12.4 ms
$a->metric('executionTime', 1.0, 12.4);

?>

Make metric call match comment :)

Make metric call match comment :)


<?php

namespace Wnx\LaravelStats\Classifiers;

use Exception;
use Illuminate\Routing\Router;
use Wnx\LaravelStats\ReflectionClass;

class ControllerClassifier extends Classifier
{
    public function getName()
    {
        return 'Controllers';
    }

    public function satisfies(ReflectionClass $class)
    {
        return collect(resolve(Router::class)->getRoutes())
            ->map(function ($route) {
                try {
                    return get_class($route->getController());
                } catch (Exception $e) {
                    return;
                }
            })
            ->unique()
            ->contains($class->getName());
    }
}

<?php

namespace Wnx\LaravelStats\Classifiers;

use Exception;
use Illuminate\Routing\Router;
use Wnx\LaravelStats\ReflectionClass;

class ControllerClassifier extends Classifier
{
    public function getName()
    {
        return 'Controllers';
    }

    public function satisfies(ReflectionClass $class)
    {
        return collect(resolve(Router::class)->getRoutes())
            ->reject(function ($route) {
                return $route->getActionName() === 'Closure';
            })
            ->map(function ($route) {
                return get_class($route->getController());
            })
            ->unique()
            ->contains($class->getName());
    }
}

Use Route ActionName instead of try/catch block


<?php
namespace Doctrine\Tests\DBAL\Functional\Mysqli;

class ConnectionTest extends \Doctrine\Tests\DbalFunctionalTestCase
{
    public function setUp()
    {
        if (!extension_loaded('mysqli')) {
            $this->markTestSkipped('mysqli is not installed.');
        }

        $driver = getenv('DB');
        if (false !== $driver && $driver !== 'mysqli') {
            $this->markTestSkipped('this test case is for mysqli only');
        }

        $this->resetSharedConn();
        parent::setUp();
    }

    public function tearDown()
    {
        parent::tearDown();
        $this->resetSharedConn();
    }

    public function testDriverOptions()
    {
        $driverOptions = array(
            \MYSQLI_OPT_CONNECT_TIMEOUT => 1,
        );

        $connection = $this->getConnection($driverOptions);
        $this->assertInstanceOf("\Doctrine\DBAL\Driver\Mysqli\MysqliConnection", $connection);
    }

    /**
     * @expectedException \Doctrine\DBAL\Driver\Mysqli\MysqliException
     */
    public function testUnsupportedDriverOption()
    {
        $this->getConnection(array('hello' => 'world')); // use local infile
    }

    private function getConnection(array $driverOptions)
    {
        return new \Doctrine\DBAL\Driver\Mysqli\MysqliConnection(
            array(
                 'host' => $GLOBALS['db_host'],
                 'dbname' => $GLOBALS['db_name'],
            ),
            $GLOBALS['db_username'],
            $GLOBALS['db_password'],
            $driverOptions
        );
    }
}

<?php
namespace Doctrine\Tests\DBAL\Functional\Mysqli;

class ConnectionTest extends \Doctrine\Tests\DbalFunctionalTestCase
{
    public function setUp()
    {
        if (!extension_loaded('mysqli')) {
            $this->markTestSkipped('mysqli is not installed.');
        }

        $this->resetSharedConn();
        parent::setUp();

        if ( !($this->_conn->getDriver() instanceof \Doctrine\DBAL\Driver\Mysqli\Driver)) {
            $this->markTestSkipped('MySQLi only test.');
        }
    }

    public function tearDown()
    {
        parent::tearDown();
        $this->resetSharedConn();
    }

    public function testDriverOptions()
    {
        $driverOptions = array(
            \MYSQLI_OPT_CONNECT_TIMEOUT => 1,
        );

        $connection = $this->getConnection($driverOptions);
        $this->assertInstanceOf("\Doctrine\DBAL\Driver\Mysqli\MysqliConnection", $connection);
    }

    /**
     * @expectedException \Doctrine\DBAL\Driver\Mysqli\MysqliException
     */
    public function testUnsupportedDriverOption()
    {
        $this->getConnection(array('hello' => 'world')); // use local infile
    }

    private function getConnection(array $driverOptions)
    {
        return new \Doctrine\DBAL\Driver\Mysqli\MysqliConnection(
            array(
                 'host' => $GLOBALS['db_host'],
                 'dbname' => $GLOBALS['db_name'],
            ),
            $GLOBALS['db_username'],
            $GLOBALS['db_password'],
            $driverOptions
        );
    }
}

Fix test failures in MySQLi test

Fix test failures in MySQLi test


<?php namespace App\Http\Controllers;

use App\Items;
use App\User;

class FeedController extends BaseController {

    public function podcast($id, $secret)
    {
        /** @var \App\User $user */
        $user = User::find($id);

        if ($secret !== $user->secret()) {
            throw new \Exception("Secret mismatch");
        }

        return view('podcast', array(
            'user'  => $user,
            'userItems' => $user->userItems->sortByDesc('updated_at'),
        ));
    }

}

<?php namespace App\Http\Controllers;

use App\Items;
use App\User;

class FeedController extends BaseController {

    public function podcast($id, $secret)
    {
        /** @var \App\User $user */
        $user = User::find($id);

        if ($secret !== $user->secret()) {
            throw new \Exception("Secret mismatch");
        }

        return response()->view('podcast', array(
            'user'  => $user,
            'userItems' => $user->userItems->sortByDesc('updated_at'),
        ))->header('Content-Type', 'application/xml');
    }

}

Return feed as xml content type.

Return feed as xml content type.


<?php
$defflip = (!cfip()) ? exit(header('HTTP/1.1 401 Unauthorized')) : 1;

// Check if the API is activated
$api->isActive();

// Check user token
$user_id = $api->checkAccess($user->checkApiKey($_REQUEST['api_key']), @$_REQUEST['id']);

// Fetch transactions
if (isset($_REQUEST['start'])) {
  $start = $_REQUEST['start'];
} else {
  // start at the beginning
  $start = 0;
}
if (isset($_REQUEST['limit']) && $_REQUEST['limit'] <= 100) {
  $limit = $_REQUEST['limit'];
} else {
  // Force limit
  $limit = 100;
}

$data['transactions'] = $transaction->getTransactions($start, NULL, $limit, $user_id);

// Fetch summary if enabled
if (!$setting->getValue('disable_transactionsummary')) {
  $aTransactionSummary = $transaction->getTransactionSummary($user_id);
  $data['transactionsummary'] = $aTransactionSummary;
}

// Output JSON format
echo $api->get_json($data);

// Supress master template
$supress_master = 1;

<?php
$defflip = (!cfip()) ? exit(header('HTTP/1.1 401 Unauthorized')) : 1;

// Check if the API is activated
$api->isActive();

// Check user token
$user_id = $api->checkAccess($user->checkApiKey($_REQUEST['api_key']), @$_REQUEST['id']);

// Fetch transactions
if (isset($_REQUEST['limit']) && $_REQUEST['limit'] <= 100) {
  $limit = $_REQUEST['limit'];
} else {
  // Force limit
  $limit = 100;
}
$data['transactions'] = $transaction->getTransactions(0, NULL, $limit, $user_id);

// Fetch summary if enabled
if (!$setting->getValue('disable_transactionsummary')) {
  $aTransactionSummary = $transaction->getTransactionSummary($user_id);
  $data['transactionsummary'] = $aTransactionSummary;
}

// Output JSON format
echo $api->get_json($data);

// Supress master template
$supress_master = 1;

Revert "add 'start' parameter to getusertransactions api page"


<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>

            Home

            Catalog

            Tickets

            Log In

            About

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>

            <a href="<?php echo site_url('welcome');?>">Home

            <a href="<?php echo site_url('welcome/catalog');?>">Catalog

            <a href="<?php echo site_url('welcome/tickets');?>">Tickets

            <a href="<?php echo site_url('welcome/log-in');?>">Log In

            <a href="<?php echo site_url('welcome/About');?>">About

Use the site_url() function inside the menu view.


<?php

namespace Plummer\Calendar;

abstract class CalendarAbstract implements CalendarInterface
{
	protected $events;

	protected $recurrenceTypes;

	protected function __construct(\Iterator $events, $recurrenceTypes)
	{
		$this->events = $events;
		$this->addRecurrenceTypes($recurrenceTypes);
	}

	public static function make(\Iterator $events, $recurrenceTypes = [])
	{
		return new static($events, $recurrenceTypes);
	}

	public function addEvents(array $events)
	{
		foreach($events as $event) {
			$this->addEvent($event);
		}
	}

	public function addRecurrenceTypes(array $recurrenceTypes)
	{
		foreach($recurrenceTypes as $recurrenceType) {
			$this->addRecurrenceType($recurrenceType);
		}
	}

	abstract public function addEvent(EventInterface $event);

	abstract public function addRecurrenceType(RecurrenceInterface $recurrenceType);

	abstract public function getEvents();
}

<?php

namespace Plummer\Calendar;

abstract class CalendarAbstract implements CalendarInterface
{
	protected $name;

	protected $events;

	protected $recurrenceTypes;

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

	public function addEvents($events)
	{
		if($events instanceof \Iterator) {
			$this->events->append($events);
		}
		elseif(is_array($events)) {
			foreach($events as $key => $event) {
				$this->events[$key] = $event;
			}
		}
	}

	public function addRecurrenceTypes($recurrenceTypes)
	{
		if($recurrenceTypes instanceof \Iterator) {
			$this->recurrenceTypes->append($recurrenceTypes);
		}
		elseif(is_array($recurrenceTypes)) {
			foreach($recurrenceTypes as $key => $recurrenceType) {
				$this->recurrenceTypes[$key] = $recurrenceType;
			}
		}
	}

	abstract public function addEvent(EventInterface $event);

	abstract public function addRecurrenceType(RecurrenceInterface $recurrenceType);

	abstract public function getEvents();
}

Restructure abstract calendar to use iterators.


<?php

namespace Liip\RMT\Tests\Functional;

use Exception;
use Liip\RMT\Context;
use Liip\RMT\Prerequisite\TestsCheck;

class TestsCheckTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        $informationCollector = $this->getMock('Liip\RMT\Information\InformationCollector');
        $informationCollector->method('getValueFor')->with(TestsCheck::SKIP_OPTION)->willReturn(false);

        $output = $this->getMock('Symfony\Component\Console\Output\OutputInterface');
        $output->method('write');

        $context = Context::getInstance();
        $context->setService('information-collector', $informationCollector);
        $context->setService('output', $output);
    }

    /** @test */
    public function succeeds_when_command_finished_within_the_default_configured_timeout_of_60s()
    {
        $check = new TestsCheck(['command' => 'echo OK']);
        $check->execute();
    }

    /** @test */
    public function succeeds_when_command_finished_within_configured_timeout()
    {
        $check = new TestsCheck(['command' => 'echo OK', 'timeout' => 0.100]);
        $check->execute();
    }

    /** @test */
    public function fails_when_the_command_exceeds_the_timeout()
    {
        $this->setExpectedException('Exception', 'exceeded the timeout');

        $check = new TestsCheck(['command' => 'sleep 1', 'timeout' => 0.100]);
        $check->execute();
    }
}

<?php

namespace Liip\RMT\Tests\Functional;

use Exception;
use Liip\RMT\Context;
use Liip\RMT\Prerequisite\TestsCheck;

class TestsCheckTest extends \PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        $informationCollector = $this->getMock('Liip\RMT\Information\InformationCollector');
        $informationCollector->method('getValueFor')->with(TestsCheck::SKIP_OPTION)->willReturn(false);

        $output = $this->getMock('Symfony\Component\Console\Output\OutputInterface');
        $output->method('write');

        $context = Context::getInstance();
        $context->setService('information-collector', $informationCollector);
        $context->setService('output', $output);
    }

    /** @test */
    public function succeeds_when_command_finished_within_the_default_configured_timeout_of_60s()
    {
        $check = new TestsCheck(array('command' => 'echo OK'));
        $check->execute();
    }

    /** @test */
    public function succeeds_when_command_finished_within_configured_timeout()
    {
        $check = new TestsCheck(array('command' => 'echo OK', 'timeout' => 0.100));
        $check->execute();
    }

    /** @test */
    public function fails_when_the_command_exceeds_the_timeout()
    {
        $this->setExpectedException('Exception', 'exceeded the timeout');

        $check = new TestsCheck(array('command' => 'sleep 1', 'timeout' => 0.100));
        $check->execute();
    }
}

Use PHP 5.3-compatible traditional array syntax


<?php
/**
 * @file    PostCurlRequest.php
 *
 * PHP version 5.4+
 *
 * @author  Yancharuk Alexander <alex at itvault dot info>
 * @date    2015-01-20 20:16
 * @copyright The BSD 3-Clause License
 */

namespace Veles\Request;

/**
 * Class PostCurlRequest
 * @author  Yancharuk Alexander <alex at itvault dot info>
 */
class PostCurlRequest extends CurlRequest
{
	/** @var array */
	protected $default_options = [
		CURLOPT_RETURNTRANSFER => true,		// output to string instead stdout
		CURLOPT_CONNECTTIMEOUT => 10,		// timeout on connect
		CURLOPT_TIMEOUT        => 10,		// timeout on request
		CURLOPT_POST           => true
	];

	/**
	 * Set request data
	 *
	 * @param array $data
	 *
	 * @return bool
	 */
	public function setData(array $data)
	{
		return $this->setOption(CURLOPT_POSTFIELDS, $data);
	}
}

<?php
/**
 * @file    PostCurlRequest.php
 *
 * PHP version 5.4+
 *
 * @author  Yancharuk Alexander <alex at itvault dot info>
 * @date    2015-01-20 20:16
 * @copyright The BSD 3-Clause License
 */

namespace Veles\Request;

/**
 * Class PostCurlRequest
 * @author  Yancharuk Alexander <alex at itvault dot info>
 */
class PostCurlRequest extends CurlRequest
{
	/** @var array */
	protected $default_options = [
		CURLOPT_RETURNTRANSFER => true,		// output to string instead stdout
		CURLOPT_CONNECTTIMEOUT => 10,		// timeout on connect
		CURLOPT_TIMEOUT        => 10,		// timeout on request
		CURLOPT_POST           => true
	];

	/**
	 * Set request data
	 *
	 * @param string|array $data
	 *
	 * @return bool
	 */
	public function setData($data)
	{
		return $this->setOption(CURLOPT_POSTFIELDS, $data);
	}
}

Allow string as POSTFIELDS param

Allow string as POSTFIELDS param


<?php

declare(strict_types=1);

/*
 * This file is part of the RollerworksSearch package.
 *
 * (c) Sebastiaan Stok <s.stok@rollerscapes.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Rollerworks\Component\Search\ApiPlatform\Tests\Mock;

use Rollerworks\Component\Search\ApiPlatform\Tests\Fixtures\BookFieldSet;
use Rollerworks\Component\Search\Field\FieldConfig;
use Rollerworks\Component\Search\FieldSet;

final class FieldSetStub implements FieldSet
{
    public function getSetName(): ?string
    {
        return BookFieldSet::class;
    }

    public function get(string $name): FieldConfig
    {
    }

    public function all(): array
    {
        return [];
    }

    public function has(string $name): bool
    {
        return false;
    }
}

<?php

declare(strict_types=1);

/*
 * This file is part of the RollerworksSearch package.
 *
 * (c) Sebastiaan Stok <s.stok@rollerscapes.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Rollerworks\Component\Search\ApiPlatform\Tests\Mock;

use Rollerworks\Component\Search\ApiPlatform\Tests\Fixtures\BookFieldSet;
use Rollerworks\Component\Search\Field\FieldConfig;
use Rollerworks\Component\Search\FieldSet;

final class FieldSetStub implements FieldSet
{
    public function getSetName(): ?string
    {
        return BookFieldSet::class;
    }

    public function get(string $name): FieldConfig
    {
    }

    public function all(): array
    {
        return [];
    }

    public function has(string $name): bool
    {
        return false;
    }

    public function isPrivate(string $name): bool
    {
        return '_' === $name[0];
    }
}

Add support for private fields

Add support for private fields

A field name accepts a single underscore prefix to indicate it’s private.

Private fields can only be used in a PrimaryCondition and are simple ignored for user-input.


            <?php echo ucwords(str_replace('_', ' ', ($this->response->meta->collection))); ?>
            <?php
            if ($this->m_users->get_user_permission('', $this->response->meta->collection, 'c') and $this->response->meta->collection != 'configuration') { ?>

                    <a class="btn btn-xs btn-primary" href="<?php echo $this->response->meta->collection; ?>/create" role="button"><?php echo __('Create'); ?>

            <?php } ?>

                <?php echo $this->response->meta->filtered . ' of ' . $this->response->meta->total . ' results'; ?>

            <?php echo ucwords(str_replace('_', ' ', ($this->response->meta->collection))); ?>
            <?php
            if ($this->m_users->get_user_permission('', $this->response->meta->collection, 'c') and $this->response->meta->collection != 'configuration' and $this->response->meta->collection != 'database') { ?>

                    <a class="btn btn-xs btn-primary" href="<?php echo $this->response->meta->collection; ?>/create" role="button"><?php echo __('Create'); ?>

            <?php } ?>

                <?php echo $this->response->meta->filtered . ' of ' . $this->response->meta->total . ' results'; ?>

Remove create button in collection header when endpoint is database.


<?php
namespace Concrete\Core\Express\Entry;

use Concrete\Core\Entity\Express\Entry;
use Concrete\Core\Support\Facade\Facade;
use Doctrine\ORM\Event\LifecycleEventArgs;

class Listener
{
    public function preRemove(Entry $entry, LifecycleEventArgs $event)
    {
        $app = Facade::getFacadeApplication();
        $express = $app->make('express');
        $associations = $entry->getAssociations();
        foreach ($associations as $entryAssociation) {
            /**
             * @var $entryAssociation Entry\Association
             */
            if ($entryAssociation->getAssociation()->isOwningAssociation()) {
                $associatedEntries = $entryAssociation->getSelectedEntries();
                if ($associatedEntries) {
                    foreach ($associatedEntries as $associatedEntry) {
                        $express->deleteEntry($associatedEntry->getId());
                    }
                }
            }
        }
        $db = $event->getEntityManager()->getConnection();

        // Delete any express entry attributes that have this selected.
        $db->Execute('delete from atExpressSelectedEntries where exEntryID = ?', array($entry->getID()));

        // Delete this from any associations that reference it
        $db->Execute('delete from ExpressEntityAssociationEntries where exEntryID = ?', array($entry->getID()));

        $category = \Core::make('Concrete\Core\Attribute\Category\ExpressCategory');

        foreach ($category->getAttributeValues($entry) as $value) {
            $category->deleteValue($value);
        }
    }
}

<?php
namespace Concrete\Core\Express\Entry;

use Concrete\Core\Entity\Express\Entry;
use Doctrine\ORM\Event\LifecycleEventArgs;

class Listener
{

    public function preRemove(Entry $entry, LifecycleEventArgs $event)
    {
        $db = $event->getEntityManager()->getConnection();

        // Delete any express entry attributes that have this selected.
        $db->Execute('delete from atExpressSelectedEntries where exEntryID = ?', array($entry->getID()));

        $category = \Core::make('Concrete\Core\Attribute\Category\ExpressCategory');

        foreach($category->getAttributeValues($entry) as $value) {
            $category->deleteValue($value);
        }

    }

}

Fix tests by reverting entity listener change – this will have to wait until 8.5


@extends('_layouts.master')

@section('body')

			Gauguin
			|
			Artist as Alchemist

			June 25
			–
			Sept 10

			Become a Member
			Get Tickets

@endsection

Add links to header buttons

Add links to header buttons


<?php

namespace SayAndDo\TaskBundle\Service;

use Doctrine\ORM\EntityManager;
use SayAndDo\TaskBundle\DependencyInjection\TaskStatus;
use SayAndDo\TaskBundle\Entity\Task;

class TaskService {

    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function store($task)
    {
        $this->saveEntity($task);
    }

    private function saveEntity($entity)
    {
        $this->em->persist($entity);
        $this->em->flush();
    }

    public function confirmTask(Task $task)
    {
        $task->setStatus(TaskStatus::STATUS_CONFIRMED);
        $this->store($task);
    }

    public function startTask(Task $task)
    {
        $task->setStatus(TaskStatus::STATUS_IN_PROGRESS);
        $this->store($task);
    }

    public function completeTask(Task $task)
    {
        $task->setStatus(TaskStatus::STATUS_DONE);
        $this->store($task);
    }
}

<?php

namespace SayAndDo\TaskBundle\Service;

use Doctrine\ORM\EntityManager;
use SayAndDo\TaskBundle\DependencyInjection\TaskPoints;
use SayAndDo\TaskBundle\DependencyInjection\TaskStatus;
use SayAndDo\TaskBundle\Entity\Task;

class TaskService {

    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function store($task)
    {
        $this->saveEntity($task);
    }

    private function saveEntity($entity)
    {
        $this->em->persist($entity);
        $this->em->flush();
    }

    public function confirmTask(Task $task)
    {
        $task->setStatus(TaskStatus::STATUS_CONFIRMED);
        $this->store($task);
    }

    public function startTask(Task $task)
    {
        $task->setStatus(TaskStatus::STATUS_IN_PROGRESS);
        $this->store($task);
    }

    public function completeTask(Task $task)
    {
        $task->setStatus(TaskStatus::STATUS_DONE);
        $this->store($task);

        $task->getProfile()->setPoints($task->getProfile()->getPoints() + TaskPoints::FOR_FINISHED_TASK);
        $this->saveEntity($task->getProfile());
    }
}

Add X points to profile on task complete


<?php

namespace Adldap\Laravel\Validation\Rules;

use Adldap\Laravel\Events\AuthenticatedModelTrashed;
use Illuminate\Support\Facades\Event;

class DenyTrashed extends Rule
{
    /**
     * {@inheritdoc}
     */
    public function isValid()
    {
        if ($this->isTrashed()) {
            Event::dispatch(
                new AuthenticatedModelTrashed($this->user, $this->model)
            );

            return false;
        }

        return true;
    }

    /**
     * Determines if the current model is trashed.
     *
     * @return bool
     */
    protected function isTrashed()
    {
        return method_exists($this->model, 'trashed') && $this->model->trashed();
    }
}

<?php

namespace Adldap\Laravel\Validation\Rules;

use Adldap\Laravel\Events\AuthenticatedModelTrashed;
use Illuminate\Support\Facades\Event;

class DenyTrashed extends Rule
{
    /**
     * {@inheritdoc}
     */
    public function isValid()
    {
        if ($this->isTrashed()) {
            Event::dispatch(
                new AuthenticatedModelTrashed($this->user, $this->model)
            );

            return false;
        }

        return true;
    }

    /**
     * Determines if the current model is trashed.
     *
     * @return bool
     */
    protected function isTrashed()
    {
        if ($this->model) {
            return method_exists($this->model, 'trashed') && $this->model->trashed();
        }
        return false;
    }
}

Make it work with PHP 8.0

Make it work with PHP 8.0

method_exists requires first parameter to be object or string now and won't accept a null parameter


<?php

class CM_Stream_Cli extends CM_Cli_Runnable_Abstract {

    /**
     * @synchronized
     */
    public function startMessageSynchronization() {
        CM_Stream_Message::getInstance()->startSynchronization();
    }

    public static function getPackageName() {
        return 'stream';
    }
}

<?php

class CM_Stream_Cli extends CM_Cli_Runnable_Abstract {

    /**
     * @synchronized
     */
    public function startMessageSynchronization() {
        CM_Stream_Message::getInstance()->startSynchronization();
    }

    /**
     * @param string  $streamName
     * @param CM_File $thumbnailSource
     * @throws CM_Exception_Invalid
     */
    public function wowzaImportThumbnail($streamName, CM_File $thumbnailSource) {
        $streamChannel = CM_Model_StreamChannel_Video::findByKey($streamName);
        if (!$streamChannel) {
            throw new CM_Exception_Invalid('Cannot find streamChannel with key `' . $streamName . '`.');
        }
        $thumbnailCount = $streamChannel->getThumbnailCount();
        $thumbnailDest = $streamChannel->getThumbnail($thumbnailCount + 1);
        if (0 == $thumbnailCount) {
            $thumbnailDest->ensureParentDirectory();
        }
        $thumbnailSource->copyToFile($thumbnailDest);
        $streamChannel->setThumbnailCount($thumbnailCount + 1);
    }

    public static function getPackageName() {
        return 'stream';
    }
}

Add wowza thumbnail import cli command

Add wowza thumbnail import cli command


<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Stdlib\Hydrator;

use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Stdlib\Exception;

class DelegatingHydrator implements HydratorInterface
{
    /**
     * @var ServiceLocatorInterface
     */
    protected $hydrators;

    /**
     * Constructor
     *
     * @param ServiceLocatorInterface $hydrators
     */
    public function __construct(ServiceLocatorInterface $hydrators)
    {
        $this->hydrators = $hydrators;
    }

    /**
     * {@inheritdoc}
     */
    public function hydrate(array $data, $object)
    {
        return $this->getHydrator($object)->hydrate($data, $object);
    }

    /**
     * {@inheritdoc}
     */
    public function extract($object)
    {
        return $this->getHydrator($object)->extract($object);
    }

    /**
     * Gets hydrator of an object
     *
     * @param  object $object
     * @return HydratorInterface
     */
    protected function getHydrator($object)
    {
        return $this->hydrators->get(get_class($object));
    }
}

<?php
/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/zf2 for the canonical source repository
 * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Zend\Stdlib\Hydrator;

use Zend\ServiceManager\ServiceLocatorInterface;

class DelegatingHydrator implements HydratorInterface
{
    /**
     * @var ServiceLocatorInterface
     */
    protected $hydrators;

    /**
     * Constructor
     *
     * @param ServiceLocatorInterface $hydrators
     */
    public function __construct(ServiceLocatorInterface $hydrators)
    {
        $this->hydrators = $hydrators;
    }

    /**
     * {@inheritdoc}
     */
    public function hydrate(array $data, $object)
    {
        return $this->getHydrator($object)->hydrate($data, $object);
    }

    /**
     * {@inheritdoc}
     */
    public function extract($object)
    {
        return $this->getHydrator($object)->extract($object);
    }

    /**
     * Gets hydrator of an object
     *
     * @param  object $object
     * @return HydratorInterface
     */
    protected function getHydrator($object)
    {
        return $this->hydrators->get(get_class($object));
    }
}

Fix CS issues reported by php-cs-fixer

Fix CS issues reported by php-cs-fixer

- Remove unused use


<?php

namespace Spatie\MediaLibrary;

use Illuminate\Support\ServiceProvider;
use Spatie\MediaLibrary\Commands\RegenerateCommand;

class MediaLibraryServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     */
    public function boot()
    {
        Media::observe(new MediaObserver());

        $this->publishes([
            __DIR__.'/../resources/config/laravel-medialibrary.php' => $this->app->configPath().'/'.'laravel-medialibrary.php',
        ], 'config');

        if (!class_exists('CreateMediaTable')) {

            // Publish the migration
            $timestamp = date('Y_m_d_His', time());

            $this->publishes([
                __DIR__.'/../resources/migrations/create_media_table.php.stub' => $this->app->basePath().'/'.'database/migrations/'.$timestamp.'_create_media_table.php',
            ], 'migrations');
        }
    }

    /**
     * Register the service provider.
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../resources/config/laravel-medialibrary.php', 'laravel-medialibrary');

        $this->app->singleton(MediaRepository::class);

        $this->app['command.medialibrary:regenerate'] = $this->app->make(RegenerateCommand::class);

        $this->commands(['command.medialibrary:regenerate']);
    }
}

<?php

namespace Spatie\MediaLibrary;

use Illuminate\Support\ServiceProvider;
use Spatie\MediaLibrary\Commands\RegenerateCommand;

class MediaLibraryServiceProvider extends ServiceProvider
{
    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     */
    public function boot()
    {
        Media::observe(new MediaObserver());

        $this->publishes([
            __DIR__.'/../resources/config/laravel-medialibrary.php' => $this->app->configPath().'/'.'laravel-medialibrary.php',
        ], 'config');

        if (!class_exists('CreateMediaTable')) {

            // Publish the migration
            $timestamp = date('Y_m_d_His', time());

            $this->publishes([
                __DIR__.'/../resources/migrations/create_media_table.php.stub' => $this->app->basePath().'/'.'database/migrations/'.$timestamp.'_create_media_table.php',
            ], 'migrations');
        }
    }

    /**
     * Register the service provider.
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../resources/config/laravel-medialibrary.php', 'laravel-medialibrary');

        $this->app->singleton(MediaRepository::class);

        $this->app->bind('command.medialibrary:regenerate', RegenerateCommand::class);

        $this->commands(['command.medialibrary:regenerate']);
    }
}

Fix an issue where binding the command would fail


<?php

function getReferralID() {
    global $_GET;

    if (empty($_GET['r'])) {
        return null;
    }

    return intval($_GET['r']);
}

function hasValidReferralData() {
    $referralID = getReferralID();

    return ($referralID > 0);
}

function hasReferralCookie() {
    global $_COOKIE;

    $referralCookieKey = REFERING_COOKIENAME;

    return (!empty($_COOKIE[$referralCookieKey]));
}

function onValidReferralDataProvided($referralID) {
    global $_COOKIE;

    define('INSIDE', true);

    $_EnginePath = './';
    include($_EnginePath . 'includes/constants.php');

    if (hasReferralCookie()) {
        return;
    }

    $nowTimestamp = time();
    $referralCookieTTLDays = 14;
    $referralCookieTTL = ($referralCookieTTLDays * TIME_DAY);

    setcookie(
        REFERING_COOKIENAME,
        $referralID,
        $nowTimestamp + $referralCookieTTL,
        '',
        GAMEURL_DOMAIN
    );
}

function renderPage() {
    if (!hasValidReferralData()) {
        header('Location: login.php');

        return;
    }

    $referralID = getReferralID();

    onValidReferralDataProvided($referralID);

    header('Location: reg.php');
}

renderPage();

?>

<?php

function getReferralID() {
    global $_GET;

    if (empty($_GET['r'])) {
        return null;
    }

    return intval($_GET['r']);
}

function hasValidReferralData() {
    $referralID = getReferralID();

    return ($referralID > 0);
}

function hasReferralCookie() {
    global $_COOKIE;

    $referralCookieKey = REFERING_COOKIENAME;

    return (!empty($_COOKIE[$referralCookieKey]));
}

function onValidReferralDataProvided($referralID) {
    global $_COOKIE;

    define('INSIDE', true);

    $_EnginePath = './';
    include($_EnginePath . 'includes/constants.php');

    if (hasReferralCookie()) {
        return;
    }

    $nowTimestamp = time();
    $referralCookieTTLDays = 14;
    $referralCookieTTL = ($referralCookieTTLDays * TIME_DAY);

    setcookie(
        REFERING_COOKIENAME,
        $referralID,
        $nowTimestamp + $referralCookieTTL,
        '',
        GAMEURL_DOMAIN
    );
}

function renderPage() {
    if (!hasValidReferralData()) {
        header('Location: login.php');

        return;
    }

    $referralID = getReferralID();

    onValidReferralDataProvided($referralID);

    header('Location: reg_mainpage.php');
}

renderPage();

?>

Fix the registration page redirection

Fix the registration page redirection


<?php
/**
 * The main template file.
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 * Learn more: http://codex.wordpress.org/Template_Hierarchy
 *
 * @package _s
 */

get_header(); ?>

	<div id="primary" class="content-area">
		<main id="main" class="site-main" role="main">

		<?php if ( have_posts() ) : ?>

			<?php /* Start the Loop */ ?>
			<?php while ( have_posts() ) : the_post(); ?>

				<?php
					/* Include the Post-Format-specific template for the content.
					 * If you want to override this in a child theme, then include a file
					 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
					 */
					get_template_part( 'content', get_post_format() );
				?>

			<?php endwhile; ?>

			<?php _s_content_nav( 'nav-below' ); ?>

		<?php else : ?>

			<?php get_template_part( 'no-results', 'index' ); ?>

		<?php endif; ?>

		</main><!-- #main -->
	</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

<?php
/**
 * The main template file.
 *
 * This is the most generic template file in a WordPress theme
 * and one of the two required files for a theme (the other being style.css).
 * It is used to display a page when nothing more specific matches a query.
 * E.g., it puts together the home page when no home.php file exists.
 * Learn more: http://codex.wordpress.org/Template_Hierarchy
 *
 * @package _s
 */

get_header(); ?>

	<div id="primary" class="content-area">
		<main id="main" class="site-main" role="main">

		<?php if ( have_posts() ) : ?>

			<?php /* Start the Loop */ ?>
			<?php while ( have_posts() ) : the_post(); ?>

				<?php
					/* Include the Post-Format-specific template for the content.
					 * If you want to override this in a child theme, then include a file
					 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
					 */
					get_template_part( 'content', get_post_format() );
				?>

			<?php endwhile; ?>

			<?php _s_content_nav( 'nav-below' ); ?>

		<?php else : ?>

			<?php get_template_part( 'content', 'none' ); ?>

		<?php endif; ?>

		</main><!-- #main -->
	</div><!-- #primary -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Use content-none.php instead of no-results.php

Renamed no-results.php to content-none.php for consistency (as done in core: https://core.trac.wordpress.org/ticket/25181); so let's make sure it's used.


<?php

namespace LaravelFlare\Cms;

class CmsModuleProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     */
    public function boot()
    {
        $this->registerBladeOperators();
    }

    /**
     * Register any package services.
     */
    public function register()
    {
        $this->registerServiceProviders();
    }

    /**
     * Register Service Providers.
     */
    protected function registerServiceProviders()
    {
    }

    /**
     * Register Blade Operators.
     */
    protected function registerBladeOperators()
    {
    }
}

<?php

namespace LaravelFlare\Cms;

use Illuminate\Support\ServiceProvider;

class CmsModuleProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     */
    public function boot()
    {
        $this->registerBladeOperators();
    }

    /**
     * Register any package services.
     */
    public function register()
    {
        $this->registerServiceProviders();
    }

    /**
     * Register Service Providers.
     */
    protected function registerServiceProviders()
    {
    }

    /**
     * Register Blade Operators.
     */
    protected function registerBladeOperators()
    {
    }
}

Add use ServiceProvider to PageModuleProvider


<?php namespace Orchestra\Memory\Console;

use Illuminate\Console\Command;

class MemoryCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'memory:migrate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run migration for orchestra/memory package.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $path = 'vendor/orchestra/memory/resources/database/migrations';

        $this->call('migrate', ['--path' => $path]);
    }
}

<?php namespace Orchestra\Memory\Console;

use Illuminate\Console\Command;

class MemoryCommand extends Command
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'memory:migrate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run migration for orchestra/memory package.';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $path = 'vendor/orchestra/memory/resources/database/migrations';

        $this->call('migrate', ['--path' => $path]);
    }
}

Rename Command fire method to handle

Rename Command fire method to handle

Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

/*
 * Include the settings.
 */
require('settings.inc.php');

/*
 * Include the Instant API library.
 */
include('class.InstantAPI.php');

/*
 * All output will be as JSON.
 */
header('Content-Type: application/json');

/*
 * Require that an ID be present in the request.
 */
if (!isset($_GET['id']))
{
	json_error('No ID provided.');
	die();
}

/*
 * Create a new instance of Instant API.
 */
$server = new InstantAPI();

/*
 * If the requested ID doesn't exist, return a 404.
 */
if (!isset($server->data->{$server->id}))
{
	json_error('ID not found.', '404 Not Found');
	die();
}

/*
 * Return the record to the client.
 */
echo json_encode($server->data->{$server->id});

<?php

/*
 * Include the settings.
 */
require('settings.inc.php');

/*
 * Include the Instant API library.
 */
require('class.InstantAPI.php');

/*
 * All output will be as JSON.
 */
header('Content-Type: application/json');

/*
 * Require that an ID be present in the request.
 */
if (!isset($_GET['id']))
{
	json_error('No ID provided.');
	die();
}

/*
 * Create a new instance of Instant API.
 */
$server = new InstantAPI();

/*
 * If the requested ID doesn't exist, return a 404.
 */
if (!isset($server->data->{$server->id}))
{
	json_error('ID not found.', '404 Not Found');
	die();
}

/*
 * Return the record to the client.
 */
echo json_encode($server->data->{$server->id});

Change from an include to a require

Change from an include to a require

It’s not like this file is optional.


<?php
	$log_file = fopen('../../log.txt','a');
	date_default_timezone_set('America/New_York');
	$date = date('Y-m-d H:i:s', time());
	$request_body = file_get_contents('php://input');
	$log_entry = $date . " " . $request_body . "\r\n";
	fwrite($log_file, $log_entry);
	fclose($log_file);
	echo $log_entry;
?>

<?php
	$log_file = fopen('../../log.txt','a');
	date_default_timezone_set('America/New_York');
	$date = date('Y-m-d H:i:s', time());
	$request_body = file_get_contents('php://input');
	$log_entry = $date . " " . $request_body . "\n";
	fwrite($log_file, $log_entry);
	fclose($log_file);
	echo $log_entry;
?>

Remove carriage return on log script

Remove carriage return on log script


<?php

namespace LiteCQRS\Plugin\Doctrine\EventStore;

use LiteCQRS\DomainEvent;
use LiteCQRS\EventStore\EventStoreInterface;
use LiteCQRS\EventStore\SerializerInterface;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema\Schema;

/**
 * Store events in a database table using Doctrine DBAL.
 */
class TableEventStore implements EventStoreInterface
{
    private $conn;
    private $table;
    private $serializer;

    public function __construct(Connection $conn, SerializerInterface $serializer, $table = 'litecqrs_events')
    {
        $this->conn       = $conn;
        $this->serializer = $serializer;
        $this->table      = $table;
    }

    public function store(DomainEvent $event)
    {
        $header = $event->getMessageHeader();

        $aggregateId = $header->aggregateId;
        if (is_array($aggregateId)) {
            $aggregateId = json_encode($aggregateId);
        }

        $this->conn->insert($this->table, array(
            'event_id'       => $header->id,
            'aggregate_type' => $header->aggregateType,
            'aggregate_id'   => $aggregateId,
            'event'          => $event->getEventName(),
            'event_date'     => $header->date->format('Y-m-d H:i:s'),// looses microseconds precision
            'command_id'     => $header->commandId,
            'session_id'     => $header->sessionId,
            'data'           => $this->serializer->serialize($event, 'json'),
        ));
    }
}

<?php

namespace LiteCQRS\Plugin\Doctrine\EventStore;

use LiteCQRS\DomainEvent;
use LiteCQRS\EventStore\EventStoreInterface;
use LiteCQRS\EventStore\SerializerInterface;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Schema\Schema;

/**
 * Store events in a database table using Doctrine DBAL.
 */
class TableEventStore implements EventStoreInterface
{
    private $conn;
    private $table;
    private $serializer;

    public function __construct(Connection $conn, SerializerInterface $serializer, $table = 'litecqrs_events')
    {
        $this->conn       = $conn;
        $this->serializer = $serializer;
        $this->table      = $table;
    }

    public function store(DomainEvent $event)
    {
        $header = $event->getMessageHeader();

        $aggregateId = $header->aggregateId;

        $this->conn->insert($this->table, array(
            'event_id'       => $header->id,
            'aggregate_type' => $header->aggregateType,
            'aggregate_id'   => $aggregateId,
            'event'          => $event->getEventName(),
            'event_date'     => $header->date->format('Y-m-d H:i:s'),// looses microseconds precision
            'command_id'     => $header->commandId,
            'session_id'     => $header->sessionId,
            'data'           => $this->serializer->serialize($event, 'json'),
        ));
    }
}

Remove json_encode() on array keys

Remove json_encode() on array keys


@extends('layouts.dashboard')

@section('title')
Accueil
@endsection

@section('smalltitle')
Mises à jour, informations, ...
@endsection

@section('content')

20/07/2015 — Site opérationnel

        Toutes les fonctionalités prévues sont opérationnelles !

@endsection

@extends('layouts.dashboard')

@section('title')
Accueil
@endsection

@section('smalltitle')
Informations diverses pour toi !
@endsection

@section('content')

Bonjour à toi bénévole !

Si tu vois ce message, c'est que tu fais partie de la grande famille des bénévoles de l'intégration. Et nous t'en remercions !

Tu te trouves sur le panneau de gestion du site de l'intégration.
                Ta mission la plus importante sur ce site est de tenir à jour ton numéro de téléphone et ton email afin de pouvoir être contacté lorsque l'intégration a besoin de toi. Tu peux les modifier en allant dans Mon compte > Mon profil bénévole.

            @if (EtuUTT::student()->isAdmin())

                    Comme tu es administrateur, ce site te permettra de faire pleins d'autres truc, mais j'ai la flème de tous les décrire.
                    Du coup je te laisse faire joujoux avec ;)
 Enfin.. evite de tout casser, hein !

            @endif

@endsection

Update dashboard homepage because all volunteers can now see it


<?php

/*
 * Layout functions
 */

// `is_currentfile`
//
// Checks for current file. Returns boolean.
function is_currentfile($file) {
  if (preg_match("/$file$/", $_SERVER['PHP_SELF'])) {
    return true;
  }
}

// `filecount`
//
// Counts number of files in a directory. `$dir` must be without a trailing
// slash.
function filecount($dir) {
  $i = 0;
  foreach (glob($dir . '/*') as $file) {
    if (!is_dir($file)) {
      $i++;
    }
  }
  echo $i;
}

// `feedparse`
//
// Parses RSS or Atom feed.
// $pre => preformat feed contents or no, must be a boolean
function feedparse($url, $pre = false) {
  $feed = fopen($url, 'r');
  $data = stream_get_contents($feed);
  fclose($feed);
  if ($pre) {
    echo '<pre>';
  }
  echo $data;
  if ($pre) {
    echo '</pre>';
  }
}

// `selectrandom`
//
// Selects a random value from array.
function selectrandom($array) {
  echo $array[array_rand($array)];
}

// `undot`
//
// Removes dots from string.
function undot($string) {
  echo str_replace('.', '', $string);
}

<?php

/*
 * Layout functions
 */

// `is_currentfile`
//
// Checks for current file. Returns boolean.
function is_currentfile($file) {
  if (preg_match("/$file$/", $_SERVER['PHP_SELF'])) {
    return true;
  }
}

// `filecount`
//
// Counts number of files in a directory. `$dir` must be without a trailing
// slash.
function filecount($dir) {
  $i = 0;
  foreach (glob($dir . '/*') as $file) {
    if (!is_dir($file)) {
      $i++;
    }
  }
  echo $i;
}

// `feedparse`
//
// Parses RSS or Atom feed.
// $pre => preformat feed contents, must be a boolean
function feedparse($url, $pre = false) {
  $feed = fopen($url, 'r');
  $data = stream_get_contents($feed);
  fclose($feed);
  if ($pre) {
    echo '<pre>';
  }
  echo $data;
  if ($pre) {
    echo '</pre>';
  }
}

// `selectrandom`
//
// Selects a random value from array.
function selectrandom($array) {
  echo $array[array_rand($array)];
}

// `undot`
//
// Removes dots from string.
function undot($string) {
  echo str_replace('.', '', $string);
}

Clean up $pre parameter description

Clean up $pre parameter description


<?php
namespace ShadowTranslate\Test\TestCase\Model\Behavior;

use Cake\ORM\Entity;
use Cake\ORM\Behavior\Translate\TranslateTrait;

/**
 * Simulated baked entity class for a translated table
 *
 */
class BakedArticles extends Entity
{
    use TranslateTrait;

    protected $_accessible = [
        'title' => true,
        'body' => true
    ];
}

<?php
namespace ShadowTranslate\Test\TestCase\Model\Behavior;

use Cake\ORM\Behavior\Translate\TranslateTrait;
use Cake\ORM\Entity;

/**
 * Simulated baked entity class for a translated table
 *
 */
class BakedArticles extends Entity
{
    use TranslateTrait;

    protected $_accessible = [
        'title' => true,
        'body' => true
    ];
}

Put use statements in order

Put use statements in order


<?php

declare(strict_types = 1);

namespace ASN1\Type;

use ASN1\Component\Identifier;
use ASN1\Component\Length;
use ASN1\Exception\DecodeException;
use ASN1\Feature\ElementBase;

/**
 * Base class for primitive strings.
 */
abstract class PrimitiveString extends StringType
{
    use PrimitiveType;

    /**
     *
     * @see \ASN1\Element::_encodedContentDER()
     * @return string
     */
    protected function _encodedContentDER(): string
    {
        return $this->_string;
    }

    /**
     *
     * {@inheritdoc}
     * @see \ASN1\Element::_decodeFromDER()
     * @return self
     */
    protected static function _decodeFromDER(Identifier $identifier, string $data,
        int &$offset): ElementBase
    {
        $idx = $offset;
        if (!$identifier->isPrimitive()) {
            throw new DecodeException("DER encoded string must be primitive.");
        }
        $length = Length::expectFromDER($data, $idx)->intLength();
        $str = $length ? substr($data, $idx, $length) : "";
        // substr should never return false, since length is
        // checked by Length::expectFromDER.
        assert(is_string($str), "substr");
        $offset = $idx + $length;
        try {
            return new static($str);
        } catch (\InvalidArgumentException $e) {
            throw new DecodeException($e->getMessage(), 0, $e);
        }
    }
}

<?php

declare(strict_types = 1);

namespace ASN1\Type;

use ASN1\Component\Identifier;
use ASN1\Component\Length;
use ASN1\Exception\DecodeException;
use ASN1\Feature\ElementBase;

/**
 * Base class for primitive strings.
 */
abstract class PrimitiveString extends StringType
{
    use PrimitiveType;

    /**
     *
     * @see \ASN1\Element::_encodedContentDER()
     * @return string
     */
    protected function _encodedContentDER(): string
    {
        return $this->_string;
    }

    /**
     *
     * {@inheritdoc}
     * @see \ASN1\Element::_decodeFromDER()
     * @return self
     */
    protected static function _decodeFromDER(Identifier $identifier, string $data,
        int &$offset): ElementBase
    {
        $idx = $offset;
        if (!$identifier->isPrimitive()) {
            throw new DecodeException("DER encoded string must be primitive.");
        }
        $length = Length::expectFromDER($data, $idx)->intLength();
        $str = $length ? substr($data, $idx, $length) : "";
        // substr should never return false, since length is
        // checked by Length::expectFromDER.
        assert(is_string($str), new DecodeException("substr"));
        $offset = $idx + $length;
        try {
            return new static($str);
        } catch (\InvalidArgumentException $e) {
            throw new DecodeException($e->getMessage(), 0, $e);
        }
    }
}

Throw exception on assert failure

Throw exception on assert failure


<?php
namespace LazyRecord\Command;
use CLIFramework\Command;

class SchemaCommand extends Command
{

    function init()
    {
        parent::init();
        $this->registerCommand('build',    'LazyRecord\Command\BuildSchemaCommand');
        $this->registerCommand('sql',    'LazyRecord\Command\BuildSqlCommand');
        $this->registerCommand('list',    'LazyRecord\Command\ListSchemaCommand');
    }

    function execute() {

    }
}

<?php
namespace LazyRecord\Command;
use CLIFramework\Command;

class SchemaCommand extends Command
{

    function brief() { return 'schema command.'; }

    function init()
    {
        parent::init();
        $this->registerCommand('build',    'LazyRecord\Command\BuildSchemaCommand');
        $this->registerCommand('sql',    'LazyRecord\Command\BuildSqlCommand');
        $this->registerCommand('list',    'LazyRecord\Command\ListSchemaCommand');
    }

    function execute() {
        $this->logger->info('Usage: schema [build|sql|list]');
    }
}

Add brief and command usage

Add brief and command usage


<?php
require_once('../../lib/merchant.php');

require_once('initialize_gateway.php');

try {

  $response = $gateway->authenticate( array(
      'transaction_id' => $_SESSION['transaction_id'],
      'payload' => $_POST['PaRes']
    ));
  if ( $response->success() ) {
?>

        PAResStatus
        SignatureVerification
        EciFlag
        Xid
        Cavv
        ErrorNo
        ErrorDesc

        <?php echo $response->pares_status ?>
        <?php echo $response->signature_verification ?>
        <?php echo $response->eci_flag ?>
        <?php echo $response->xid ?>
        <?php echo $response->Cavv ?>
        <?php echo $response->ErrorNo ?>
        <td<?php echo $response->ErrorDesc ?>

<?php
  } else {
    echo "
{$response->message()}
";
  }

} catch (Exception $exc) {
  echo $exc->getMessage();
}
?>

Return to test page

<?php
require_once('../../lib/merchant.php');

require_once('initialize_gateway.php');

try {

  $response = $gateway->authenticate( array(
      'transaction_id' => $_SESSION['transaction_id'],
      'payload' => $_POST['PaRes']
    ));
  if ( $response->success() ) {
?>

        PAResStatus
        SignatureVerification
        TransactionId
        EciFlag
        Xid
        Cavv
        ErrorNo
        ErrorDesc

        <?php echo $response->pares_status ?>
        <?php echo $response->signature_verification ?>
        <?php echo $_SESSION['transaction_id'] ?>
        <?php echo $response->eci_flag ?>
        <?php echo $response->xid ?>
        <?php echo $response->cavv ?>
        <?php echo $response->error_no ?>
        <td<?php echo $response->error_desc ?>

<?php
  } else {
    echo "
{$response->message()}
";
  }

} catch (Exception $exc) {
  echo $exc->getMessage();
}
?>

Return to test page

Add TransactionId to responses. Fix error_no and error_desc variables


Change Access

<form class="form-horizontal">

    Select Access Type

      <?php
      $types = $dal->getAccessTypes();
      $selected_user = $_GET['for'];
      $curr = $dal->getUserAccessLevel($selected_user);
      $level_options = '';
      ?>
      <select id="access-type" name="access-type" class="form-control">
        <option disabled>Select Access Type</option>
        <?php
        foreach ($types as $row) {
          return '';
          //$level_options .= "<option value=".$row['id'].">".$row['type']."</option>";
        }
        echo $level_options;
        /*
        if ($types) {
          foreach ($types as $row) {
            $option = "<option value='".$row['type']."' ";
            if ($row['type'] == $curr) {
              $option .= "selected>$row['type']</option>";
            } else {
              $option .= ">$row['type']</option>";
            }
            echo $option;
          }
        }
        */
        ?>
      </select>

      <button id="submit" name="submit" class="btn btn-primary">Update</button>

</form>

Change Access

<form class="form-horizontal">

    Select Access Type

      <?php
      $types = $dal->getAccessTypes();
      $selected_user = $_GET['for'];
      $curr = $dal->getUserAccessLevel($selected_user);
      $level_options = '';
      ?>
      <select id="access-type" name="access-type" class="form-control">
        <option disabled>Select Access Type</option>
        <?php
        foreach ($types as $row) {
          $level_options .= '';
          //$level_options .= "<option value=".$row['id'].">".$row['type']."</option>";
        }
        echo $level_options;
        /*
        if ($types) {
          foreach ($types as $row) {
            $option = "<option value='".$row['type']."' ";
            if ($row['type'] == $curr) {
              $option .= "selected>$row['type']</option>";
            } else {
              $option .= ">$row['type']</option>";
            }
            echo $option;
          }
        }
        */
        ?>
      </select>

      <button id="submit" name="submit" class="btn btn-primary">Update</button>

</form>

Change that line to see if maybe that's the culprit


<?php

declare(strict_types=1);

namespace GraphQLTests\Doctrine\Blog\Model\Special;

use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use GraphQLTests\Doctrine\Blog\Model\AbstractModel;

/**
 * @ORM\Entity
 */
class NoTypeCollection extends AbstractModel
{
    public function getFoos(): Collection
    {
        return __FUNCTION__;
    }
}

<?php

declare(strict_types=1);

namespace GraphQLTests\Doctrine\Blog\Model\Special;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use GraphQLTests\Doctrine\Blog\Model\AbstractModel;

/**
 * @ORM\Entity
 */
class NoTypeCollection extends AbstractModel
{
    public function getFoos(): Collection
    {
        return new ArrayCollection();
    }
}

Return correct type during tests

Return correct type during tests


<?php
/**
 * An author who can be linked to several add-ons.
 */
class AddonAuthor extends DataObject
{

    public static $db = array(
        'Name' => 'Varchar(255)',
        'Email' => 'Varchar(255)',
        'Homepage' => 'Varchar(255)',
        'Role' => 'Varchar(255)'
    );

    public static $belongs_many_many = array(
        'Versions' => 'AddonVersion'
    );

    public static $default_sort = 'Name';

    public function GravatarUrl($size, $default = 'mm')
    {
        return sprintf(
            'http://www.gravatar.com/avatar/%s?s=%d&d=%s',
            md5(strtolower(trim($this->Email))),
            $size,
            $default
        );
    }

    public function Link()
    {
        return Controller::join_links(Director::baseURL(), 'authors', $this->ID);
    }

    public function Addons()
    {
        return Addon::get()->filter('ID', $this->Versions()->column('AddonID'));
    }
}

<?php
/**
 * An author who can be linked to several add-ons.
 */
class AddonAuthor extends DataObject
{

    public static $db = array(
        'Name' => 'Varchar(255)',
        'Email' => 'Varchar(255)',
        'Homepage' => 'Varchar(255)',
        'Role' => 'Varchar(255)'
    );

    public static $belongs_many_many = array(
        'Versions' => 'AddonVersion'
    );

    public static $default_sort = 'Name';

    public function GravatarUrl($size, $default = 'mm')
    {
        return sprintf(
            'https://www.gravatar.com/avatar/%s?s=%d&d=%s',
            md5(strtolower(trim($this->Email))),
            $size,
            $default
        );
    }

    public function Link()
    {
        return Controller::join_links(Director::baseURL(), 'authors', $this->ID);
    }

    public function Addons()
    {
        return Addon::get()->filter('ID', $this->Versions()->column('AddonID'));
    }
}

FIX Use HTTPS protocol in Gravatar URL

FIX Use HTTPS protocol in Gravatar URL


<?php

namespace SlightScribeBundle\Task;

use SlightScribeBundle\Entity\Communication;
use SlightScribeBundle\Entity\RunHasCommunication;

/**
 *  @license 3-clause BSD https://github.com/SlightScribe/SlightScribe-Core/blob/master/LICENSE.md
 *  @link https://github.com/SlightScribe/SlightScribe-Core
 */
class IsFurtherCommunicationReadyToSendTask {

    /** @var  \DateTime */
    protected $now;

    /**
     * IsFurtherCommunicationReadyToSendTask constructor.
     * @param \DateTime $now
     */
    public function __construct(\DateTime $now)
    {
        $this->now = $now;
    }

    public function go(Communication $nextCommunication, RunHasCommunication $lastRunCommunication) {

        $secondsDifference = abs($this->now->getTimestamp() - $lastRunCommunication->getSentAt()->getTimestamp());

        return $secondsDifference / (60*60*24) > $nextCommunication->getDaysBefore();

    }

}

<?php

namespace SlightScribeBundle\Task;

use SlightScribeBundle\Entity\Communication;
use SlightScribeBundle\Entity\RunHasCommunication;

/**
 *  @license 3-clause BSD https://github.com/SlightScribe/SlightScribe-Core/blob/master/LICENSE.md
 *  @link https://github.com/SlightScribe/SlightScribe-Core
 */
class IsFurtherCommunicationReadyToSendTask {

    /** @var  \DateTime */
    protected $now;

    /**
     * IsFurtherCommunicationReadyToSendTask constructor.
     * @param \DateTime $now
     */
    public function __construct(\DateTime $now)
    {
        $this->now = $now;
    }

    public function go(Communication $nextCommunication, RunHasCommunication $lastRunCommunication) {

        // This should never really be needed - if the lastRunCommunication wasn't actually sent, something in the caller should catch it.
        // Have this as a final catch.
        if (is_null($lastRunCommunication->getSentAt())) {
            return false;
        }

        $secondsDifference = abs($this->now->getTimestamp() - $lastRunCommunication->getSentAt()->getTimestamp());

        return $secondsDifference / (60*60*24) > $nextCommunication->getDaysBefore();

    }

}

Add code to make more robust.

Add code to make more robust.


<?php

namespace Ddeboer\Imap;

/**
 * A connection to an IMAP server that is authenticated for a user
 */
class Connection
{
    protected $server;
    protected $resource;
    protected $mailboxes;

    public function __construct($resource, $server)
    {
        if (!is_resource($resource)) {
            throw new \InvalidArgumentException('$resource must be a resource');
        }

        $this->resource = $resource;
        $this->server = $server;
    }

    /**
     * Get a list of mailboxes
     *
     * @return array
     */
    public function getMailboxes()
    {
        if (null === $this->mailboxes) {
            $mailboxes = \imap_getmailboxes($this->resource, $this->server, '*');
            foreach ($mailboxes as $mailbox) {
                $this->mailboxes[] = str_replace($this->server, '', $mailbox->name);
            }
        }

        return $this->mailboxes;
    }

    public function getMailbox($name)
    {
        foreach ($this->getMailboxes() as $mailbox) {
            if ($name === $mailbox) {
                if (false === \imap_reopen($this->resource, $this->server . $mailbox)) {
                    throw new \Exception('Could not open mailbox ' . $mailbox);
                }

                return new Mailbox($mailbox, $this->resource);
            }
        }

        throw new \InvalidArgumentException('Mailbox ' . $name . ' not found');
    }

    public function count()
    {
        return \imap_num_msg($this->resource);
    }
}

<?php

namespace Ddeboer\Imap;

/**
 * A connection to an IMAP server that is authenticated for a user
 */
class Connection
{
    protected $server;
    protected $resource;
    protected $mailboxes;

    public function __construct($resource, $server)
    {
        if (!is_resource($resource)) {
            throw new \InvalidArgumentException('$resource must be a resource');
        }

        $this->resource = $resource;
        $this->server = $server;
    }

    /**
     * Get a list of mailboxes
     *
     * @return array
     */
    public function getMailboxes()
    {
        if (null === $this->mailboxes) {
            $mailboxes = \imap_getmailboxes($this->resource, $this->server, '*');
            foreach ($mailboxes as $mailbox) {
                $this->mailboxes[] = str_replace($this->server, '', $mailbox->name);
            }
        }

        return $this->mailboxes;
    }

    public function getMailbox($name)
    {
        foreach ($this->getMailboxes() as $mailbox) {
            if (strcasecmp($name, $mailbox) === 0) {
                if (false === \imap_reopen($this->resource, $this->server . $mailbox)) {
                    throw new \Exception('Could not open mailbox ' . $mailbox);
                }

                return new Mailbox($mailbox, $this->resource);
            }
        }

        throw new \InvalidArgumentException('Mailbox ' . $name . ' not found');
    }

    public function count()
    {
        return \imap_num_msg($this->resource);
    }
}

Make getting mailbox case insensitive

Make getting mailbox case insensitive