<?php

declare(strict_types=1);

namespace Doctrine\Bundle\MongoDBBundle\Tests\DataCollector;

use Doctrine\Bundle\MongoDBBundle\DataCollector\CommandDataCollector;
use Doctrine\Bundle\MongoDBBundle\Tests\TestCase;
use Doctrine\ODM\MongoDB\APM\CommandLogger;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class CommandDataCollectorTest extends TestCase
{
    public function testCollector(): void
    {
        $collector = new CommandDataCollector(new CommandLogger());

        $collector->collect($request = new Request(['group' => '0']), $response = new Response());
    }
}

<?php

declare(strict_types=1);

namespace Doctrine\Bundle\MongoDBBundle\Tests\DataCollector;

use Doctrine\Bundle\MongoDBBundle\DataCollector\CommandDataCollector;
use Doctrine\Bundle\MongoDBBundle\Tests\TestCase;
use Doctrine\ODM\MongoDB\APM\CommandLogger;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class CommandDataCollectorTest extends TestCase
{
    /**
     * @doesNotPerformAssertions
     */
    public function testCollector(): void
    {
        $collector = new CommandDataCollector(new CommandLogger());

        $collector->collect($request = new Request(['group' => '0']), $response = new Response());
    }
}

Mark test not performing assertions as such

It is considered risky not to perform assertions.


Add more assertions for Favicon

Add more assertions for Favicon


<?php echo Asset::css('site.css');?>
<?php
$module_assets_css = conf('assets.css.modules');
foreach ($module_assets_css as $module => $files)
{
	if ($module == 'admin') continue;
	foreach ($files as $file) echo Asset::css(sprintf('modules/%s/%s', $module, $file));
}
?>

<?php echo Asset::css('site.css');?>
<?php
$module_assets_css = conf('assets.css.modules', null, array());
foreach ($module_assets_css as $module => $files)
{
	if ($module == 'admin') continue;
	foreach ($files as $file) echo Asset::css(sprintf('modules/%s/%s', $module, $file));
}
?>

Improve error to load module assets.

Improve error to load module assets.


<?php

namespace Drupal\wmcontent\EventSubscriber;

use Drupal\Core\Entity\EntityInterface;
use Drupal\wmcontent\Event\ContentBlockChangedEvent;
use Drupal\wmcontent\WmContentManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ContentBlockSubscriber implements EventSubscriberInterface
{
    /** @var WmContentManager */
    private $manager;

    private $updatedHosts = [];

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

    public static function getSubscribedEvents()
    {
        $events[ContentBlockChangedEvent::NAME][] = ['updateHostEntity'];
        return $events;
    }

    /**
     * Trigger an update of the contentblock's host entity
     */
    public function updateHostEntity(ContentBlockChangedEvent $event)
    {
        $host = $this->manager->getHost($event->getContentBlock());

        if (!$host instanceof EntityInterface) {
            return;
        }

        $cid = sprintf('%s:%s', $host->getEntityTypeId(), $host->id());

        if (array_key_exists($cid, $this->updatedHosts)) {
            return;
        }

        $host->save();
        $this->updatedHosts[$cid] = true;
    }
}

<?php

namespace Drupal\wmcontent\EventSubscriber;

use Drupal\Core\Entity\EntityInterface;
use Drupal\wmcontent\Event\ContentBlockChangedEvent;
use Drupal\wmcontent\WmContentManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ContentBlockSubscriber implements EventSubscriberInterface
{
    /** @var WmContentManager */
    private $manager;

    private $updatedHosts = [];

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

    public static function getSubscribedEvents()
    {
        $events[ContentBlockChangedEvent::NAME][] = ['updateHostEntity'];
        return $events;
    }

    /**
     * Trigger an update of the contentblock's host entity
     */
    public function updateHostEntity(ContentBlockChangedEvent $event)
    {
        $host = $this->manager->getHost($event->getContentBlock());

        if (!$host instanceof EntityInterface) {
            return;
        }

        $cid = sprintf('%s:%s', $host->getEntityTypeId(), $host->id());

        if (array_key_exists($cid, $this->updatedHosts)) {
            return;
        }

        $host->set('changed', time());
        $host->save();
        $this->updatedHosts[$cid] = true;
    }
}

Update host changed time on content block save


<?php

namespace NodeRED\Test;

use GuzzleHttp\Psr7\Response;
use NodeRED\OAuth;
use NodeRED\OAuthToken;

class OAuthTest extends \PHPUnit_Framework_TestCase
{
    const MOCK_URL = 'https://MOCK/';

    public function testGetToken()
    {
        $successJson = '{"access_token": "A_SECRET_TOKEN","expires_in":604800,"token_type": "Bearer"}';
        $response = new Response(200, ['Content-Type' => 'application/json'], $successJson);

        $instance = InstanceFactory::getMock([$response]);

        $oAuth = new OAuth($instance);

        $token = $oAuth->getToken($username, $password);

        $this->assertInstanceOf(OAuthToken::class, $token);
    }
}

<?php

namespace NodeRED\Test;

use GuzzleHttp\Psr7\Response;
use NodeRED\OAuth;
use NodeRED\OAuthToken;

class OAuthTest extends \PHPUnit_Framework_TestCase
{
    const MOCK_URL = 'https://MOCK/';

    public function testGetToken()
    {
        $successJson = '{"access_token": "A_SECRET_TOKEN","expires_in":604800,"token_type": "Bearer"}';
        $response = new Response(200, ['Content-Type' => 'application/json'], $successJson);

        $instance = InstanceFactory::getMock([$response]);

        $oAuth = new OAuth($instance);

        $token = $oAuth->getToken('foo', 'bar');

        $this->assertInstanceOf(OAuthToken::class, $token);
    }
}

Test fix - variable not defined

Test fix - variable not defined


<?php
// (c) Copyright 2002-2010 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
  header("location: index.php");
  exit;
}

function module_svnup_info()
{
	return array(
		'name' => tra('SVN up info'),
		'description' => tra('SVN Version and last update information.'),
		'params' => array(),
	);
}

function module_svnup($mod_reference, $module_params)
{

}

<?php
// (c) Copyright 2002-2010 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
  header("location: index.php");
  exit;
}

function module_svnup_info()
{
	return array(
		'name' => tra('SVN Up Info'),
		'description' => tra('SVN Version and last update information.'),
		'params' => array(),
	);
}

function module_svnup($mod_reference, $module_params)
{

}

Tidy up info a little for the PluginModule popup edit form

git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@40400 b456876b-0849-0410-b77d-98878d47e9d5


<?php
/**
 * This file is part of the BootstrapBundle project.
 *
 * (c) 2013 Philipp Boes <mostgreedy@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace P2\Bundle\BootstrapBundle\Form\Extension;

use P2\Bundle\BootstrapBundle\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * Class FormTypeExtension
 * @package P2\Bundle\BootstrapBundle\Form\Extension
 */
class FormTypeExtension extends AbstractTypeExtension
{
    /**
     * {@inheritDoc}
     */
    public function getExtendedType()
    {
        return 'form';
    }
}

<?php
/**
 * This file is part of the BootstrapBundle project.
 *
 * (c) 2013 Philipp Boes <mostgreedy@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace P2\Bundle\BootstrapBundle\Form\Extension;

use P2\Bundle\BootstrapBundle\Form\AbstractTypeExtension;

/**
 * Class FormTypeExtension
 * @package P2\Bundle\BootstrapBundle\Form\Extension
 */
class FormTypeExtension extends AbstractTypeExtension
{
    /**
     * {@inheritDoc}
     */
    public function getExtendedType()
    {
        return 'form';
    }
}

Remove deprecated code from form type extension


<?php

/**
 * Define client request optional configurations
 */
class KalturaRequestConfiguration
{
	/**
	 * Impersonated partner id
	 * @var int
	 */
	public $partnerId;

	/**
	 * Kaltura API session
	 * @alias session
	 * @var string
	 */
	public $ks;

	/**
	 * Response profile
	 * @alias responseProfile
	 * @var KalturaNestedResponseProfileBase
	 */
	public $rp;
}

<?php

/**
 * Define client request optional configurations
 */
class KalturaRequestConfiguration
{
	/**
	 * Impersonated partner id
	 * @var int
	 */
	public $partnerId;

	/**
	 * Kaltura API session
	 * @alias session
	 * @var string
	 */
	public $ks;

	/**
	 * Response profile
	 * @var KalturaNestedResponseProfileBase
	 */
	public $responseProfile;
}

Use responseProfile as argument name

Use responseProfile as argument name


<?php
class logger
{
    private $logfile = null;

    private static $instance = null;

    public static function getInstance()
    {
        if (self::$instance == null) {
            self::$instance = new logger();
        }
        return self::$instance;
    }

    private function __construct()
    {
    }

    public function setLogfile($logfile)
    {
        $this->logfile = $logfile;
    }

    public function log($level, $message)
    {
        $msg = $level." : ".$message."\n";
        $type = 3;
        if ($logfile == null) {
            $type = 0;
        }
        error_log($message, $type, $this->logfile);
    }
}

<?php
/**
 * Logger class to register the logger for
 * to give a central logging with callback
 * registration in the php_rsync extension.
 *
 * @author ironpinguin
 *
 */
class logger
{
    /**
     * Log file.
     *
     * @var string
     */
    private $logfile = null;

    /**
     * Instance variable for the logger singelton.
     *
     * @var logger
     */
    private static $instance = null;

    /**
     * Static method to get the instance of the
     * logger singelton.
     *
     * @return logger
     */
    public static function getInstance()
    {
        if (self::$instance == null) {
            self::$instance = new logger();
        }
        return self::$instance;
    }

    /**
     * Empty Constructor....
     *
     */
    private function __construct()
    {
    }

    /**
     * Setter for the logfile.
     *
     * @param string $logfile String with the logfile incl. path.
     */
    public function setLogfile($logfile)
    {
        $this->logfile = $logfile;
    }

    /**
     * Logging method where will be register as callback in the
     * php_rsync extension.
     *
     * @param int    $level   Logging level.
     * @param string $message Logging message.
     */
    public function log($level, $message)
    {
        $msg = $level." : ".$message."\n";
        $type = 3;
        if ($logfile == null) {
            $type = 0;
        }
        error_log($message, $type, $this->logfile);
    }
}

Add doc comment to the class.

Add doc comment to the class.


<?php
include('include/config.ini.php');
$plugins = $file_db->prepare("SELECT id_plugin, file, public1, public2, public3, int1, int2, int3, txt1, txt2, txt3 FROM plugins ORDER BY id_plugin ASC");
$plugins->execute() or die("Unable to lookup plugins");
$plugins = $plugins->fetchAll(PDO::FETCH_ASSOC);
foreach ($plugins as $settings) {
    //Technes : 431789
  include('plugins/'.$settings["file"].'.php');
  echo("$settings[file] executé");
}
die();
//Google Calendar
?>

