Indentation when using File Template to create new PHP Class in Netbeans - templates

I'm probably missing something, but I have the following issue:
I'm using Netbeans IDE 7.0.
I've created a template for new PHP Classes, but when I try to create a new class, the template I've created is inserted without any indentation.
Example:
Template:
<?php
/**
* Description of ${name}
*
* #author ${user}
*/
include_once("class_functions.php");
class ${name} {
//Class properties
function __construct() {
//Constructor
}
public function __get($name) {
if(method_exists($this, 'get' . ucfirst($name))) {
return $this->{'get' . ucfirst($name)};
} else {
if (property_exists($this, $name)) {
$this->{$name} = $value;
} else {
throw new Exception("Undefined property '$name'.");
}
}
}
}
But when I use this template, the new class is created like:
<?php
/**
* Description of ${name}
*
* #author ${user}
*/
include_once("class_functions.php");
class ${name} {
//Class properties
function __construct() {
//Constructor
}
public function __get($name) {
if(method_exists($this, 'get' . ucfirst($name))) {
return $this->{'get' . ucfirst($name)};
} else {
if (property_exists($this, $name)) {
$this->{$name} = $value;
} else {
throw new Exception("Undefined property '$name'.");
}
}
}
}
Does anyone know what I'm doing wrong?
Any help is greatly appreciated! Thanks in advance.

Seems if you save your template using tabs it will strip them. Save your templating with spaces used for indenting they will be filtered into tabs or left as spaces per your netbeans preferences.
You may also have syntax issues that will sometimes through the render off.
Also as I said before, alt + shit + f is your friend in netbeans (auto format)

Workaround:
Create your OWN template file and add it to Netbeans File Templates.
All the indentations magically starts working...
File templates dialog -> Add

Related

Laravel 5.5 Service Provider

I am trying to have a custom service provider with common methods that I am using throughout my application. However I am getting an error target not instantiable. I have the same working fine in Laravel 5.3 but now its not working in Laravel 5.5. Here is my code:
In the app\Helpers folder, I have created a folder Contracts with an interface FrontendContracts.
namespace App\Helpers\Contracts;
Interface FrontendContracts{
public function randomString($len);
}
In app\Helpers I have a class FrontendMethods which implements the interface
namespace App\Helpers;
use App\Helpers\Contracts\FrontendContracts;
class FrontendMethods implements FrontendContracts{
public function randomString($len){
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmonpqrstuvwxyz";
$result = "";
$charArray = str_split($chars);
for($i = 0; $i < $len; $i++){
$randItem = array_rand($charArray);
$result .= "".$charArray[$randItem];
}
$result .= time();
return $result;
}
}
In the app\Providers I have FrontendServiceProvider class with:
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Helpers\FrontendMethods;
class FrontendServiceProvider extends ServiceProvider{
protected $defer = true;
/**
* Bootstrap the application services.
*
* #return void
*/
public function boot(){
//
}
/**
* Register the application services.
*
* #return void
*/
public function register(){
$this->app->bind('App\Helpers\Contracts\FrontendContracts', function(){
return new FrontendMethods();
});
}
/**
* Get the services provided by the provider.
*
* #return array
*/
public function provides(){
return ['App\Helpers\Contracts\FrontendContracts'];
}
}
I have registered the provider in the providers array as:
App\Providers\FrontendServiceProvider::class,
I am getting the error message Unresolvable dependency resolving [$parameter] in class {$parameter->getDeclaringClass()->getName()}
and Target [App\Helpers\Contracts\FrontendContracts] is not instantiable.
Can someone kindly point at to me what I am doing wrong?
I don't think you need the provides() method in your FrontendServiceProvider class. Try removing this.

Large number of queries if templates stored in database, or error on delete from cache

