How to get smarty file tokens? - php

How to get smarty(test.tpl) file tokens using the smarty-php/smarty-lexer package. From the documentation, I can’t understand how to do this, since I don’t have experience in parsing a file into tokens.
use Smarty_Internal_SmartyTemplateCompiler;
use Smarty_Internal_Templatelexer;
use Smarty;
use Smarty_Internal_Templateparser;
$smarty = new Smarty();
$templateSource = file_get_contents('path/to/template.tpl');
$lexer = new Smarty_Internal_Templatelexer();
$parser = new Smarty_Internal_Templateparser();
$compiler = new Smarty_Internal_SmartyTemplateCompiler($lexer, $parser, $smarty);
$lexer = new Smarty_Internal_Templatelexer($templateSource, $compiler);
$tokens = $lexer->tokenize();
This is one of the methods that I tried, I tried different approaches, nothing works.

Related

How can you use the ResourceWatcher bundle from YoSymfony?

I am trying to make a file watcher where, when you add, update or delete a file, you can see the files updates in a database. I'm using the framework Symfony4 and a bundle from it called ResourceWatcher from YoSymfony. This bundle uses the Finder bundle from Symfony to find files in the directories specified and then, the watcher compares the cache and the new file to see if there are any changes. When I use a method with the watcher which returns a path array, when I try to see the array, it returns null. How am I suppose to use these methods and their returns?
I put the var_dump everywhere to see that the problem comes from the findChanges()->getUpdatedFiles() and getNewFiles();
//OLD CODE
$finder = new Finder();
$finder->files()
->name('*.csv')
->in('%kernel.root_dir%/../src/data/');
//watcher
$hashContent = new Crc32ContentHash();
$resourceCache = new ResourceCachePhpFile('cache-key.php');
$watcher = new ResourceWatcher($resourceCache, $finder, $hashContent);
$watcher->initialize();
if($watcher->findChanges()->hasChanges()){
if($watcher->findChanges()->getNewFiles() === null){
$paths = $watcher->findChanges()->getUpdatedFiles();
}
else{
$paths = $watcher->findChanges()->getNewFiles();
}
$propertyAccessor = PropertyAccess::createPropertyAccessor();
var_dump($propertyAccessor->getValue($paths, '[first_name]'));
die();
}
I'd like to be able to see the paths, convert them into string and use that into my other method to make the data appear in my database.
In my var_dump, I get NULL in terminal.
EDIT:[first_name] is in my csv-file, you can dump $paths directly.
//NEW CODE
$finder = new Finder();
$finder->files()
->name('*.csv')
->in('%kernel.root_dir%/../src/data/');
//watcher
$hashContent = new Crc32ContentHash();
$resourceCache = new ResourceCachePhpFile('cache-key.php');
$watcher = new ResourceWatcher($resourceCache, $finder, $hashContent);
$watcher->initialize();
$changes = $watcher->findChanges();
if(!empty($changes->getUpdatedFiles())){
$updatedFilesPath = $changes->getUpdatedFiles();
$pathString = implode($updatedFilesPath);
$reader = Reader::createFromPath($pathString);
}
elseif(!empty($changes->getNewFiles())){
$newFilesPath = $changes->getNewFiles();
$pathString = implode($newFilesPath);
$reader = Reader::createFromPath($pathString);
}
else{
return;
}
$results = $reader->fetchAssoc();
So it looks like that as soon as you use the method findChanges()->hasChanges(), it tells the watcher that there is some changes but then it resets and there's no changes anymore in the watcher so it's pointless to use
$paths = $watcher->findChanges()->getUpdatedFiles();
since it will always return nothing because of the reset. I had to make a variable with the changes inside so that I could re-use the changes further down.
Details in code...

PHP Calling dynamic functions

Im trying to figure out how to call functions based on what a user clicks on a form. But im not sure if im doing it right.
I have a number of classes, lets say 3 for different ways to connect to a site, the user clicks on which one they would like.
FTP
SFTP
SSH
Which i have named 'service' in my code.
I don't want to run a whole bunch of IF statements, i would rather try and build the call dynamically.
What i have at the moment is as follows
$ftp_backup = new FTPBackup;
$sftp_backup = new SFTPBackup;
$ssh_backup = new SSHBackup;
$service = $request->input('service') . '_backup';
$service->testConn($request);
Im getting the following error
Call to a member function testConn() on string
Im not sure im doing this right.
Any help would be greatly appreciated.
Thanks
First of all $service is a string on which You cannot call method, because it is not an object (class instance).
I think it is a great example of where You can use Strategy Pattern which look like that:
class BackupStrategy {
private $strategy = null;
public function __construct($service_name)
{
switch ($service_name) {
case "ftp":
$this->strategy = new FTPBackup();
break;
case "sftp":
$this->strategy = new SFTPBackup();
break;
case "ssh":
$this->strategy = new SSHBackup();
break;
}
}
public function testConn()
{
return $this->strategy->testConn();
}
}
And then in place where You want to call it You call it by:
$service = new BackupStrategy($request->input('service'));
$service->testConn($request);
I suggest You to read about Design Patterns in OOP - it will help You a lot in the future.
How about this:
$ftp_backup = new FTPBackup;
$sftp_backup = new SFTPBackup;
$ssh_backup = new SSHBackup;
$service = $request->input('service') . '_backup';
${$service}->testConn($request);
This is called "Variables variable": http://php.net/manual/en/language.variables.variable.php
// Create class name
$className = $request->get('service') . '_backup';
// Create class instance
$service = new $className();
// Use it as you want
$service->testConn($request);