<?php
include('include/config.ini.php');
$plugins = $file_db->prepare("SELECT id_plugin, file, public1, public2, public3, int1, int2, int3, txt1, txt2, txt3 FROM plugins ORDER BY id_plugin ASC");
$plugins->execute() or die("Unable to lookup plugins");
$plugins = $plugins->fetchAll(PDO::FETCH_ASSOC);
foreach ($plugins as $settings) {
    //Technes : 431789
  include('plugins/'.$settings["file"].'.php');
  echo("$settings[file] executé");
}
die();
//Google Calendars
?>

Add new line in customCSS

Add new line in customCSS


<?php

include(LIB_PATH . '/Favicon/Favicon.php');
include(LIB_PATH . '/Favicon/DataAccess.php');

$favicons_dir = DATA_PATH . '/favicons/';
$default_favicon = PUBLIC_PATH . '/themes/icons/default_favicon.ico';

function download_favicon($website, $dest) {
	global $favicons_dir, $default_favicon;

	syslog(LOG_INFO, 'FreshRSS Favicon discovery GET ' . $website);
	$favicon_getter = new \Favicon\Favicon();
	$favicon_getter->setCacheDir($favicons_dir);
	$favicon_url = $favicon_getter->get($website);

	if ($favicon_url === false) {
		return @copy($default_favicon, $dest);
	}

	syslog(LOG_INFO, 'FreshRSS Favicon GET ' . $favicon_url);
	$c = curl_init($favicon_url);
	curl_setopt($c, CURLOPT_HEADER, false);
	curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($c, CURLOPT_BINARYTRANSFER, true);
	curl_setopt($c, CURLOPT_USERAGENT, 'FreshRSS/' . FRESHRSS_VERSION . ' (' . PHP_OS . '; ' . FRESHRSS_WEBSITE . ')');
	$img_raw = curl_exec($c);
	$status_code = curl_getinfo($c, CURLINFO_HTTP_CODE);
	curl_close($c);

	if ($status_code === 200) {
		$file = fopen($dest, 'w');
		if ($file !== false) {
			fwrite($file, $img_raw);
			fclose($file);
			return true;
		}
	} else {
		syslog(LOG_WARNING, 'FreshRSS Favicon GET ' . $favicon_url . ' error ' . $status_code);
	}

	return false;
}

<?php

include(LIB_PATH . '/Favicon/FaviconDLType.php');
include(LIB_PATH . '/Favicon/DataAccess.php');
include(LIB_PATH . '/Favicon/Favicon.php');

$favicons_dir = DATA_PATH . '/favicons/';
$default_favicon = PUBLIC_PATH . '/themes/icons/default_favicon.ico';

function download_favicon($website, $dest) {
	global $default_favicon;

	syslog(LOG_INFO, 'FreshRSS Favicon discovery GET ' . $website);
	$favicon_getter = new \Favicon\Favicon();
	$tmpPath = realpath(TMP_PATH) . '/';
	$favicon_getter->setCacheDir($tmpPath);
	$favicon_path = $favicon_getter->get($website, \Favicon\FaviconDLType::DL_FILE_PATH);

	return ($favicon_path != false && @rename($tmpPath . $favicon_path, $dest)) ||
		@copy($default_favicon, $dest);
}

Use new version 1.2 of Favicon library

Use new version 1.2 of Favicon library


<?php
/**
* Defines the SupportingProjectPage page type - initial code created by ss generator
*/
class PageWithImage extends Page implements RenderableAsPortlet {

  static $has_one = array(
    'MainImage' => 'Image'
  );

  // for rendering thumbnail when linked in facebook
  function getOGImage() {
        return $this->MainImage();
    }

  function getCMSFields() {
    $fields = parent::getCMSFields();
    $fields->addFieldToTab( 'Root.Image', $uf = new UploadField('MainImage'));
    $dirname = strtolower($this->ClassName).'s';
    $uf->setFolderName($dirname);
    return $fields;
  }

  public function getPortletTitle() {
    return $this->Title;
  }

  // FIXME - make this more efficient
  public function getPortletImage() {
    $result = '';
    if ($this->MainImageID) {
      $result = DataObject::get_by_id('Image', $this->MainImageID);
    }
    return $result;
  }

  public function getPortletCaption() {
    return '';
  }

}

class PageWithImage_Controller extends Page_Controller {

}

 <?php
/**
* Defines the SupportingProjectPage page type - initial code created by ss generator
*/
class PageWithImage extends Page implements RenderableAsPortlet {

  static $has_one = array(
    'MainImage' => 'Image'
  );

  // for rendering thumbnail when linked in facebook
  function getOGImage() {
        return $this->MainImage();
    }

  function getCMSFields() {
    $fields = parent::getCMSFields();
    $fields->addFieldToTab( 'Root.Image', $uf = new UploadField('MainImage'));
    $dirname = strtolower($this->ClassName).'s';
    $uf->setFolderName($dirname);
    return $fields;
  }

  public function getPortletTitle() {
    return $this->Title;
  }

  // FIXME - make this more efficient
  public function getPortletImage() {
    $result = null;
    if ($this->MainImageId) {
      $result = DataObject::get_by_id('Image', $this->MainImageID);
    }

    return $result;
  }

  public function getPortletCaption() {
    return '';
  }

}

class PageWithImage_Controller extends Page_Controller {

}

FIX: Remove accidentally introduced '23' at the start of the file


