how to "escape" the output zf1? - php

How "escape" the output of a string so js on the search line will not work? In Zend Framework1(v. 1.12.3).
<div id="search-box">
<input type="text" placeholder="<?php echo $this->languageText('TEXT_SEARCH_OUR_SITE',"Search Our Site"); ?>" name="query" id="query" />
<div class="search-box-bk"></div>
</div>
I tried this, but it didn't work
placeholder="<?php echo $this->escape($this->languageText('TEXT_SEARCH_OUR_SITE',"Search Our Site"));

Sadly Zend 1 does not have good escaping mechanism by default. ->escape() only uses standard PHP method htmlspecialchars.
You can set what escape method to use in Controller by getting View and using method setEscape('htmlentities') ( setEscape(array('Class/Object','method)))
(response for comment)
In one of my projects I've used Zend2 Escaper. First I've copied Escaper to my folder in Library (i renamed it to Adx_Escaper so it fits in existing library - I'm lazy ;)). Next I've created ViewHelper (resources.view.helperPath.Adx_View_Helper = "Adx/View/Helper/"(application.ini)) with content like this:
class Adx_View_Helper_Escaper extends Zend_View_Helper_Abstract
{
protected $escaper = null;
public function Escaper()
{
if ($this->escaper === null) {
$this->escaper = new Adx_Escaper();
}
return $this;
}
public function html($string)
{
return $this->escaper->escapeHtml($string);
}
/* ... */
Then i could just use $this->escaper()->html('SomeText') (now I see it would be even simpler to just return Escaper in constructor, but works eiter way).

Related

enum class in ternary expression

Enums were introduced to PHP very recently. I'm trying them out in a laravel project. I've got my enum class here:
namespace App\Enums;
enum AlertType
{
case SUCCESS;
case ERROR;
}
I'm trying to create an alert class that will take the enum in the constructor to set the severity of the alert, which will decide what colour it is rendered as to the user. Here is that class:
<?php
namespace App\View\Components;
use App\Enums\AlertType;
use Illuminate\View\Component;
class Alert extends Component
{
public string $contextClass;
public function __construct(public string $message, AlertType $alertType = AlertType::SUCCESS)
{
$this->setContextClassFromAlertType($alertType);
}
public function setContextClassFromAlertType(AlertType $alertType)
{
$this->contextClass = ($alertType === AlertType::SUCCESS ? 'success' : 'error');
}
public function getClassListFromType()
{
return [
'border-' . $this->contextClass,
'text-' . $this->contextClass
];
}
public function render()
{
return view('components.alert', [
'class' => implode(' ', $this->getClassListFromType())
]);
}
}
This alert will be used in a login form which is built using Laravel Livewire and blade components:
<form class="grid grid-cols-min-auto-1 gap-x-2" id="login" action="/login" method="post">
<x-alert :message="$errorMessage"/>
#csrf
<label for="email" class="mb-2 text-lg text-sans w-min mt-2 font-thin">Email</label>
<x-basic-input wire:model="email" placeholder="{{ $emailPlaceholder }}"/>
<label for="password" class="mb-2 text-lg text-sans w-min mt-2 font-thin">Password</label>
<x-basic-input wire:model="password"/>
</form>
When I come to display the login form I am getting the following error:
Cannot instantiate enum App\Enums\AlertType (View: /resources/views/livewire/forms/login.blade.php)
I think there is something wrong with my enum usage in the Alert component, but I'm not sure where. Can anyone point me in the right direction. I've looked at the rfc for enums but I can't see anything obvious that I'm doing wrong
I was able to reproduce this error; in my case the stack trace led back to the barryvdh/laravel-debugbar package, not sure if this is the same for you. I was able to resolve it by changing the enum to a backed enum.
I'd recommend making this change regardless, as I expect in a lot of cases strings will be easier to work with than enum instances. (Though TBH this looks like trying to use a new feature just because it's there, not because it makes sense.)
namespace App\Enums;
enum AlertType: string
{
case SUCCESS = 'success';
case ERROR = 'error';
case INFO = 'info';
}
In a backed enum, each item has a string representation that can be accessed using the value property, which we do in the constructor:
<?php
namespace App\View\Components;
use App\Enums\AlertType;
use Illuminate\View\Component;
class Alert extends Component
{
public string $contextClass;
public function __construct(
public string $message,
AlertType $alertType = AlertType::SUCCESS,
)
{
$this->contextClass = $alertType->value;
}
public function getClassListFromType()
{
return [
'border-' . $this->contextClass,
'text-' . $this->contextClass
];
}
public function render()
{
return view('components.alert', [
'class' => implode(' ', $this->getClassListFromType())
]);
}
}
You're now able to use the from() or tryFrom() methods which can add flexibility with alert types saved in a variable. For example:
<x-alert :message="$errorMessage" :type="App\Enums\AlertType::from($errorType)"/>
I think the problem here is due to dependency injection. In the constructor I'm typehinting an enum, so the Laravel container is trying to create an instance of that class to pass in which doesn't work because enums are instantiable.
If I update the container to manually resolve the typehinted instance like this:
$this->app->bind(Alert::class, function ($app) {
return new Alert('this is a message', AlertType::SUCCESS);
});
Then the issue is resolved and it works as expected. I'll need to change the way I'm using enums here as #miken32 suggests to use a backed enum and rely on the strings instead. Otherwise I'd need to override the container injection for every method where I wanted to pass an enum.

Passing multiple url parameters in laravel 4

1
I need to pass 3 parameters (name,path,number) in update function
Here,below is the code for the same,Kindly, help me in the same.Help is appreciated
Routes:
Route::put('update_document_details/{name}/{path}/{number}',array('as'=>'update_document_details','uses'=>'AuthorsController#update_document_details'));
Controller:
public function update_document_details($name,$path,$number)
{
$document_details=Response::json(Author::update_document_details_by_id_Call($name,$path,$number));
return $document_details;
}
Model:
public static function update_document_details_by_id_Call($name,$path,$number)
{
return DB::select("call update_document_details_by_id('$name','$path','$number')");
}
I really don't see a reason why the above code should not work, but you can try this as an alternative. This helps you not to pass your parameters on the URL if you wish to change.
Route
Route::put('/update_document_details','AuthorsController#update_document_details');
Form
{{Form::open(array('url'=>'update_document_details','method'=>'put'))}}
<input type="text" name="name"/>
<input type="text" name="path"/>
<input type="text" name="numbe"/>
{{Form::close()}}
Controller
public function update_document_details()
{
$name = Input::get('name');
$path = Input::get('path');
$number = Input::get('number');
$response = Author::update_document_details_by_id_Call($name,$path,$number);
return Response::json($response);
}
Couple of suggestions here, this might be helpful or may be not.
Why not use a resource controller instead of defining a seperate put route.
When asking a question, try to give as much information as possible, so that it is easy for us to help you in all regards.

Zend Forms email element changing to text

I'm trying to create an input of type email in Zend Forms but I cannot accomplish the desired result.
I've created a custom class:
namespace AAA\Forms\Elements;
class Email extends \Zend_Form_Element_Text
{
function __construct($name, $label, $required)
{
parent::__construct($name);
$this->setAttrib('type', 'email');
$this->setLabel($label)->setRequired($required);
}
}
And then I'm using it like this:
class Application_Form_Register extends Zend_Form
{
public function init()
{
// …
$email = new AAA\Forms\Elements\Email('email', 'E-mail:', true);
$this->addElement($email);
// …
}
}
And what I get is:
<input type="text" name="email" id="email" value="" type="email">
Note the two type parameters.
I have set HTML5 doctype ($documentType = new Zend_View_Helper_Doctype(); $documentType->doctype('HTML5'); in Bootstrap.php) and I have also tried this:
function __construct($name, $label, $required)
{
$options = array();
$options['type'] = 'email';
parent::__construct($name, $options);
// …
}
I've read Zend HTML5 Form element types but none of the answers work. I've tried also Glitch library but the result is the same.
Anyone knows how to force Zend Framework to use HTML5 form controls?
You will need to implement your own view helper for rendering the email form element as well.
Zend_Form_Element_Text uses the formText view helper (Zend/View/Helper/FormText.php) to render the HTML input and it is hard coded to output <input type="text" when rendering the element.
Two possible ways to handle this would be to:
Remove the ViewHelper decorator from the element and use the ViewScript helper to render the element.
Make your own view helper formEmail almost identical to formText except that it outputs type="email"; and set the public $helper property in your Element class to formEmail. You will have to register the path to the formEmail helper using Zend_View::addHelperPath() so it will be found by the ViewHelper decorator.

Different form formatter for embeded form?

I'm trying to change the form formatter of the embeded form. Is it possible to approach something like this?
class sfOuterForm extends sfForm {
public function configure()
{
$innerForm = new sfForm();
$this->embedForm('inner', $innerForm);
$this->getWidgetSchema()->setFormFormatter('list');
$this->getEmbeddedForm('inner')->getWidgetSchema()->setFormFormatterName('table');
}
}
i'm expecting the following:
echo (new sfOuterForm())
outputs:
<li><label>Outer Label</label><input type="text" /></li>
<li>
<table>
<tr><td><label>Inner Label</label></td><td><input type="text" /></td></tr>
</table>
</li>
Once a form is embedded, it's original widget schema and validator schema do nothing - they've been merged into the top level schemas. Thus, you need to set the form formatter before embedding:
$this->getWidgetSchema()->setFormFormatter('list');
$innerForm = new sfForm();
$innerForm->getWidgetSchema()->setFormFormatterName('table');
$this->embedForm('inner', $innerForm);
It's worth a look into sfForm::embedForm to see what's going on internally.
I'll answer my question by myself :)
The problem arised when i tried to change formatter for relation's embedded forms. I solved this as follows:
class sfOuterForm extends sfForm {
public function configure()
{
$innerForm = new sfForm();
$this->embedRelation('relationName');
$this->getWidgetSchema()->setFormFormatter('list');
$this->getEmbeddedForm('relationName')->getWidgetSchema()->setDefaultFormFormatterName('table');
}
}
Hope this will help someone :)

Do I need to hack ZendFramework1.10.8/Doctrine1.2.2 to get model generated?

I've started reading on zend framework and it's use with Doctrine and have implemented a small project to grasp the understanding.I've come to a point where i needed my model generated as in having a generate script like the one suggested in Doctrine 1.2.2 pdf manual.After few unsuccessful attempts like
Class 'sfYaml' not found in
G:\php_document\zendworkspace\BookingManager\library\doctrine\Doctrine\Parser\Yml.php
on line 80
i've googled and found out what people are doing about that.
To me it sounds too much the fact of having a command line script to do that work.So my question is do i really need the command line or i fail to load something is my application.ini file to get the error up there?
my testerController is like this:
class Testing_TesterController extends Zend_Controller_Action {
public function init(){
$optionDoctrine = Zend_Registry::get("config")->toArray();
$this->config = $optionDoctrine["doctrine"];
}
public function generateAction() {
$this->view->drop="dropping database............";
Doctrine_Core::dropDatabases();
$this->view->create = "creating database........";
Doctrine_Core::createDatabases();
$this->view->models = "generating models....";
//things started breadking from this line Doctrine_Core::generateModelsFromYaml("$this->config[yaml_schema_path]","$this->config[models_path]");
// $this->view->tables = "creating tables.......";
// Doctrine_Core::createTablesFromModels($this->config["models_path"]);
// $this->view->success = "tables and model successfully generated";
// $optionobject= Zend_Registry::get("config")->toArray();
// $this->view->generate =$optionobject["doctrine"]["yaml_schema_path"];
}
public function testAction(){
$dbs= Doctrine_Manager::connection()->import->listDatabases();
$this->view->test = $dbs;
//$this->view->test = "test";
}
}
the generate view is like this
<h1>My Manager:: generate page</h1><br>
<div style="text-align: left"><?php echo $this->drop; ?></div>
<div style="text-align: left"><?php echo $this->create; ?></div>
<div style="text-align: left"><?php var_dump($this->models); ?></div>
<div style="text-align: left"><?php echo $this->tables; ?></div>
here is my bootstrap class
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
protected function _initDoctrine(){
require_once 'doctrine/Doctrine.php';
$this->getApplication()->getAutoloader()->pushAutoloader(array('Doctrine','autoload'),"Doctrine");
//$this->getApplication()->getAutoloader()->pushAutoloader(array('Doctrine','modelsAutoload'),"Doctrine");
$manager = Doctrine_Manager::getInstance();
//$manager->setAttribute(Doctrine_Core::ATTR_MODEL_LOADING,Doctrine_Core::MODEL_LOADING_AGGRESSIVE);
$manager->setAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE,true);
$doctrineConfig = $this->getOption('doctrine');
$conn = Doctrine_Manager::connection($doctrineConfig['dsn'],'doctrine');
return $conn;
}
protected function _initDoctrineConfig(){
$conf = new Zend_Config($this->getOptions(),true);
Zend_Registry::set('config',$conf);
return $conf;
}
}
I've also adopted the use of modules which seems to complicate my situation so what do you think is the best to go with? thanks for reading
You need to grab the sfYaml component and install it. I Thought it was int the Doctrine svn repo as an svn:external but maybe not... you can get it from the Symfony components site.
Im not sure what tutorial youre following but if you drop:
http://svn.symfony-project.com/components/yaml/branches/1.0/
into your library folder as sfYaml and add library/sfYaml to the include path you should be fine assuming youve gotten everything else set up correctly.
Also whay is your command line script using Zend_Controller stuff? Shouldnt you be using the Zend_Tool_Framework infrastructure or writing a completely custom script? Thats how I've done it in the past anyway...

Categories