Instantiating class by string

i have this code.
$contrl = stripslashes($this->params['controller'].'Controller'); //PostController
$obj = new $contrl(); // What's won't work
//this don't work too
$contrl = 'PostController';
$obj = new $contrl();
//but this work good
$obj = new PostController();
I dont understand why it happen and how I can fix it?
I haven't tested it, but I'm pretty sure it should be done like this (as per the doc):
$obj = new $contrl;

Symfony 1.4 not loading sfTestFunctional failing with class not found

I've done my functional tests and now I want to run them. However, every time I run them I get sfTestFunctional class not found.
As far as I can tell the functional.php bootstrap is not autoloading the classes from the framework. Any reason why this could be?
This is my functional bootstrap
// guess current application
if (!isset($app))
{
$traces = debug_backtrace();
$caller = $traces[0];
$dirPieces = explode(DIRECTORY_SEPARATOR, dirname($caller['file']));
$app = array_pop($dirPieces);
}
require_once dirname(__FILE__).'/../../config/ProjectConfiguration.class.php';
$configuration = ProjectConfiguration::getApplicationConfiguration($app, 'test', isset($debug) ? $debug : true);
sfContext::createInstance($configuration);
// remove all cache
sfToolkit::clearDirectory(sfConfig::get('sf_app_cache_dir'));
$doctrine = new sfDoctrineDropDbTask($configuration->getEventDispatcher(), new sfAnsiColorFormatter());
$doctrine->run(array(), array("--no-confirmation","--env=test"));
$doctrine = new sfDoctrineBuildDbTask($configuration->getEventDispatcher(), new sfAnsiColorFormatter());
$doctrine->run(array(), array("--env=test"));
$doctrine = new sfDoctrineInsertSqlTask($configuration->getEventDispatcher(), new sfAnsiColorFormatter());
$doctrine->run(array(), array("--env=test"));
This is what is in my the functional tests
include(dirname(__FILE__).'/../../bootstrap/functional.php');
$browser = sfTestFunctional(new sfBrowser());
Doctrine_Core::loadData(sfConfig::get('sf_test_dir').'/fixtures/fixtures_initial.yml');
Ok. So after banging my head against the wall, I found a solution.
For some reason within the test environment custom filters are not autoloaded. The solution is to add require_once for all the custom filters to the ProjectConfiguration file. Here is the example of what I did:
if(sfConfig::get('sf_environment') == 'test' && sfConfig::get('sf_app') == 'frontend')
{
require_once sfConfig::get('sf_app_lib_dir').'/myFilter.class.php';
require_once sfConfig::get('sf_app_lib_dir').'/myotherFilter.class.php';
require_once sfConfig::get('sf_app_lib_dir').'/lovefiltersFilter.php';
require_once sfConfig::get('sf_app_lib_dir').'/eventsManagement.class.php';
require_once sfConfig::get('sf_test_dir').'/ProdPadTestFunctional.class.php';
}
I also had to add my custom testFuntional class as well. This might be more elegantly done using the autoload.yml file.
I spot the problem:
$browser = sfTestFunctional(new sfBrowser());
You should write:
$browser = new sfTestFunctional(new sfBrowser());

How do i remove a file from Rackspace's Cloudfiles with their api?

I was wondering how do i remove a file from Rackspace's Cloudfiles using their API?
Im using php.
Devan
Use the delete_object method of CF_Container.
Here is my code in C#. Just guessing the api is similar for php.
UserCredentials userCredientials = new UserCredentials("xxxxxx", "99999999999999");
cloudConnection = new Connection(userCredientials);
cloudConnection.DeleteStorageItem(ContainerName, fileName);
Make sure you set the container and define any sudo folder you are using.
$my_container = $this->conn->get_container($cf_container);
//delete file
$my_container->delete_object($cf_folder.$file_name);
I thought I would post here since there isn't an answer marked as the correct one, although I would accept Matthew Flaschen answer as the correct one. This would be all the code you need to delete your file
<?php
require '/path/to/php-cloudfiles/cloudfiles.php';
$username = 'my_username';
$api_key = 'my_api_key';
$full_object_name = 'this/is/the/full/file/name/in/the/container.png';
$auth = new CF_Authentication($username, $api_key);
$auth->ssl_use_cabundle();
$auth->authenticate();
if ( $auth->authenticated() )
{
$this->connection = new CF_Connection($auth);
// Get the container we want to use
$container = $this->connection->get_container($name);
$object = $container->delete_object($full_object_name);
echo 'object deleted';
}
else
{
throw new AuthenticationException("Authentication failed") ;
}
Note that the "$full_object_name" includes the "path" to the file in the container and the file name with no initial '/'. This is because containers use a Pseudo-Hierarchical folders/directories and what end ups being the name of the file in the container is the path + filename. for more info see http://docs.rackspace.com/files/api/v1/cf-devguide/content/Pseudo-Hierarchical_Folders_Directories-d1e1580.html
Use the method called DeleteObject from class CF_Container.
The method DeleteObject of CF_Container require only one string argument object_name.
This arguments should be the filename to be deleted.
See the example C# code bellow:
string username = "your-username";
string apiKey = "your-api-key";
CF_Client client = new CF_Client();
UserCredentials creds = new UserCredentials(username, apiKey);
Connection conn = new CF_Connection(creds, client);
conn.Authenticate();
var containerObj = new CF_Container(conn, client, container);
string file = "filename-to-delete";
containerObj.DeleteObject(file);
Note Don´t use the DeleteObject from class *CF_Client*

Categories