<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class FileuploaderController extends Controller
{

    public function upload()
    {
            $input = Input::all();
            $error = '';

            $callback = Input::get('CKEditorFuncNum');

            $rules = array(
                'upload' => 'image|max:15000|required',
            );

            $validation = Validator::make($input, $rules);

            if ($validation->fails()) {
                return response($validation->messages(), 400);
            }

            $file = Input::file('upload');
            $extension = $file->getClientOriginalExtension();
            $filename = md5(date("YmdHis").rand(5, 50)) . "." . $extension;
            $destinationPath = '/images/uploaded/';
            $file->move(public_path() . $destinationPath, $filename);
            $http_path = $destinationPath . $filename;
            // return '<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$callback.',  "'.$http_path.'", "'.$error.'" );</script>';
            return [
                "uploaded" =>  1,
                "fileName" =>  $filename,
                "url" =>  $http_path,
            ];
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class FileuploaderController extends Controller
{

    public function upload()
    {
            $input = Input::all();
            $error = '';

            $callback = Input::get('CKEditorFuncNum');

            $rules = array(
                'upload' => 'image|max:15000|required',
            );

            $validation = Validator::make($input, $rules);

            if ($validation->fails()) {
                return response($validation->messages(), 400);
            }

            $file = Input::file('upload');
            $extension = $file->getClientOriginalExtension();
            $filename = md5(date("YmdHis").rand(5, 50)) . "." . $extension;
            $destinationPath = '/storage/images/uploaded/';
            $file->move(public_path() . $destinationPath, $filename);
            $http_path = $destinationPath . $filename;
            // return '<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction('.$callback.',  "'.$http_path.'", "'.$error.'" );</script>';
            return [
                "uploaded" =>  1,
                "fileName" =>  $filename,
                "url" =>  $http_path,
            ];
    }
}

Store uploaded images in public/storage/images/uploaded


<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / App / Include / Class
 */

namespace PH7;

class DbTableName
{
    const ADMIN = 'admins';
    const MEMBERSHIP = 'memberships';
}

<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / App / Include / Class
 */

namespace PH7;

class DbTableName
{
    const ADMIN = 'admins';
    const MEMBER = 'members';
    const MEMBERSHIP = 'memberships';
    const AFFILIATE = 'affiliates';
    const SUBSCRIBER = 'subscribers';
    const MEMBER_INFO = 'members_info';
    const AFFILIATE_INFO = 'affiliates_info';

}

Add new db table name constants

Add new db table name constants


<!DOCTYPE html>
<?php
  define('BASE_DIR', dirname(__FILE__));
  require_once(BASE_DIR.'/config.php');
?>

    <title><?php echo CAM_STRING; ?></title>

Make img tag compliant to the standard html


<?php

function modal ($id, $title, $body, $data) {
    $html = '

                        <button aria-hidden="true" class="close" data-dismiss="modal" type="button">×</button>

' . $title .'

' . $body .'

                          Cancel
                          Confirm

';
    echo $html;
};

Add case param in accept/reject urls.

Add case param in accept/reject urls.


<?php

/**
 * @copyright 2017 Vladimir Jimenez
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
 */

namespace allejo\stakx\Document;

interface TwigDocumentInterface
{
    /**
     * @param string $filePath
     * @return void
     */
    public function __construct($filePath);

    /**
     * @return string
     */
    public function getNamespace();

    /**
     * @param string $namespace
     *
     * @return void
     */
    public function setNamespace($namespace);

    /**
     * @param PageView $pageView
     *
     * @return void
     */
    public function setPageView(&$pageView);

    /**
     * @return string
     */
    public function getRelativeFilePath();

    /**
     * @return string
     */
    public function getExtension();

    /**
     * @return string
     */
    public function getFilePath();

    /**
     * @return string
     */
    public function getName();

    /**
     * @return bool
     */
    public function isDraft();

    /**
     * Read the contents of a file.
     *
     * This function is responsible for reading the file and doing whatever is needed to parse & save the contents into
     * the given object.
     *
     * @return void
     */
    public function refreshFileContent();
}

<?php

/**
 * @copyright 2017 Vladimir Jimenez
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
 */

namespace allejo\stakx\Document;

interface TwigDocumentInterface
{
    /**
     * @param string $filePath
     */
    public function __construct($filePath);

    /**
     * @return string
     */
    public function getNamespace();

    /**
     * @param string $namespace
     *
     * @return void
     */
    public function setNamespace($namespace);

    /**
     * @param PageView $pageView
     *
     * @return void
     */
    public function setPageView(&$pageView);

    /**
     * @return string
     */
    public function getRelativeFilePath();

    /**
     * @return string
     */
    public function getExtension();

    /**
     * @return string
     */
    public function getFilePath();

    /**
     * @return string
     */
    public function getName();

    /**
     * @return bool
     */
    public function isDraft();

    /**
     * Read the contents of a file.
     *
     * This function is responsible for reading the file and doing whatever is needed to parse & save the contents into
     * the given object.
     *
     * @return void
     */
    public function refreshFileContent();
}

Remove unused phpdoc @return for a constructor

[ci skip]


<?php
/**
 * Skeleton Test class file for Suhosin group
 *
 * @package PhpSecInfo
 * @author Anthon Pang
 */

/**
 * require the main PhpSecInfo class
 */
require_once(PHPSECINFO_BASE_DIR.'/Test/Test.php');

/**
 * This is a skeleton class for PhpSecInfo "Suhosin" tests
 * @package PhpSecInfo
 */
class PhpSecInfo_Test_Suhosin extends PhpSecInfo_Test
{

	/**
	 * This value is used to group test results together.
	 *
	 * For example, all tests related to the mysql lib should be grouped under "mysql."
	 *
	 * @var string
	 */
	var $test_group = 'Suhosin';

	/**
	 * "Suhosin" tests should pretty much be always testable, so the default is just to return true
	 *
	 * @return boolean
	 */
	function isTestable() {

		return true;
	}

	function getMoreInfoURL() {
		if ($tn = $this->getTestName()) {
			return 'http://www.hardened-php.net/suhosin/index.html';
		} else {
			return false;
		}
	}
}

<?php
/**
 * Skeleton Test class file for Suhosin group
 *
 * @package PhpSecInfo
 * @author Anthon Pang
 */

/**
 * require the main PhpSecInfo class
 */
require_once(PHPSECINFO_BASE_DIR.'/Test/Test.php');

/**
 * This is a skeleton class for PhpSecInfo "Suhosin" tests
 * @package PhpSecInfo
 */
class PhpSecInfo_Test_Suhosin extends PhpSecInfo_Test
{

	/**
	 * This value is used to group test results together.
	 *
	 * For example, all tests related to the mysql lib should be grouped under "mysql."
	 *
	 * @var string
	 */
	var $test_group = 'Suhosin';

	/**
	 * "Suhosin" tests should pretty much be always testable, so the default is just to return true
	 *
	 * @return boolean
	 */
	function isTestable() {
		if (version_compare(PHP_VERSION, '5.3.9') >= 0) {
			return false;
		}
		return true;
	}

	function getMoreInfoURL() {
		if ($tn = $this->getTestName()) {
			return 'http://www.hardened-php.net/suhosin/index.html';
		} else {
			return false;
		}
	}
}

Disable Suhosin test for PHP > 5.3.9. Suhosin project is inactive right now and the latest release is for 5.3.9.


<?php
namespace Zf2FileUploader\Resource\Persister\Image;

use Zend\Filter\File\Rename;
use Zf2FileUploader\Options\ImageResourceOptionsInterface;
use Zf2FileUploader\Resource\ImageResourceInterface;
use Zf2FileUploader\Resource\Persister\AbstractFilesystemPersister;
use Zf2FileUploader\Resource\Persister\ImagePersisterInterface;

class FilesystemPersister extends AbstractFilesystemPersister implements ImagePersisterInterface
{
    /**
     * @var ImageResourceOptionsInterface
     */
    protected $options;

    /**
     * @var \Callable
     */
    protected $revertClb = null;

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

    /**
     * @param ImageResourceInterface $resource
     * @return boolean
     */
    public function persist(ImageResourceInterface $resource)
    {
        $ext = $resource->getExt();
        $baseName = uniqid().($ext ? '.'.$ext : '');
        $target = realpath($this->options->getImagePersistentPath()).'/'.$baseName;

        $moveUploadedFilter = new Rename(array(
            'target'               => $target,
            'overwrite'            => false,
            'randomize'            => false,
        ));

        $moveUploadedFilter->filter($resource->getPath());

        $resource->setPath($target);
        $resource->setHttpPath($this->options->getImageHttpPath().'/'.$baseName);

        $this->setCallbacks(null, function () use ($target) {
            if (file_exists($target)) {
                unlink($target);
            }
        });

        return file_exists($target);
    }
}

<?php
namespace Zf2FileUploader\Resource\Persister\Image;

use Zend\Filter\File\Rename;
use Zf2FileUploader\Options\ImageResourceOptionsInterface;
use Zf2FileUploader\Resource\ImageResourceInterface;
use Zf2FileUploader\Resource\Persister\AbstractFilesystemPersister;
use Zf2FileUploader\Resource\Persister\ImagePersisterInterface;

class FilesystemPersister extends AbstractFilesystemPersister implements ImagePersisterInterface
{
    /**
     * @var ImageResourceOptionsInterface
     */
    protected $options;

    /**
     * @var \Callable
     */
    protected $revertClb = null;

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

    /**
     * @param ImageResourceInterface $resource
     * @return boolean
     */
    public function persist(ImageResourceInterface $resource)
    {
        $ext = $resource->getExt();
        $baseName = $resource->getToken().($ext ? '.'.$ext : '');
        $target = realpath($this->options->getImagePersistentPath()).'/'.$baseName;

        $moveUploadedFilter = new Rename(array(
            'target'               => $target,
            'overwrite'            => false,
            'randomize'            => false,
        ));

        $moveUploadedFilter->filter($resource->getPath());

        $resource->setPath($target);
        $resource->setHttpPath($this->options->getImageHttpPath().'/'.$baseName);

        $this->setCallbacks(null, function () use ($target) {
            if (file_exists($target)) {
                unlink($target);
            }
        });

        return file_exists($target);
    }
}

Change name of file on the filesystem.

Change name of file on the filesystem.


<?php

/**
 * Factory class for providing Localization implementations
 * @author M2Mobi, Heinz Wiesinger
 */
class L10nFactory
{

    /**
     * Instance of the L10nProvider
     * @var array
     */
    private static $lprovider;

    /**
     * Constructor
     */
    public function __construct()
    {

    }

    /**
     * Destructor
     */
    public function __destruct()
    {

    }

    /**
     * This method returns an object with the appropriate localization
     * implementation provider
     * @param String $provider The localization implementation requested
     * @param String $language POSIX locale definition
     * @return L10nProvider $return Instance of the localization provider requested
     */
    public static function get_localization($provider, $language)
    {
        switch($provider)
        {
            case "php":
                if (!isset(self::$lprovider[$provider]))
                {
                    require_once("class.l10nproviderphp.inc.php");
                    self::$lprovider[$provider] = new L10nProviderPHP($language);
                }

                return self::$lprovider[$provider];
                break;
            case "gettext":
            default:
                if (!isset(self::$lprovider[$provider]))
                {
                    require_once("class.l10nprovidergettext.inc.php");
                    self::$lprovider[$provider] = new L10nProviderGettext($language);
                }

                return self::$lprovider[$provider];
                break;
        }
    }
}

?>

<?php

/**
 * Factory class for providing Localization implementations
 * @author M2Mobi, Heinz Wiesinger
 */
class L10nFactory
{

    /**
     * Instance of the L10nProvider
     * @var array
     */
    private static $lprovider;

    /**
     * Constructor
     */
    public function __construct()
    {

    }

    /**
     * Destructor
     */
    public function __destruct()
    {

    }

    /**
     * This method returns an object with the appropriate localization
     * implementation provider
     * @param String $provider The localization implementation requested
     * @param String $language POSIX locale definition
     * @return L10nProvider $return Instance of the localization provider requested
     */
    public static function get_localization($provider, $language)
    {
        require_once("class.l10nprovider.inc.php");
        switch($provider)
        {
            case "php":
                if (!isset(self::$lprovider[$provider]))
                {
                    require_once("class.l10nproviderphp.inc.php");
                    self::$lprovider[$provider] = new L10nProviderPHP($language);
                }

                return self::$lprovider[$provider];
                break;
            case "gettext":
            default:
                if (!isset(self::$lprovider[$provider]))
                {
                    require_once("class.l10nprovidergettext.inc.php");
                    self::$lprovider[$provider] = new L10nProviderGettext($language);
                }

                return self::$lprovider[$provider];
                break;
        }
    }
}

?>

system: Add require statement for the abstract L10nProvider


@php
    $moduleHeading = (!$hideTitle && !empty($postTitle)) ?
        ''. $postTitle.'
' : '';
@endphp

@notice([
    'type' => $notice_type,
    'message' => [
        'text' => $moduleHeading . $notice_text,
        'size' => $notice_size
    ],
    'icon' => $icon,
    'context' => ['notice', 'module.notice']
])
@endnotice

@notice([
    'type' => $notice_type,
    'message' => [
        'title' => !$hideTitle && !empty($postTitle) ? $postTitle : null,
        'text' => $moduleHeading . $notice_text,
        'size' => $notice_size
    ],
    'icon' => $icon,
    'context' => ['notice', 'module.notice']
])
@endnotice

Use new title parameter from notice component

woops


<?php
declare(strict_types = 1);

namespace app;

use ErrorException;
use Throwable;

/**
 * Include base source files and extensions
 */
foreach (glob(__DIR__ . '/src/*.php') as $file) {
    include_once $file;
}

foreach (glob(path('ext', 'src/*.php')) as $file) {
    include_once $file;
}

/**
 * Register error and exception handlers
 */
set_error_handler(
    function (int $severity, string $msg, string $file, int $line): void {
        log(new ErrorException($msg, 0, $severity, $file, $line));
    }
);
set_exception_handler(
    function (Throwable $e): void {
        log($e);
    }
);

/**
 * Run application
 */
run();

/**
 * Render response
 */
echo §('root');

<?php
declare(strict_types = 1);

namespace app;

use ErrorException;
use Throwable;

/**
 * Include base source files and extensions
 */
foreach (glob(dirname(__DIR__) . '/src/*.php') as $file) {
    include_once $file;
}

foreach (glob(path('ext', 'src/*.php')) as $file) {
    include_once $file;
}

/**
 * Register error and exception handlers
 */
set_error_handler(
    function (int $severity, string $msg, string $file, int $line): void {
        log(new ErrorException($msg, 0, $severity, $file, $line));
    }
);
set_exception_handler(
    function (Throwable $e): void {
        log($e);
    }
);

/**
 * Run application
 */
run();

/**
 * Render response
 */
echo §('root');

Fix regression from "boot.php currently not needed separately"


<?php

use YesWiki\Core\YesWikiHandler;

class HelloHandler extends YesWikiHandler
{
    function run()
    {
        $pageBody = $this->wiki->page['body'];
        throw new \Exception("toto");
        return $this->renderInSquelette('@helloworld/hello.twig', ['body' => $pageBody]);
    }
}

<?php

use YesWiki\Core\YesWikiHandler;

class HelloHandler extends YesWikiHandler
{
    function run()
    {
        $pageBody = $this->wiki->page['body'];
        return $this->renderInSquelette('@helloworld/hello.twig', ['body' => $pageBody]);
    }
}

Revert "feat(Performer): test on HelloWorld"


<?php

use Illuminate\Database\Seeder;

class WebMentionsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $webmention = App\WebMention::create([
            'source' => 'https://aaornpk.local/reply/1',
            'target' => 'https://jonnybarnes.localhost/notes/D',
            'commentable_id' => '13',
            'commentable_type' => 'App\Note',
            'type' => 'in-reply-to',
            'mf2' => '{"rels": [], "items": [{"type": ["h-entry"], "properties": {"url": ["https://aaronpk.localhost/reply/1"], "name": ["Hi too"], "author": [{"type": ["h-card"], "value": "Aaron Parecki", "properties": {"url": ["https://aaronpk.localhost"], "name": ["Aaron Parecki"], "photo": ["https://aaronparecki.com/images/profile.jpg"]}}], "content": [{"html": "Hi too", "value": "Hi too"}], "published": ["' . date(DATE_W3C) . '"], "in-reply-to": ["https://aaronpk.loclahost/reply/1", "https://jonnybarnes.uk/notes/D"]}}]}'
        ]);
    }
}