With storing a few templates in a database as found in this answer there is a great increase in the number of database queries. For example, profiler shows 12 of 20 queries on a page were related to searching for templates although none was stored in the database. I was under the impression that searches were done only if a template was not available within the file structure. Is there a method to query the database only if the required template is not in the file structure?
Update 1:
Experiments have shown that commenting out the tags section of the vol.volbundle.twig_database_loader service eliminates the unnecessary queries but can still find a template in the database. Without the tags block the following error occurs
InvalidArgumentException: Template name "new_opp" is not valid (format
is "bundle:section:template.format.engine"
when a template is edited, persisted and an attempt is made to delete its predecessor from cache with the following code. [With the tags block present, the cached template is deleted!] This appears to be the case because the tags block allows the database loader to be found during cache delete.
$fileCache = $this->container->get('twig')->getCacheFilename($name);
if (is_file($fileCache)) {
#unlink($fileCache);
}
So it is odd, then, that the database loader is used by the controller when the block is not present.
services.yml
vol.volbundle.twig_database_loader:
class: Vol\VolBundle\Tools\TwigDatabaseLoader
arguments: [#doctrine.orm.entity_manager]
tags:
- { name: twig.loader }
TwigDatabaseLoader
namespace Vol\VolBundle\Tools;
use \Twig_Error_Loader;
/**
* Description of DatabaseTwigLoader
*
*/
class TwigDatabaseLoader implements \Twig_LoaderInterface
{
private $entityManager;
public function __construct($entityManager)
{
$this->entityManager = $entityManager;
}
public function getSource($name)
{
if (false === $source = $this->getValue('source', $name)) {
throw new Twig_Error_Loader(sprintf('Template "%s" does not exist.', $name));
}
return $source;
}
public function isFresh($name, $time)
{
if (false === $lastModified = $this->getValue('last_modified', $name)) {
return false;
}
return $lastModified <= $time;
}
public function getCacheKey($name)
{
// check if exists
return 'db:' . $name;
}
protected function getValue($column, $name)
{
$conn = $this->entityManager->getConnection();
$sth = $conn->prepare('SELECT '.$column.' FROM template WHERE name = :name');
$sth->execute(array(':name' => (string) $name));
return $sth->fetchColumn();
}
}
Compiler
namespace Vol\VolBundle\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Description of TwigDatabaseLoaderPass
*
*/
class TwigDatabaseLoaderPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$definition = $container->getDefinition('twig');
$definition->addMethodCall('setLoader', array(new Reference('vol.volbundle.twig_database_loader')));
}
}
It turns out that the large number of queries only occurs in dev mode! This was determined by enabling the query log in MySQL. Exercising the editing of a template and then rendering it then reviewing the log showed that only the stored template invoked a template query. None of the other templates appeared in the query log. Case closed!

Cannot save a Doctrine_Collection

I am using Docrine 1.2 with Zend Framework and trying to save a Doctrine Collection.
I am retrieving my collection from my table class with the following code.
public function getAll()
{
return $this->createQuery('e')
->orderBy('e.order ASC, e.eventType ASC')
->execute();
}
I also have the following class to reorder the above event records.
class Admin_Model_Event_Sort extends Model_Abstract
{
/**
* Events collection
* #var Doctrine_Collection
*/
protected $_collection = null;
public function __construct()
{
$this->_collection = Model_Doctrine_EventTypesTable::getInstance()->getAll();
}
public function save($eventIds)
{
if ($this->_collection instanceof Doctrine_Collection) {
foreach ($this->_collection as $record)
{
$key = array_search($record->eventTypeId, $eventIds);
if ($key !== false) {
$record->order = (string)$key;
}
}
return $this->_saveCollection($this->_collection);
} else {
return false;
}
}
}
The _saveCollection method above is as follows
/**
* Attempts to save a Doctrine Collection
* Sets the error message property on error
* #param Doctrine_Collection $collection
* #return boolean
*/
protected function _saveCollection(Doctrine_Collection $collection)
{
try {
$collection->save();
return true;
} catch (Exception $e) {
$this->_errorMessage = $e->getMessage();
OpenMeetings_Logger_ErrorLogger::write('Unable to save Doctrine Collection');
OpenMeetings_Logger_ErrorLogger::vardump($this->_errorMessage);
return false;
}
}
The event id's in the above save method is simply an enumerated array of event id's, I am using the keys of the array to set the sort order of the events using the order field. If I do a var_dump of the collection to an array ($this->_collection->toArray()) I get the correct data. However when I attempt to save the collection I get the following error.
"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order = '0' WHERE eventtypeid = '3'' at line 1"
Is there anyway I can get Doctrine to expand on this error, the full SQL statement would be a start, also if anyone knows as to why this error is occuring then that would be very helpful.
Many thanks in advance
Garry
EDIT
I have modified my above code to try to work one record at a time but I still get the same problem.
public function save($eventIds)
{
foreach ($eventIds as $key => $eventId) {
$event = Model_Doctrine_EventTypesTable::getInstance()->getOne($eventId);
$event->order = (string)$key;
$event->save();
}
}
Ok I have found the problem. I was using the MYSQL reserved word order as a field name thus the error, changed it to sortOrder and the problem went away.
Hope this helps someone with a similar issue.
Garry