<?php

use Illuminate\Database\Seeder;

class WebMentionsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $webmention = App\WebMention::create([
            'source' => 'https://aaornpk.localhost/reply/1',
            'target' => 'https://jonnybarnes.localhost/notes/D',
            'commentable_id' => '13',
            'commentable_type' => 'App\Note',
            'type' => 'in-reply-to',
            'mf2' => '{"rels": [], "items": [{"type": ["h-entry"], "properties": {"url": ["https://aaronpk.localhost/reply/1"], "name": ["Hi too"], "author": [{"type": ["h-card"], "value": "Aaron Parecki", "properties": {"url": ["https://aaronpk.localhost"], "name": ["Aaron Parecki"], "photo": ["https://aaronparecki.com/images/profile.jpg"]}}], "content": [{"html": "Hi too", "value": "Hi too"}], "published": ["' . date(DATE_W3C) . '"], "in-reply-to": ["https://aaronpk.loclahost/reply/1", "https://jonnybarnes.uk/notes/D"]}}]}'
        ]);
    }
}

Fix difference in URLs in webmention

Fix difference in URLs in webmention


<?php

    include_once  $_SERVER["DOCUMENT_ROOT"].'/system/utils/UserHelper.php';

    Use \App\System\Helpers\UserHelper as UserHelper;

    if ( !isset($_POST['username-modal']) && !isset($_POST['password-modal']) ){
        header('Location: /account/bad_login');
        die();
    }

    $user = array(
        'username' => $_POST['username-modal'],
        'password' => $_POST['password-modal']
    );

    if(isset($_POST['remember_me']) && $_POST['remember_me'] == "true"){
      $remember = true;
    }else{
      $remember = false;
    }
    if (UserHelper::login($user, $remember) === true){
        header('Location: /home');
        die();
    }else{
        header('Location: /account/bad_login');
        die();
    }

 ?>

<?php

    include_once  $_SERVER["DOCUMENT_ROOT"].'/system/utils/UserHelper.php';

    Use \App\System\Helpers\UserHelper as UserHelper;

    if ( !isset($_POST['username']) && !isset($_POST['password']) ){
        header('Location: /account/bad_login');
        die();
    }

    $user = array(
        'username' => $_POST['username'],
        'password' => $_POST['password']
    );

    if(isset($_POST['remember_me']) && $_POST['remember_me'] == "true"){
      $remember = true;
    }else{
      $remember = false;
    }
    if (UserHelper::login($user, $remember) === true){
        header('Location: /home');
        die();
    }else{
        header('Location: /account/bad_login');
        die();
    }

 ?>

Fix nombre de los campos

Fix nombre de los campos


<?php defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Enable/Disable Migrations
|--------------------------------------------------------------------------
|
| Migrations are disabled by default but should be enabled
| whenever you intend to do a schema migration.
|
*/
$config['migration_enabled'] = FALSE;

/*
|--------------------------------------------------------------------------
| Migrations version
|--------------------------------------------------------------------------
|
| This is used to set migration version that the file system should be on.
| If you run $this->migration->latest() this is the version that schema will
| be upgraded / downgraded to.
|
*/
$config['migration_version'] = 0;

/*
|--------------------------------------------------------------------------
| Migrations Path
|--------------------------------------------------------------------------
|
| Path to your migrations folder.
| Typically, it will be within your application path.
| Also, writing permission is required within the migrations path.
|
*/
$config['migration_path'] = APPPATH . 'migrations/';

/* End of file migration.php */
/* Location: ./application/config/migration.php */

Convert liefeeds to Unix style

Convert liefeeds to Unix style


    <?php echo $savvy->render($context->getMonthWidget()); ?>

    Subscribe to this calendar

<a href="<?php echo $frontend->getUpcomingURL(); ?>?format=rss&limit=100" title="RSS feed of upcoming events" class="wdn-icon-rss-squared">RSS

<a href="<?php echo $frontend->getUpcomingURL(); ?>?format=ics&limit=100" title="ICS format of upcoming events" class="wdn-icon-calendar">ICS

    <?php echo $savvy->render($context->getMonthWidget()); ?>

    Subscribe to this calendar

<a href="<?php echo $frontend->getUpcomingURL(); ?>?format=rss&limit=100" title="RSS feed of upcoming events" class="eventicon-rss">RSS

<a href="<?php echo $frontend->getUpcomingURL(); ?>?format=ics&limit=100" title="ICS format of upcoming events" class="wdn-icon-calendar">ICS

Use eventicon in sidebar links

Use eventicon in sidebar links


<div id="<?=$_id?>" class="well">

Register

    <form action="<?=$registerUrl?>" method="post">
        Email
        <input name="email" type="text" value="<?=empty($email) ? '' : $email?>"
               placeholder="Email" />

        Password
        <input name="password" type="password" placeholder="Password" />

        Confirm Password
        <input name="password_confirm" type="password"
               placeholder="Confirm password" />

        <input type="hidden" name="register" value="1" />
        <button>Register</button>

        <?=app()->createCaptcha()?>
    </form>

PHP

Create validator

$validator = app()->createValidator();

Create rule to validate email address format

$rule = $validator->createRule('email')
    ->setErrorMessage('Invalid email address')
    ->setAction('isEmail');
$validator->addRule($rule);

Add more rules and finally get validation result

    $result = $validator->validate()->getResult();

<div id="<?=$_id?>" class="well">

Register

    <form action="<?=$registerUrl?>" method="post">
        Email
        <input name="email" type="text" value="<?=empty($email) ? '' : $email?>"
               placeholder="Email" />

        Password
        <input name="password" type="password" placeholder="Password" />

        Confirm Password
        <input name="password_confirm" type="password"
               placeholder="Confirm password" />

        <input type="hidden" name="register" value="1" />
        <button class="btn">Register</button>

        <?=app()->createCaptcha()?>
    </form>

PHP

Create validator

$validator = app()->createValidator();

Create rule to validate email address format

$rule = $validator->createRule('email')
    ->setErrorMessage('Invalid email address')
    ->setAction('isEmail');
$validator->addRule($rule);

Add more rules and finally get validation result

    $result = $validator->validate()->getResult();

Add css class to register form button

Add css class to register form button


<?php

namespace Fuzz\ApiServer\Exception;

use Exception;
use Fuzz\ApiServer\Routing\Responder;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
	/**
	 * Render an exception into an HTTP response.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Exception  $e
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function render($request, Exception $e)
	{
		// Recast ModelNotFoundExceptions as local NotFoundExceptions
		if ($e instanceof ModelNotFoundException) {
			$e = new NotFoundException(
				'Unable to find ' . $e->getModel() . '.'
			);
		}

		return (new Responder)->sendException($e);
	}
}

<?php

namespace Fuzz\ApiServer\Exception;

use Exception;
use Fuzz\ApiServer\Routing\Responder;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
	/**
	 * Render an exception into an HTTP response.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Exception  $e
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function render($request, Exception $e)
	{
		// Recast ModelNotFoundExceptions as local NotFoundExceptions
		if ($e instanceof ModelNotFoundException) {
			$e = new NotFoundException(
				'Unable to find ' . class_basename($e->getModel()) . '.'
			);
		}

		return (new Responder)->sendException($e);
	}
}

Use class basename for ModelNotFoundException


@extends('layout')

@section('body')

{{ __('general.earnings') }}

            @if (count($earnings))
                @foreach ($earnings as $earning)

{{ $earning->description }}

{{ $earning->formatted_happened_on }}

€ {{ $earning->formatted_amount }}

                @endforeach
            @else

You don't have any earnings

            @endif

@endsection

@extends('layout')

@section('title', __('general.earnings'))

@section('body')

{{ __('general.earnings') }}

            @if (count($earnings))
                @foreach ($earnings as $earning)

{{ $earning->description }}

{{ $earning->formatted_happened_on }}

€ {{ $earning->formatted_amount }}

                @endforeach
            @else

You don't have any earnings

            @endif

@endsection

Add title to earnings' index view

Add title to earnings' index view


<?php

namespace JVCrud\Filter;

class Url
{
    public function verifyUrlQueryFilter($paramsQuery)
    {
        $fromQuery = null;

        if (is_array($paramsQuery) && count($paramsQuery))
        {
            $fromQuery = '?';
            $line = array_map(array($this,'map'),array_keys($paramsQuery),array_value($paramsQuery));
            $fromQuery .= implode('&',$line);
        }

        return $fromQuery;
    }
    public function map($k,$v){
        return "{$k}={$v}";
    }
}

<?php

namespace JVCrud\Filter;

class Url
{
    public function verifyUrlQueryFilter($paramsQuery)
    {
        $fromQuery = null;

        if (is_array($paramsQuery) && count($paramsQuery))
        {
            $fromQuery = '?'.http_build_query($paramsQuery); // http://www.php.net/manual/pt_BR/function.http-build-query.php
        }

        return $fromQuery;
    }
    public function map($k,$v){
        return "{$k}={$v}";
    }
}

Add native function on url filter

Add native function on url filter


<?php

namespace SaasRunner;

use Guzzle;

class Client {

    public function __construct($apiKey, $apiHost = 'api.saasrunner.com') {
        $this->client = new Guzzle\Http\Client('http://' . $apiHost);
        $this->setApiKey($apiKey);
    }

    protected function setApiKey($apiKey) {
        $this->apiKey = $apiKey;
        $this->client->setDefaultOption('headers', ['X-API-Key' => $apiKey]);

        return $this;
    }
}

<?php

namespace SaasRunner;

use Guzzle;

class Client {

    public function __construct($apiKey, $apiHost = 'api.saasrunner.com') {
        $this->client = new Guzzle\Http\Client('http://' . $apiHost);
        $this->setApiKey($apiKey);
    }

    # Public: perform an HTTP GET request
    #
    #   string $path - URL path to send the request to
    #
    # Return instance of Guzzle\Http\Message\Response
    public function get($path) {
        return $this->request('get', $path);
    }

    # Public: perform an HTTP POST request
    #
    #   string $path - URL path to send the request to
    #   array $params - Parameters to send as the POST body
    #
    # Return instance of Guzzle\Http\Message\Response
    public function post($path, $params = []) {
        return $this->request('post', $path, $params);
    }

    # Public: perform an HTTP DELETE request
    #
    #   string $path - URL path to send the request to
    #
    # Return instance of Guzzle\Http\Message\Response
    public function delete($path) {
        return $this->request('delete', $path);
    }

    # Internal: perform an HTTP request
    #
    #   string $httpMethod - HTTP request method to perform (eg. "post")
    #   string $path - URL path to send the request to
    #   array $params - Parameters to send as the POST body
    #
    # Return instance of Guzzle\Http\Message\Response
    protected function request($httpMethod, $path, $params = []) {
        $request = $this->client->createRequest($httpMethod, $path, [], $params, []);
        $response = $request->send();

        return $response;
    }

    # Internal: store the API key and add it as a default header
    #
    #   string $apiKey  - The API key to store
    #
    # Returns this
    protected function setApiKey($apiKey) {
        $this->apiKey = $apiKey;
        $this->client->setDefaultOption('headers', ['X-API-Key' => $apiKey]);

        return $this;
    }
}

Add request methods to client

Add request methods to client


<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class ChangeDataTypeToLongtext extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		$this->dropColumn();

		Schema::table('sprint_snapshots', function($t)
		{
			$t->longText('data');
		});
	}

	private function dropColumn()
	{
		Schema::table('sprint_snapshots', function($t)
		{
			$t->dropColumn('data');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		$this->dropColumn();

		Schema::table('sprint_snapshots', function($t)
		{
			$t->dropColumn('data');
		});
	}

}

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class ChangeDataTypeToLongtext extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		DB::statement('ALTER TABLE sprint_snapshots MODIFY COLUMN data LONGTEXT');
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		DB::statement('ALTER TABLE sprint_snapshots MODIFY COLUMN data TEXT');
	}

}

Fix data column to longtext migration.

Fix data column to longtext migration.


<?php

namespace Platformsh\ConsoleForm\Field;

class BooleanField extends Field
{
    public $default = true;

    /**
     * {@inheritdoc}
     */
    protected function getQuestionText()
    {
        return $this->name
          . '? <question>['
          . ($this->default ? 'Y|n' : 'y|N')
          . ']</question> ';
    }

    /**
     * {@inheritdoc}
     */
    protected function normalize($value)
    {
        $false = ['false', '0', 'no', 'n'];

        return !in_array(strtolower($value), $false);
    }
}

<?php

namespace Platformsh\ConsoleForm\Field;

use Platformsh\ConsoleForm\Exception\InvalidValueException;

class BooleanField extends Field
{
    public $default = true;

    /**
     * {@inheritdoc}
     */
    protected function getQuestionText()
    {
        return $this->name
          . '? <question>['
          . ($this->default ? 'Y|n' : 'y|N')
          . ']</question> ';
    }

    /**
     * {@inheritdoc}
     */
    protected function normalize($value)
    {
        if (is_bool($value)) {
            return $value;
        }
        elseif (preg_match('/^(0|false|no|n)$/i', $value)) {
            return false;
        }
        elseif (preg_match('/^(1|true|yes|y)$/i', $value)) {
            return true;
        }
        else {
            throw new InvalidValueException("Invalid value for '{$this->name}': $value");
        }
    }
}

Validate the boolean field strictly

Validate the boolean field strictly


<?php

$_dir = rtrim(__DIR__, '\/').DIRECTORY_SEPARATOR;
require $_dir.'../../vendor/autoload.php';
require $_dir.'../conf.php';

\App\RedisHelper::del(array_slice($argv, 1));

<?php

$_dir = rtrim(__DIR__, '\/').DIRECTORY_SEPARATOR;
require $_dir.'../../vendor/autoload.php';
require $_dir.'../conf.php';

$num = \App\RedisHelper::del(array_slice($argv, 1)) ?? 0;
echo basename(__FILE__).": $num key".($num===1?'':'s')." deleted successfully\n";

Add number of keys deleted as output to the redis clear script


<?php

/*
|--------------------------------------------------------------------------
| Vietnamese Language for Laravel 4
|--------------------------------------------------------------------------
|
| Translate by anhsk.ohbo@gmail.com
|
*/

return array(

	/*
	|--------------------------------------------------------------------------
	| Password Reminder Language Lines
	|--------------------------------------------------------------------------
	|
	| The following language lines are the default lines which match reasons
	| that are given by the password broker for a password update attempt
	| has failed, such as for an invalid token or invalid new password.
	|
	*/

	"password" => "Mật khẩu phải gồm 6 ký tự và khớp với phần xác nhận.",

	"user"     => "Không tìm thấy user với địa chỉ email này.",

	"token"    => "Mã reset mật khẩu không hợp lệ.",

    "sent"     => "Password reminder sent!",

);

<?php

/*
|--------------------------------------------------------------------------
| Vietnamese Language for Laravel 4
|--------------------------------------------------------------------------
|
| Translate by anhsk.ohbo@gmail.com
|
*/

return array(

	/*
	|--------------------------------------------------------------------------
	| Password Reminder Language Lines
	|--------------------------------------------------------------------------
	|
	| The following language lines are the default lines which match reasons
	| that are given by the password broker for a password update attempt
	| has failed, such as for an invalid token or invalid new password.
	|
	*/

	"password" => "Mật khẩu phải gồm 6 ký tự và khớp với phần xác nhận.",

	"user"     => "Không tìm thấy user với địa chỉ email này.",

	"token"    => "Mã reset mật khẩu không hợp lệ.",

    	"sent"     => "Cấp lại mật khẩu đã đuợc gửi!",

);

Add send element supprort Laravel 4.1

Add send element supprort Laravel 4.1


{% extends 'backend/layout.twig.php' %}
{% block content %}

    {% if message.content is defined %}

        {{ message.content }}

    {% endif %}

Register a new user

    <form action="/backend/users/register" method="post">

          Name
          <input name="name" placeholder="Real Name" value="{{ formVars.name }}" class="input-control" />

          Email
          <input name="email" placeholder="Email" value="{{ formVars.email }}" class="input-control" />

          Password
          <input name="passwd" placeholder="password" class="input-control" />

          User Level
          <input name="userLevel" value="{{ formVars.userLevel }}" class="input-control" placeholder="3" style="flex: 6" />

          <button type="submit">Save</button>
          <button>Cancel</button>

    </form>

{% endblock %}

{% extends 'backend/layout.twig.php' %}
{% block content %}

    {% if message.content is defined %}

        {{ message.content }}

    {% endif %}

Register a new user

    <form action="/backend/users/register" method="post">

          Name
          <input name="name" placeholder="Real Name" value="{{ formVars.name }}" class="input-control" />

          Email
          <input name="email" placeholder="Email" value="{{ formVars.email }}" class="input-control" />

          Password
          <input name="passwd" placeholder="password" class="input-control" />

          User Level
          <input name="userLevel" value="{{ formVars.userLevel }}" class="input-control" placeholder="3" style="flex: 6" />

          <button type="submit">Save</button>
          <button onclick="event.preventDefault(); window.location.href='/backend/users'">Cancel</button>

    </form>

{% endblock %}

EDIT prevent default submit behaviour, add redirect


@extends('layouts.app')

@section('title', 'Schedule new campaign run')

@section('content')

SCHEDULES

Edit scheduled run {{ $schedule->campaign->name }}

                 $schedule->campaign])  }}" class="btn palette-Cyan bg waves-effect">
                     Edit campaign

                 $schedule->campaign])  }}" class="btn palette-Cyan bg waves-effect">
                     Edit campaign

            @include('flash::message')

            {!! Form::model($schedule, ['route' => ['schedule.update', 'schedule' => $schedule], 'method' => 'PATCH']) !!}
            @include('schedule._form')
            {!! Form::close() !!}

@endsection

@extends('layouts.app')

@section('title', 'Schedule new campaign run')

@section('content')

SCHEDULES

Edit scheduled run {{ $schedule->campaign->name }}

                 $schedule->campaign])  }}" class="btn palette-Cyan bg waves-effect">
                     Show campaign

                 $schedule->campaign])  }}" class="btn palette-Cyan bg waves-effect">
                     Edit campaign

            @include('flash::message')

            {!! Form::model($schedule, ['route' => ['schedule.update', 'schedule' => $schedule], 'method' => 'PATCH']) !!}
            @include('schedule._form')
            {!! Form::close() !!}

@endsection

Fix "show campaign" button label

Fix "show campaign" button label


<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2020, Pierre-Henry Soria. All Rights Reserved.
 * @license          MIT License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Test / Unit / Framework / Navigation
 */

declare(strict_types=1);

namespace PH7\Test\Unit\Framework\Navigation;

use PH7\Framework\Navigation\Browser;
use PHPUnit\Framework\TestCase;

final class BrowserTest extends TestCase
{
    /**
     * @dataProvider defaultBrowserHexCodesProvider
     */
    public function testFoundDefaultBrowserHexCode(string $sHexCode): void
    {
        $bResult = Browser::isDefaultBrowserHexCodeFound($sHexCode);

        $this->assertTrue($bResult);
    }

    public function testNotFoundDefaultBrowserHexCode(): void
    {
        $bResult = Browser::isDefaultBrowserHexCodeFound('#FFF');

        $this->assertFalse($bResult);
    }

    public function defaultBrowserHexCodesProvider(): array
    {
        return [
            ['#000'],
            ['#000000']
        ];
    }
}

<?php
/**
 * @author           Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright        (c) 2020, Pierre-Henry Soria. All Rights Reserved.
 * @license          MIT License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Test / Unit / Framework / Navigation
 */

declare(strict_types=1);

namespace PH7\Test\Unit\Framework\Navigation;

use PH7\Framework\Navigation\Browser;
use PHPUnit\Framework\TestCase;

final class BrowserTest extends TestCase
{
    private Browser $oBrowser;

    protected function setUp(): void
    {
        parent::setUp();

        $this->oBrowser = new Browser();
    }

    /**
     * @dataProvider defaultBrowserHexCodesProvider
     */
    public function testFoundDefaultBrowserHexCode(string $sHexCode): void
    {
        $bResult = Browser::isDefaultBrowserHexCodeFound($sHexCode);

        $this->assertTrue($bResult);
    }

    public function testNotFoundDefaultBrowserHexCode(): void
    {
        $bResult = Browser::isDefaultBrowserHexCodeFound('#FFF');

        $this->assertFalse($bResult);
    }

    public function testIfModifiedSinceExists(): void
    {
        $sExpectedDate = 'Tue, 29 Feb 2022 10:20:26 GMT';

        $_SERVER['HTTP_IF_MODIFIED_SINCE'] = $sExpectedDate;

        $this->assertSame($sExpectedDate, $this->oBrowser->getIfModifiedSince());
    }

    public function testIfModifiedSinceDoesNotExist(): void
    {
        unset($_SERVER['HTTP_IF_MODIFIED_SINCE']);

        $this->assertNull($this->oBrowser->getIfModifiedSince());
    }

    public function defaultBrowserHexCodesProvider(): array
    {
        return [
            ['#000'],
            ['#000000']
        ];
    }
}

Add unit tests for `getIfModifiedSince`

Add unit tests for `getIfModifiedSince`


<?php

use Proud\Core;

class Submenu extends Core\ProudWidget {

    function __construct() {
        parent::__construct(
            'submenu', // Base ID
            __( 'Submenu', 'wp-agency' ), // Name
            array( 'description' => __( "Display a submenu", 'wp-agency' ), ) // Args
        );
    }

    function initialize() {
    }