symfony2.1 translatable saved, but not retrieved

Basically, I had the same problem as here:
Symfony2 & Translatable : entity's locale is empty
Translations where saved in the ext_translations table, but where not being displayed.
After adding the proposed fix, it DID work.
Today I upgraded from 2.0 to 2.1 I managed to get pretty much everything working so far.
But now my translatables are again not being displayed properly (they ARE still being saved properly).
I think it has something to do with the changes to where and how the users locale is stored in 2.1 compared to 2.0 .. but i cannot figure this one out.
Fixed this by registering a custom listener
namespace XXX;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LocaleListener implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct($defaultLocale = 'en')
{
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
if ($locale = $request->attributes->get('_locale')) {
$request->getSession()->set('_locale', $request->getLocale());
} else {
$request->setDefaultLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
}
static public function getSubscribedEvents()
{
return array(
// must be registered before the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
);
}
}
then changed
$request->setDefaultLocale($request->getSession()->get('_locale', $this->defaultLocale));
to
$request->setLocale($request->getSession()->get('_locale'));
and used
$this->getRequest()->getSession()->set('_locale', 'nl');
to set the locale, translations and translatables now work
hope this also helps someone else ..

SimpleTester on CodeIgniter fails with "Class 'GroupTest' not found"

I'm trying to do a clean install SimpleTester on a new CodeIgniter application, following the instructions here: http://codeigniter.com/wiki/SimpleTester_-_Unit_testing_library
Everything's fine until step 6, when I add "simpletester" to the list of libraries that are autoloaded. As soon as I do that, visiting any page simply results in:
Fatal error: Class 'GroupTest' not found in
/path/to/app/application/libraries/simpletester.php on line 84
Grepping through the code for GroupTest I only see it referenced in comments, and in a readme file which states the following:
The GroupTest has been renamed TestSuite (see below).
It was removed completely in 1.1 in favour of this
name.
I tried modifying line 84 to replace GroupTest with TestSuite, but then I get the following error:
Fatal error: Call to undefined method TestSuite::addTestFile() in
/home/path/to/app/application/libraries/simpletester.php
on line 96
Is this a bug on their end? Has anyone seen this before?
I have run into the same issue. The GroupTest class can be found in test_case.php of version 1.0.1 of SimpleTest:
http://sourceforge.net/projects/simpletest/files/simpletest/simpletest_1.0.1/
Unfortunately, simply inserting v1.0.1 into the libraries folder doesn’t solve all the world’s problems. I no longer get the “Fatal error: Class ‘GroupTest’ not found ...” error, but I do get a segmentation fault and my site no longer works.
I have briefly tried to track down the issue but to no avail.
Note: I also responded on the CodeIgniter Wiki page containing the same question.
I had the same problem with a current project and found that the problem is that GroupTest was replaced with TestSuite which works a little differently.
This is the library code I use:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
$libraryDir = APPPATH . 'libraries/simpletest';
if(!is_dir($libraryDir))
exit("Simpletest must be located in \"$libraryDir\"");
require_once $libraryDir . '/unit_tester.php';
require_once $libraryDir . '/mock_objects.php';
require_once $libraryDir . '/collector.php';
class SimpleTester
{
/**
* What reporter should be used for display.
* Could be either HtmlReporter, SmallReporter, MinimalReporter or ShowPasses.
*/
public $Reporter = 'MinimalReporter';
private $testDir;
private $testTitle;
private $fileExtension;
public function __construct($params = false)
{
$ci =& get_instance();
$ci->config->load('simpletester');
if($params == false) {
$params['runFromIPs'] = $ci->config->item('runFromIPs');
$params['testDir'] = $ci->config->item('testDir');
$params['fileExtension'] = $ci->config->item('fileExtension');
$params['autorun'] = $ci->config->item('autorun');
$params['reporter'] = $ci->config->item('reporter');
$params['testTitle'] = $ci->config->item('testTitle');
}
if(isset($params['runFromIPs']) && strpos($params['runFromIPs'], $ci->input->server('SERVER_ADDR') === FALSE))
{
// Tests won't be run automatically from this IP.
$params['autorun'] = FALSE;
}
// Check if call was an AJAX call. No point in running test
// if not seen and may break the call.
$header = 'CONTENT_TYPE';
if(!empty($_SERVER[$header])) {
// #todo Content types could be placed in config.
$ajaxContentTypes = array('application/x-www-form-urlencoded', 'multipart/form-data');
foreach ($ajaxContentTypes as $ajaxContentType) {
if(false !== stripos($_SERVER[$header], $ajaxContentType))
{
$params['autorun'] = FALSE;
break;
}
}
}
$this->testDir = $params['testDir'];
$this->testTitle = $params['testTitle'];
$this->fileExtension = $params['fileExtension'];
if(isset($params['reporter']))
$this->Reporter = $params['reporter'];
if($params['autorun'] == TRUE)
echo $this->Run();
}
/**
* Run the tests, returning the reporter output.
*/
public function Run()
{
// Save superglobals that might be tested.
if(isset($_SESSION)) $oldsession = $_SESSION;
$oldrequest = $_REQUEST;
$oldpost = $_POST;
$oldget = $_GET;
$oldfiles = $_FILES;
$oldcookie = $_COOKIE;
$test_suite = new TestSuite($this->testTitle);
// Add files in tests_dir
if(is_dir($this->testDir))
{
if($dh = opendir($this->testDir))
{
while(($file = readdir($dh)) !== FALSE)
{
// Test if file ends with php, then include it.
if(substr($file, -(strlen($this->fileExtension)+1)) == '.' . $this->fileExtension)
{
$test_suite->addFile($this->testDir . "/$file");
}
}
closedir($dh);
}
}
// Start the tests
ob_start();
$test_suite->run(new $this->Reporter);
$output_buffer = ob_get_clean();
// Restore superglobals
if(isset($oldsession)) $_SESSION = $oldsession;
$_REQUEST = $oldrequest;
$_POST = $oldpost;
$_GET = $oldget;
$_FILES = $oldfiles;
$_COOKIE = $oldcookie;
return $output_buffer;
}
}
// Html output reporter classes //////////////////////////////////////
/**
* Display passes
*/
class ShowPasses extends HtmlReporter
{
function ShowPasses()
{
$this->HtmlReporter();
}
function paintPass($message)
{
parent::paintPass($message);
print "<span class=\"pass\">Pass</span>: ";
$breadcrumb = $this->getTestList();
array_shift($breadcrumb);
print implode("->", $breadcrumb);
print "->$message<br />\n";
}
function _getCss()
{
return parent::_getCss() . ' .pass {color:green;}';
}
}
/**
* Displays a tiny div in upper right corner when ok
*/
class SmallReporter extends HtmlReporter
{
var $test_name;
function ShowPasses()
{
$this->HtmlReporter();
}
function paintHeader($test_name)
{
$this->test_name = $test_name;
}
function paintFooter($test_name)
{
if($this->getFailCount() + $this->getExceptionCount() == 0)
{
$text = $this->getPassCount() . " tests ok";
print "<div style=\"background-color:#F5FFA8; text-align:center; right:10px; top:30px; border:2px solid green; z-index:10; position:absolute;\">$text</div>";
}
else
{
parent::paintFooter($test_name);
print "</div>";
}
}
function paintFail($message)
{
static $header = FALSE;
if(!$header)
{
$this->newPaintHeader();
$header = TRUE;
}
parent::paintFail($message);
}
function newPaintHeader()
{
$this->sendNoCacheHeaders();
print "<style type=\"text/css\">\n";
print $this->_getCss() . "\n";
print "</style>\n";
print "<h1 style=\"background-color:red; color:white;\">$this->test_name</h1>\n";
print "<div style=\"background-color:#FBFBF0;\">";
flush();
}
}
/**
* Minimal only displays on error
*/
class MinimalReporter extends SmallReporter
{
function paintFooter($test_name)
{
if($this->getFailCount() + $this->getExceptionCount() != 0)
{
parent::paintFooter($test_name);
print "</div>";
}
}
}
Works fine for me I haven't tested all the different reporters yet though. But the default one works fine.
And this is how I use it:
$this->load->library('simpletester');
echo $this->simpletester->Run();
And my config file is:
$config['testDir'] = APPPATH . 'tests';
$config['runFromIPs'] = '127.0.0.1';
$config['reporter'] = 'HtmlReporter';
$config['autorun'] = false;
$config['fileExtension'] = 'php';
$config['testTitle'] = 'My Unit Tests';