    /**
     * Outputs the content of the widget
     *
     * @param array $args
     * @param array $instance
     */
    public function printWidget( $args, $instance ) {
        global $pageInfo;
        if ( $pageInfo['parent_link'] > 0 ) {

            $args = array(
              'menu' => $pageInfo['menu'],
              'submenu' => $pageInfo['parent_link'],
              'menu_class' => 'nav nav-pills nav-stacked',
            );

            wp_nav_menu( $args );
        }

    }
}

// register Foo_Widget widget
function register_submenu_widget() {
    register_widget( 'Submenu' );
}
add_action( 'widgets_init', 'register_submenu_widget' );

<?php

use Proud\Core;

class Submenu extends Core\ProudWidget {

    function __construct() {
        parent::__construct(
            'submenu', // Base ID
            __( 'Submenu', 'wp-agency' ), // Name
            array( 'description' => __( "Display a submenu", 'wp-agency' ), ) // Args
        );
    }

    function initialize() {
    }

    /**
     * Outputs the content of the widget
     *
     * @param array $args
     * @param array $instance
     */
    public function printWidget( $args, $instance ) {
        global $pageInfo;
        if ( $pageInfo['parent_link'] > 0 ) {

            $args = array(
              'menu' => $pageInfo['menu'],
              'submenu' => $pageInfo['parent_link'],
              'menu_class' => 'nav nav-pills nav-stacked submenu',
              'fallback_cb' => false,
            );

            wp_nav_menu( $args );
        }

    }
}

// register Foo_Widget widget
function register_submenu_widget() {
    register_widget( 'Submenu' );
}
add_action( 'widgets_init', 'register_submenu_widget' );

Set callback param to false

Set callback param to false


<?php namespace Maatwebsite\Usher\Domain\Users\Activations;

use Doctrine\ORM\Mapping as ORM;
use Maatwebsite\Usher\Services\CodeGenerator;
use Maatwebsite\Usher\Domain\Shared\Embeddables\Date;
use Maatwebsite\Usher\Contracts\Users\Activiations\ActivationCode as ActivationCodeInterface;

/**
 * @ORM\Embeddable
 */
class ActivationCode extends Date implements ActivationCodeInterface
{

    /**
     * @ORM\Column(type="string", name="activation_code", unique=true)
     */
    protected $code;

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

    /**
     * @return mixed
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * @param mixed $code
     */
    public function setCode($code)
    {
        $this->code = $code;
    }

    /**
     * @return ActivationCode
     */
    public static function generate()
    {
        return new static(
            CodeGenerator::make()
        );
    }

    /**
     * @return string
     */
    public function toString()
    {
        return (string) $this->getToken();
    }
}

<?php namespace Maatwebsite\Usher\Domain\Users\Activations;

use Doctrine\ORM\Mapping as ORM;
use Maatwebsite\Usher\Services\CodeGenerator;
use Maatwebsite\Usher\Domain\Shared\Embeddables\Date;
use Maatwebsite\Usher\Contracts\Users\Activiations\ActivationCode as ActivationCodeInterface;

/**
 * @ORM\Embeddable
 */
class ActivationCode extends Date implements ActivationCodeInterface
{

    /**
     * @ORM\Column(type="string", name="activation_code", unique=true)
     */
    protected $code;

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

    /**
     * @return mixed
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * @param mixed $code
     */
    public function setCode($code)
    {
        $this->code = $code;
    }

    /**
     * @return ActivationCode
     */
    public static function generate()
    {
        return new static(
            CodeGenerator::make()
        );
    }

    /**
     * @return string
     */
    public function toString()
    {
        return (string) $this->getCode();
    }
}

Fix activation code to string

Fix activation code to string


<?php

use OAuth1Client\Credentials\TemporaryCredentials;

class TemporaryCredentialsTest extends PHPUnit_Framework_TestCase {
    protected $temporaryCredentials;

    function setUp()
    {
        $this->temporaryCredentials = new TemporaryCredentials('foo', 'bar');
    }

    /** @test */
    function temporary_credentials_has_identifier()
    {
        $this->assertEquals('foo', $this->temporaryCredentials->identifier());
    }

    /** @test */
    function temporary_credentials_has_secret()
    {
        $this->assertEquals('bar', $this->temporaryCredentials->secret());
    }

    /** @test */
    function temporary_credentials_not_exposing_secret_property_when_casting_to_string()
    {
        $this->assertEquals('foo', (string) $this->temporaryCredentials);
    }
}

<?php

use GuzzleHttp\Client as HttpClient;
use OAuth1Client\Credentials\TemporaryCredentials;

class TemporaryCredentialsTest extends PHPUnit_Framework_TestCase {
    protected $temporaryCredentials;

    function setUp()
    {
        $this->temporaryCredentials = new TemporaryCredentials('foo', 'bar');

        $this->httpClient = new HttpClient();
    }

    /** @test */
    function temporary_credentials_has_identifier()
    {
        $this->assertEquals('foo', $this->temporaryCredentials->identifier());
    }

    /** @test */
    function temporary_credentials_has_secret()
    {
        $this->assertEquals('bar', $this->temporaryCredentials->secret());
    }

    /** @test */
    function temporary_credentials_can_be_instantiated_from_http_response()
    {
        $response = $this->httpClient->get('http://www.mocky.io/v2/567a64390f0000eb051aef7c');

        $temporaryCredentials = TemporaryCredentials::fromHttpResponse($response);

        $this->assertInstanceOf(TemporaryCredentials::class, $temporaryCredentials);

        $this->assertEquals('foo', $temporaryCredentials->identifier());

        $this->assertEquals('bar', $temporaryCredentials->secret());
    }

    /** @test */
    function temporary_credentials_not_exposing_secret_property_when_casting_to_string()
    {
        $this->assertEquals('foo', (string) $this->temporaryCredentials);
    }
}

Add new test for fromHttpResponse method.


<?php

namespace SlmMail\Mail\Message\Provider;

use SlmMail\Mail\Message\ProvidesAttachments;
use Zend\Mail\Message;

class AlphaMail extends Message
{
    /**
     * Identifier of AlphaMail project id to use
     *
     * @var int
     */
    protected $project;

    /**
     * Variables to send to the project (they call it "payload")
     *
     * @var array
     */
    protected $variables;

    /**
     * Set the project id to use
     *
     * @param  int $project
     * @return self
     */
    public function setProject($project)
    {
        $this->project = (int) $project;
        return $this;
    }

    /**
     * Get the porject id to use
     *
     * @return string
     */
    public function getProject()
    {
        return $this->project;
    }

    /**
     * Set variables
     *
     * @param  array $variables
     * @return self
     */
    public function setVariables(array $variables)
    {
        $this->variables = $variables;
        return $this;
    }

    /**
     * Get variables
     *
     * @return array
     */
    public function getVariables()
    {
        return $this->variables;
    }
}

<?php

namespace SlmMail\Mail\Message\Provider;

use Zend\Mail\Message;

class AlphaMail extends Message
{
    /**
     * Identifier of AlphaMail project id to use
     *
     * @var int
     */
    protected $project;

    /**
     * Variables to send to the project (they call it "payload")
     *
     * @var array
     */
    protected $variables;

    /**
     * Set the project id to use
     *
     * @param  int $project
     * @return self
     */
    public function setProject($project)
    {
        $this->project = (int) $project;
        return $this;
    }

    /**
     * Get the porject id to use
     *
     * @return string
     */
    public function getProject()
    {
        return $this->project;
    }

    /**
     * Set variables
     *
     * @param  array $variables
     * @return self
     */
    public function setVariables(array $variables)
    {
        $this->variables = $variables;
        return $this;
    }

    /**
     * Get variables
     *
     * @return array
     */
    public function getVariables()
    {
        return $this->variables;
    }
}

Remove not existing and unused trait

Remove not existing and unused trait


<?php
/**
 * @author Boris Guéry <guery.b@gmail.com>
 */

namespace JsonBuilder;

class JsonBuilderTest extends \PHPUnit_Framework_TestCase
{
    public function testBuildASimpleJsonObject()
    {
    }

    public function testBuildAMoreComplexJsonObject()
    {
    }

    public function testBuildASimpleString()
    {
    }

    public function testBuildASimpleNumber()
    {
    }

    public function testBuildNullValue()
    {
    }
}

<?php
/**
 * @author Boris Guéry <guery.b@gmail.com>
 */

namespace JsonBuilder;

class JsonBuilderTest extends \PHPUnit_Framework_TestCase
{
    public function testBuildASimpleJsonObject()
    {
        $object = new JsonObject();
        $json = $object->add('Foo', 'Bar')->add('Bar', 'Baz')->toJson();

        $expectedJson = <<<JSON
{"Foo": "Bar", "Bar": "Baz"}
JSON;

        $this->assertEquals(
            json_decode($expectedJson, true),
            json_decode($json, true)
        );
    }

    public function testBuildASimpleJsonArray()
    {
        $array = new JsonArray();
        $json = $array->add('Foo')->add('Bar')->toJson();

        $expectedJson =<<<JSON
["Foo", "Bar"]
JSON;

        $this->assertEquals(
            json_decode($expectedJson, true),
            json_decode($json, true)
        );
    }

    public function testBuildAnArrayOfObject()
    {
    }

    public function testBuildAnObjectOfArray()
    {
    }

    public function testBuildASimpleString()
    {
        $string = new JsonString("Foobar");
        $json = $string->toJson();

        $expectedJson = <<<JSON
"Foobar"
JSON;

        $this->assertEquals(
            json_decode($expectedJson, true),
            json_decode($json)
        );
    }

    public function testBuildASimpleNumber()
    {
        $string = new JsonNumber(3.14);
        $json = $string->toJson();

        $expectedJson = <<<JSON
3.14
JSON;

        $this->assertEquals(
            json_decode($expectedJson, true),
            json_decode($json)
        );
    }

    public function testBuildNullValue()
    {
        $string = new JsonNull();
        $json = $string->toJson();

        $expectedJson = <<<JSON
null
JSON;

        $this->assertEquals(
            json_decode($expectedJson, true),
            json_decode($json)
        );
    }
}

Add some concrete tests with a simple api


<?php

use Tomahawk\HttpKernel\Kernel;

class AppKernel extends Kernel
{

    public function registerBundles()
    {
        $bundles = array(
            new \Tomahawk\Bundle\FrameworkBundle\FrameworkBundle(),
            new \Tomahawk\Bundle\GeneratorBundle\GeneratorBundle(),
            new \Tomahawk\Bundle\MigrationsBundle\MigrationsBundle(),
            new \Acme\AcmeBundle()
        );

        if ($this->getEnvironment() === 'dev') {
            $bundles[] = new \Tomahawk\Bundle\WebProfilerBundle\WebProfilerBundle();
        }

        return $bundles;
    }

    public function registerMiddleware()
    {
        return array(
            new \Tomahawk\HttpCore\Middleware\Response(),
            new \Tomahawk\Session\Middleware\Session()
        );
    }
}

<?php

use Tomahawk\HttpKernel\Kernel;

class AppKernel extends Kernel
{

    public function registerBundles()
    {
        $bundles = array(
            new \Tomahawk\Bundle\FrameworkBundle\FrameworkBundle(),
            new \Tomahawk\Bundle\GeneratorBundle\GeneratorBundle(),
            new \Tomahawk\Bundle\MigrationsBundle\MigrationsBundle(),
            new \Tomahawk\Bundle\DoctrineBundle\DoctrineBundle(),
            new \Tomahawk\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new \Acme\AcmeBundle()
        );

        if ($this->getEnvironment() === 'dev') {
            $bundles[] = new \Tomahawk\Bundle\WebProfilerBundle\WebProfilerBundle();
        }

        return $bundles;
    }

    public function registerMiddleware()
    {
        return array(
            new \Tomahawk\HttpCore\Middleware\Response(),
            new \Tomahawk\Session\Middleware\Session()
        );
    }
}

Load new doctrine and swiftmailer bundles


<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),

            new Mopa\Bundle\BootstrapBundle\MopaBootstrapBundle(),

            new Ben\CoreBundle\BenCoreBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}

<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),

            new Mopa\Bundle\BootstrapBundle\MopaBootstrapBundle(),
            new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),

            new Ben\CoreBundle\BenCoreBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}

Add data fixtures bundle config

Add data fixtures bundle config


<?php

namespace Just\SonataThemeBundle\DependencyInjection;

use RuntimeException;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;

/**
 * This is the class that loads and manages your bundle configuration.
 *
 * @link http://symfony.com/doc/current/cookbook/bundles/extension.html
 */
class JustSonataThemeExtension extends Extension implements PrependExtensionInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $this->processConfiguration($configuration, $configs);
    }

    /**
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
     */
    public function prepend(ContainerBuilder $container)
    {
        $bundles = $container->getParameter('kernel.bundles');

        if (!array_key_exists('SonataAdminBundle', $bundles)) {
            throw new RuntimeException('SonataAdminBundle wasn\'t found, dit you registered it correctly?');
        }

        try {
            $config = Yaml::parse(file_get_contents(__DIR__ . '/../Resources/config/theme.yml'));
        } catch (ParseException $e) {
            printf("Unable to parse the YAML string: %s", $e->getMessage());
        }

        $container->prependExtensionConfig('sonata_admin', $config);
    }
}

<?php

namespace Just\SonataThemeBundle\DependencyInjection;

use RuntimeException;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;

/**
 * This is the class that loads and manages your bundle configuration.
 *
 * @link http://symfony.com/doc/current/cookbook/bundles/extension.html
 */
class JustSonataThemeExtension extends Extension implements PrependExtensionInterface
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $this->processConfiguration($configuration, $configs);
    }

    /**
     * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
     */
    public function prepend(ContainerBuilder $container)
    {
        $bundles = $container->getParameter('kernel.bundles');

        if (!array_key_exists('SonataAdminBundle', $bundles)) {
            throw new RuntimeException('SonataAdminBundle wasn\'t found, dit you registered it correctly?');
        }

        try {
            $config = Yaml::parse(file_get_contents(__DIR__ . '/../Resources/config/theme.yml'));
        } catch (ParseException $e) {
            throw new RuntimeException(sprintf("Unable to parse the YAML string: %s", $e->getMessage()));
        }

        $container->prependExtensionConfig('sonata_admin', $config);
    }
}

Bugfix: Update exception when YAML couldn't be parsed


<?php
/**
 * Plugin Name: Culture Object
 * Plugin URI: http://cultureobject.co.uk
 * Description: A framework as a plugin to enable sync of culture objects into WordPress.
 * Version: 3.0.0-alpha.2
 * Author: Liam Gladdy / Thirty8 Digital
 * Text Domain: culture-object
 * Author URI: https://github.com/lgladdy
 * GitHub Plugin URI: Thirty8Digital/CultureObject
 * GitHub Branch: master
 * License: Apache 2 License
 */

require_once('CultureObject/CultureObject.class.php');
$cos = new \CultureObject\CultureObject();

/* General Functions. These need to go into their own file one day. */

function cos_get_remapped_field_name($field_key) {
    global $cos;
    return $cos->helper->cos_get_remapped_field_name($field_key);
}

function cos_remapped_field_name($field_key) {
    global $cos;
    return $cos->helper->cos_remapped_field_name($field_key);
}

function cos_get_field($field_key) {
    $id = get_the_ID();
    if (!$id) return false;
    return get_post_meta($id, $field_key, true);
}

function cos_the_field($field_key) {
    echo cos_get_field($field_key);
}

<?php
/**
 * Plugin Name: Culture Object
 * Plugin URI: http://cultureobject.co.uk
 * Description: A framework as a plugin to enable sync of culture objects into WordPress.
 * Version: 3.0.0-alpha.2
 * Author: Liam Gladdy / Thirty8 Digital
 * Text Domain: culture-object
 * Author URI: https://github.com/lgladdy
 * GitHub Plugin URI: Thirty8Digital/CultureObject
 * GitHub Branch: schemas
 * License: Apache 2 License
 */

require_once('CultureObject/CultureObject.class.php');
$cos = new \CultureObject\CultureObject();

/* General Functions. These need to go into their own file one day. */

function cos_get_remapped_field_name($field_key) {
    global $cos;
    return $cos->helper->cos_get_remapped_field_name($field_key);
}

function cos_remapped_field_name($field_key) {
    global $cos;
    return $cos->helper->cos_remapped_field_name($field_key);
}

function cos_get_field($field_key) {
    $id = get_the_ID();
    if (!$id) return false;
    return get_post_meta($id, $field_key, true);
}

function cos_the_field($field_key) {
    echo cos_get_field($field_key);
}

Update branch for git updater

Update branch for git updater


<?php

namespace Becklyn\RadBundle\Entity\Traits;

use Doctrine\ORM\Mapping as ORM;

/**
 *
 */
trait TimestampsTrait
{
    /**
     * @var \DateTimeImmutable
     * @ORM\Column(name="time_created", type="datetime_immutable")
     */
    private $timeCreated;

    /**
     * @var \DateTimeImmutable|null
     * @ORM\Column(name="time_modified", type="datetime_immutable", nullable=true)
     */
    private $timeModified;

    /**
     * @return \DateTimeImmutable
     */
    public function getTimeCreated () : \DateTimeImmutable
    {
        return $this->timeCreated;
    }

    /**
     * @return \DateTimeImmutable|null
     */
    public function getTimeModified () : ?\DateTimeImmutable
    {
        return $this->timeModified;
    }

    /**
     * @param \DateTimeImmutable $timeModified
     */
    public function setTimeModified (\DateTimeImmutable $timeModified)
    {
        $this->timeModified = $timeModified;
    }

    /**
     * Returns the most recent modification time
     *
     * @return \DateTimeImmutable
     */
    public function getLastModificationTime () : \DateTimeImmutable
    {
        return $this->getTimeModified() ?? $this->getTimeCreated();
    }
}

<?php

namespace Becklyn\RadBundle\Entity\Traits;

use Doctrine\ORM\Mapping as ORM;

/**
 *
 */
trait TimestampsTrait
{
    /**
     * @var \DateTimeImmutable
     * @ORM\Column(name="time_created", type="datetime_immutable")
     */
    private $timeCreated;

    /**
     * @var \DateTimeImmutable|null
     * @ORM\Column(name="time_modified", type="datetime_immutable", nullable=true)
     */
    private $timeModified;

    /**
     * @return \DateTimeImmutable
     */
    public function getTimeCreated () : \DateTimeImmutable
    {
        return $this->timeCreated;
    }

    /**
     * @return \DateTimeImmutable|null
     */
    public function getTimeModified () : ?\DateTimeImmutable
    {
        return $this->timeModified;
    }

    /**
     * @param \DateTimeImmutable $timeModified
     */
    public function markAsModified ()
    {
        $this->timeModified = new \DateTimeImmutable();
    }

    /**
     * Returns the most recent modification time
     *
     * @return \DateTimeImmutable
     */
    public function getLastModificationTime () : \DateTimeImmutable
    {
        return $this->getTimeModified() ?? $this->getTimeCreated();
    }
}

Change to new setter-less date time method


<?php

namespace FOM\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class GroupType extends AbstractType
{
    /** @var string */
    protected $userEntityClass;

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

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', 'Symfony\Component\Form\Extension\Core\Type\TextType', array(
                'label' => 'Name',
            ))
            ->add('description', 'Symfony\Component\Form\Extension\Core\Type\TextareaType', array(
                'required' => false,
                'label' => 'fom.user.user.container.description',
            ))
            ->add('users', 'Symfony\Bridge\Doctrine\Form\Type\EntityType', array(
                'class' =>  $this->userEntityClass,
                'expanded' => true,
                'multiple' => true,
                'choice_label' => 'username',
                'label' => 'Users',
            ));
    }
}

<?php

namespace FOM\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class GroupType extends AbstractType
{
    /** @var string */
    protected $userEntityClass;

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

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', 'Symfony\Component\Form\Extension\Core\Type\TextType', array(
                'label' => 'Name',
            ))
            ->add('description', 'Symfony\Component\Form\Extension\Core\Type\TextareaType', array(
                'required' => false,
                'label' => 'fom.user.user.container.description',
            ))
            ->add('users', 'Symfony\Bridge\Doctrine\Form\Type\EntityType', array(
                'class' =>  $this->userEntityClass,
                'expanded' => true,
                'multiple' => true,
                'choice_label' => 'username',
                'label' => 'Users',
                // collection field rendering bypasses form theme; suppress
                // the spurious label if collection is empty
                'label_attr' => array(
                    'class' => 'hidden',
                ),
            ));
    }
}

Fix dangling collection label on empty users list, in group editing


<?php

namespace Bob;

task('test', array('phpunit.xml'), function() {
    echo sh('phpunit');
});

fileTask('phpunit.xml', array('phpunit.dist.xml'), function() {
    copy('phpunit.dist.xml', 'phpunit.xml');
});

<?php

namespace Bob;

task('default', array('test'));

task('test', array('phpunit.xml'), function() {
    echo `phpunit`;
});

fileTask('phpunit.xml', array('phpunit.dist.xml'), function() {
    copy('phpunit.dist.xml', 'phpunit.xml');
});

Set default build task to test

Set default build task to test


<?php
/**
 * mbc-transactional-digest
 *
 * Collect transactional campaign sign up message requests in a certain time period and
 * compose a single digest message request.
 */

date_default_timezone_set('America/New_York');
define('CONFIG_PATH',  __DIR__ . '/messagebroker-config');

// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\ MBC_TransactionalDigest\MBC_TransactionalDigest_Consumer;

// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-transactional-digest.config.inc';

// Kick off
echo '------- mbc-transactional-digest START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

$mb = $mbConfig->getProperty('messageBroker');
$mb->consumeMessage(array(new MBC_TransactionalDigest_Consumer(), 'consumeQueue'));

echo '------- mbc-transactional-digest END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

<?php
/**
 * mbc-transactional-digest
 *
 * Collect transactional campaign sign up message requests in a certain time period and
 * compose a single digest message request.
 */

date_default_timezone_set('America/New_York');
define('CONFIG_PATH',  __DIR__ . '/messagebroker-config');

// Load up the Composer autoload magic
require_once __DIR__ . '/vendor/autoload.php';
use DoSomething\ MBC_TransactionalDigest\MBC_TransactionalDigest_Consumer;

// Load configuration settings specific to this application
require_once __DIR__ . '/mbc-transactional-digest.config.inc';

// Kick off
echo '------- mbc-transactional-digest START - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

$mb = $mbConfig->getProperty('messageBroker_transactionalDigest');
$mb->consumeMessage(array(new MBC_TransactionalDigest_Consumer('messageBroker_transactionalDigest'), 'consumeQueue'));

echo '------- mbc-transactional-digest END - ' . date('j D M Y G:i:s T') . ' -------', PHP_EOL;

Connect to transactionalDigest queue as exclusive consumer


<?php // basic (and dumb) HTTP client

require __DIR__ . '/../vendor/autoload.php';

// This is a very simple HTTP client that just prints the response without parsing.

use Amp\ByteStream\ResourceOutputStream;
use Amp\Loop;
use Amp\Socket\Socket;
use Amp\Uri\Uri;
use function Amp\Socket\connect;
use function Amp\Socket\cryptoConnect;

Loop::run(function () use ($argv) {
    $stdout = new ResourceOutputStream(STDOUT);

    if (count($argv) !== 2) {
        yield $stdout->write("Usage: examples/simple-http-client.php url" . PHP_EOL);
        exit(1);
    }

    $uri = new Uri($argv[1]);
    $host = $uri->getHost();

    if ($uri->getScheme() === "https") {
        /** @var Socket $socket */
        $socket = yield cryptoConnect("tcp://" . $host . ":" . $uri->getPort());
    } else {
        /** @var Socket $socket */
        $socket = yield connect("tcp://" . $host . ":" . $uri->getPort());
    }

    yield $socket->write("GET {$uri} HTTP/1.1\r\nHost: $host\r\nConnection: close\r\n\r\n");
    yield Amp\ByteStream\pipe($socket, $stdout);
});

<?php // basic (and dumb) HTTP client

require __DIR__ . '/../vendor/autoload.php';

// This is a very simple HTTP client that just prints the response without parsing.

use Amp\ByteStream\ResourceOutputStream;
use Amp\Loop;
use Amp\Socket\Socket;
use Amp\Uri\Uri;
use function Amp\Socket\connect;
use function Amp\Socket\cryptoConnect;

Loop::run(function () use ($argv) {
    $stdout = new ResourceOutputStream(STDOUT);

    if (count($argv) !== 2) {
        yield $stdout->write("Usage: examples/simple-http-client.php url" . PHP_EOL);
        exit(1);
    }

    $uri = new Uri($argv[1]);
    $host = $uri->getHost();

    if ($uri->getScheme() === "https") {
        /** @var Socket $socket */
        $socket = yield cryptoConnect("tcp://" . $host . ":" . $uri->getPort());
    } else {
        /** @var Socket $socket */
        $socket = yield connect("tcp://" . $host . ":" . $uri->getPort());
    }

    yield $socket->write("GET {$uri} HTTP/1.1\r\nHost: $host\r\nConnection: close\r\n\r\n");

    while (null !== $chunk = yield $socket->read()) {
        yield $stdout->write($chunk);
    }

    // If the promise returned from `read()` resolves to `null`, the socket closed and we're done.
    // In this case you can also use `yield Amp\ByteStream\pipe($socket, $stdout)` instead of the while loop,
    // but we want to demonstate the `read()` method here.
});

Use read() directly in example instead of ByteStream\pipe()


<?php

use Illuminate\Database\Migrations\Migration;

/**
 * SuppressWarnings(PHPMD.ShortMethodName)
 *
 * Class ChangesForV321
 */
class ChangesForV321 extends Migration
{

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::rename('budget_limits', 'limits');
        Schema::rename('piggy_bank_events', 'piggybank_events');
        DB::update(DB::raw('ALTER TABLE `limit_repetitions` ALGORITHM=INPLACE, CHANGE `budget_limit_id` `limit_id` INT UNSIGNED NOT NULL'));
        DB::update(DB::Raw('ALTER TABLE `transactions` ADD `piggybank_id` INT(10) UNSIGNED DEFAULT NULL AFTER `account_id`;'));
    }

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::rename('limits', 'budget_limits');
        DB::update(DB::raw('ALTER TABLE `limit_repetitions` ALGORITHM=INPLACE, CHANGE `limit_id` `budget_limit_id` INT UNSIGNED NOT NULL'));
        DB::update(DB::Raw('ALTER TABLE `transactions` DROP `piggybank_id`'));
        Schema::rename('piggybank_events', 'piggy_bank_events');

    }

}

<?php

use Illuminate\Database\Migrations\Migration;

/**
 * SuppressWarnings(PHPMD.ShortMethodName)
 *
 * Class ChangesForV321
 */
class ChangesForV321 extends Migration
{

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::rename('budget_limits', 'limits');
        Schema::rename('piggy_bank_events', 'piggybank_events');
        DB::update(DB::raw('ALTER TABLE `limit_repetitions` ALGORITHM=INPLACE, CHANGE `budget_limit_id` `limit_id` INT UNSIGNED NOT NULL'));
        DB::update(DB::Raw('ALTER TABLE `transactions` ADD `piggybank_id` INT(10) UNSIGNED DEFAULT NULL AFTER `account_id`;'));
        DB::update(DB::Raw('CREATE INDEX `transactions_piggybank_id_foreign` ON `transactions` (`piggybank_id`)'));
        DB::update(DB::Raw('ALTER TABLE `transactions` ADD FOREIGN KEY (`piggybank_id`) REFERENCES `piggybanks`(`id`);'));
    }
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::rename('limits', 'budget_limits');
        DB::update(DB::raw('ALTER TABLE `limit_repetitions` ALGORITHM = INPLACE, CHANGE `limit_id` `budget_limit_id` INT UNSIGNED NOT null'));
        DB::update(DB::Raw('ALTER TABLE `transactions` DROP FOREIGN KEY `transactions_piggybank_id_foreign`'));
        DB::update(DB::Raw('ALTER TABLE `transactions` DROP `piggybank_id`'));
        Schema::rename('piggybank_events', 'piggy_bank_events');

    }

}

Update migrations to include index.

Update migrations to include index.


@if (config('services.algolia.key'))

        <input type="text" class="form-control" id="search" placeholder="Search the docs...">

@endif

Check if algolia api key is set.

Check if algolia api key is set.


		<?php echo validation_errors(); ?>
		<?php echo form_open('admin/login'); ?>

<?php echo $title; ?>

					<?php if($this->session->flashdata('user_loggedout')): ?>
		       		<?php echo '
'.$this->session->flashdata('user_loggedout').'
'; ?>
		     		<?php endif; ?>

					<?php if($this->session->flashdata('login_failed')): ?>
		        	<?php echo '
'.$this->session->flashdata('login_failed').'
'; ?>
		      		<?php endif; ?>

					<input type="text" name="username" class="form-control" placeholder="Enter Username" required autofocus autocomplete='off'>

						<input type="password" name="password" class="form-control" placeholder="Enter Password" required autofocus>

				<button type="submit" class="btn btn-success btn-block">Login</button>

		<?php echo form_close(); ?>

		<?php echo validation_errors(); ?>
		<?php echo form_open('admin/login'); ?>

<?php echo $title; ?>

					<?php if($this->session->flashdata('user_loggedout')): ?>
		       		<?php echo '
'.$this->session->flashdata('user_loggedout').'
'; ?>
		     		<?php endif; ?>

					<?php if($this->session->flashdata('login_failed')): ?>
		        	<?php echo '
'.$this->session->flashdata('login_failed').'
'; ?>
		      		<?php endif; ?>

					<input type="text" name="username" class="form-control" placeholder="Enter Username" required autofocus autocomplete='off'>

						<input type="password" name="password" class="form-control" placeholder="Enter Password" required autofocus>

				<button style="background-color:#5cb85c; color:white;" type="submit" class="btn btn-success btn-block">Login</button>

		<?php echo form_close(); ?>

Add Color to Login Button

Add Color to Login Button


<?php

use AdamWathan\Form\Elements\DateTimeLocal;

class DateTimeLocalTest extends PHPUnit_Framework_TestCase
{
    use InputContractTest;

    protected function newTestSubjectInstance($name)
    {
        return new DateTimeLocal($name);
    }

    protected function getTestSubjectType()
    {
        return 'datetime-local';
    }
}

<?php

use AdamWathan\Form\Elements\DateTimeLocal;

class DateTimeLocalTest extends PHPUnit_Framework_TestCase
{
    use InputContractTest;

    protected function newTestSubjectInstance($name)
    {
        return new DateTimeLocal($name);
    }

    protected function getTestSubjectType()
    {
        return 'datetime-local';
    }

    public function testDateTimeValuesAreBoundAsFormattedStrings()
    {
        $dateTimeLocal = new DateTimeLocal('dob');
        $dateTimeLocal->value(new DateTime('12-04-1988 10:33'));

        $expected = '<input type="datetime-local" name="dob" value="1988-04-12T10:33">';
        $this->assertSame($expected, $dateTimeLocal->render());
    }
}

Test for DateTimeLocal DateTime formatting


<?php

namespace MetaSyntactical\Http\Transport;

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

interface TransportInterface
{
    /**
     * Send request and return response
     *
     * @param  RequestInterface  $request
     * @return ResponseInterface
     */
    public function send(RequestInterface $request);

    /**
     * Create new request
     *
     * @return RequestInterface
     */
    public function newRequest();

    /**
     * Build query string as required for PSR 7 URI ->withQuery
     *
     * @return string
     */
    public function buildQuery();
}

<?php

namespace MetaSyntactical\Http\Transport;

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

interface TransportInterface
{
    /**
     * Send request and return response
     *
     * @param  RequestInterface  $request
     * @return ResponseInterface
     */
    public function send(RequestInterface $request);

    /**
     * Create new request
     *
     * @return RequestInterface
     */
    public function newRequest();

    /**
     * Build a query string from an array of key value pairs
     *
     * @param array     $params   Query string parameters.
     * @param int|false $encoding Set to false to not encode, PHP_QUERY_RFC3986
     *                            to encode using RFC3986, or PHP_QUERY_RFC1738
     *                            to encode using RFC1738.
     * @return string
     */
    public function buildQuery(array $params, $encoding = PHP_QUERY_RFC3986);
}

Add method to build query string

Add method to build query string