Deprecated: version_compare(): Passing null to parameter #2 ($version2) of type string is deprecated in /var/www/vhosts/shatteredmultimedia.com.au/httpdocs/wp-content/plugins/Ultimate_VC_Addons/Ultimate_VC_Addons.php on line 1485

Deprecated: Constant FILTER_SANITIZE_STRING is deprecated in /var/www/vhosts/shatteredmultimedia.com.au/httpdocs/wp-content/plugins/wordpress-seo/src/conditionals/third-party/elementor-edit-conditional.php on line 22

Deprecated: Constant FILTER_SANITIZE_STRING is deprecated in /var/www/vhosts/shatteredmultimedia.com.au/httpdocs/wp-content/plugins/wordpress-seo/src/conditionals/third-party/elementor-edit-conditional.php on line 28
Shattered Multimedia – Built with love https://www.shatteredmultimedia.com.au/ Built with love Thu, 03 Nov 2016 11:53:58 +0000 en-AU hourly 1 https://www.shatteredmultimedia.com.au/wp-content/uploads/2016/10/cropped-sm_favicon-1-32x32.jpg Shattered Multimedia – Built with love https://www.shatteredmultimedia.com.au/ 32 32 AWS installing CLI – Fix El Capitan issues https://www.shatteredmultimedia.com.au/aws-installing-cli-fix-el-capitan-issues/ https://www.shatteredmultimedia.com.au/aws-installing-cli-fix-el-capitan-issues/#respond Tue, 27 Oct 2015 11:39:08 +0000 https://www.shatteredmultimedia.com.au/?p=192 After updating to El Capitan with the latest Mac OSX, you may receive an error when trying to install the AWS CLI by trying: The cause of this is that El Capitan ships with the package six 1.4.1 installed and it can’t uninstall this as it’s considered core. You can bypass this step by telling…

The post AWS installing CLI – Fix El Capitan issues appeared first on Shattered Multimedia - Built with love.

]]>
After updating to El Capitan with the latest Mac OSX, you may receive an error when trying to install the AWS CLI by trying:

pip install aws cli

Installing collected packages: six, python-dateutil, docutils, botocore, awscli
  Found existing installation: six 1.4.1
    DEPRECATION: Uninstalling a distutils installed project (six) has been deprecated and will be removed in a future version. This is due to the fact that uninstalling a distutils project will only partially uninstall the project.
    Uninstalling six-1.4.1:
Exception:
Traceback (most recent call last):

The cause of this is that El Capitan ships with the package six 1.4.1 installed and it can’t uninstall this as it’s considered core.

You can bypass this step by telling your little pip to ignore installed packaged.

sudo pip install awscli --ignore-installed

The AWS CLI will now be available through terminal.

The post AWS installing CLI – Fix El Capitan issues appeared first on Shattered Multimedia - Built with love.

]]>
https://www.shatteredmultimedia.com.au/aws-installing-cli-fix-el-capitan-issues/feed/ 0
We love using Gravity Forms https://www.shatteredmultimedia.com.au/love-using-gravity-forms/ https://www.shatteredmultimedia.com.au/love-using-gravity-forms/#respond Wed, 09 Jul 2014 11:40:48 +0000 https://www.shatteredmultimedia.com.au/?p=194 I’d like to show my support for the Gravity Forms Plugin created by the team at RocketGenius. I’ve tried many form plugins for WordPress and this one beats them all. It’s not the cheapest, but you get what you pay for with Gravity Forms. Our clients love how easy it is to edit forms and…

The post We love using Gravity Forms appeared first on Shattered Multimedia - Built with love.

]]>
I’d like to show my support for the Gravity Forms Plugin created by the team at RocketGenius.

I’ve tried many form plugins for WordPress and this one beats them all. It’s not the cheapest, but you get what you pay for with Gravity Forms.

Our clients love how easy it is to edit forms and view and export user entries.

As developers, we love the documentation provided for us to really extend forms behind the scenes, giving us a large degree of flexibility.

The built-in integration with Campaign Monitor & Mailchimp gives clients access to add users to their campaign lists without even asking us developers.

So if you’re looking to use a form plugin for WordPress, I highly recommend Gravity Forms. Click the below link for further information.

Gravity Forms Plugin for WordPress

The post We love using Gravity Forms appeared first on Shattered Multimedia - Built with love.

]]>
https://www.shatteredmultimedia.com.au/love-using-gravity-forms/feed/ 0
WordPress: adding external link capability to admin menu items https://www.shatteredmultimedia.com.au/wordpress-adding-external-link-capability-admin-menu-items/ https://www.shatteredmultimedia.com.au/wordpress-adding-external-link-capability-admin-menu-items/#respond Tue, 15 Oct 2013 11:42:07 +0000 https://www.shatteredmultimedia.com.au/?p=196 I stumbled across this fantastic built-in feature of WordPress today, which allows you to enable hidden functionality to your menu items. If you’ve ever created social media icons or external links and wanted to target=”blank” them, well look no further at this page – http://wordpress.org/support/topic/add-target-element-to-menu-editor. Some great comments too

The post WordPress: adding external link capability to admin menu items appeared first on Shattered Multimedia - Built with love.

]]>
I stumbled across this fantastic built-in feature of WordPress today, which allows you to enable hidden functionality to your menu items.

If you’ve ever created social media icons or external links and wanted to target=”blank” them, well look no further at this page – http://wordpress.org/support/topic/add-target-element-to-menu-editor.

Some great comments too

The post WordPress: adding external link capability to admin menu items appeared first on Shattered Multimedia - Built with love.

]]>
https://www.shatteredmultimedia.com.au/wordpress-adding-external-link-capability-admin-menu-items/feed/ 0
GIT Basics https://www.shatteredmultimedia.com.au/git-basics/ https://www.shatteredmultimedia.com.au/git-basics/#respond Fri, 08 Jun 2012 11:43:19 +0000 https://www.shatteredmultimedia.com.au/?p=199 If you’re a web developer and you’re not using Distributed Version Control System (DVCS), you fall into two categories: 1) You are scared of change or 2) You have found something even better such as flying over the moon on a spoon. DVCS’s allow everyone to all have their own clones/copies of the source code,…

The post GIT Basics appeared first on Shattered Multimedia - Built with love.

]]>
If you’re a web developer and you’re not using Distributed Version Control System (DVCS), you fall into two categories:
1) You are scared of change or
2) You have found something even better such as flying over the moon on a spoon.

DVCS’s allow everyone to all have their own clones/copies of the source code, and branch to their hearts content. You can commit your changes locally and then push them back to a central cloud hosted service when you feel the code is of value to others, then other users can then fetch your updates and enhance the source code.

More details on this article at: http://blog.mrpony.com.au/git-basics/

The post GIT Basics appeared first on Shattered Multimedia - Built with love.

]]>
https://www.shatteredmultimedia.com.au/git-basics/feed/ 0
Assigning global attributes for select boxes in Silverstripe https://www.shatteredmultimedia.com.au/assigning-global-attributes-select-boxes-silverstripe/ https://www.shatteredmultimedia.com.au/assigning-global-attributes-select-boxes-silverstripe/#respond Sat, 05 May 2012 11:48:20 +0000 https://www.shatteredmultimedia.com.au/?p=201 Recently, I was working on a Silverstripe project where the client requested that they have a contact form, and based on the state/region that was chosen in a select box, an email would be sent to that regions email. Another example of this would be to send an email to a certain department such as…

The post Assigning global attributes for select boxes in Silverstripe appeared first on Shattered Multimedia - Built with love.

]]>
Recently, I was working on a Silverstripe project where the client requested that they have a contact form, and based on the state/region that was chosen in a select box, an email would be sent to that regions email. Another example of this would be to send an email to a certain department such as sales, technical support, advertising, general inquiries etc.
I could have assigned the values with the contact form itself, but when the client informed me that each state did their own email campaigns, it became apparent that a newsletter sign up form would require the same email information based on state/region.

This example will allow your administrator to update these email addresses down the track, by using the CMS, and not require modifying any PHP code.

Ok, so the first thing we want to do is is make sure that the DataObjectManager plugin is installed. This is a favourite of mine because it extends the ComplexTableField class and adds new features such as datepickers and just looks and works better.
Once installed we need to log in to the CMS admin, and from there we need to make sure the main website config item is selected in the Page tree (it’s the one with the Earth icon). Our end result in the administration panel is to create a new tab titled Email Locations as per the image below.

Next step is to create our LocationEmail class in /mysite/code/LocationEmail.php

<php // This class will create a table in the database titled LocationEmail class LocationEmail extends DataObject { // Create two fields to be added to the database table to be used for reference static $db = array( 'LocationName' => 'Text',
    'LocationEmailAddress' => 'Text'
  );

  // Set up the join that 1 Location can join to one SiteConfig object
  static $has_one = array(
    'MyLocation' => 'SiteConfig'
  );

  // Add input fields to be used in the admin panel, and link the fieldnames for which to store the values to
  function getCMSFields_forPopup() {
    $fields = new FieldSet();

    $fields->push( new TextField('LocationName', 'Location name' ) );
    $fields->push( new EmailField('LocationEmailAddress', 'Email' ) );

    return $fields;

  }

}

You will have to add a line in your _config.php in the root folder to inform Silverstripe of the extra configuration file to load

// Place this near the bottom of your _config.php file
// Read a new configuration file in /mysite/code/CustomSiteConfig.php
DataObject::add_extension('SiteConfig', 'CustomSiteConfig');

Now we have to modify (or add) our extended config file to allow us to add a new tab to the global site configuration in admin. /mysite/code/CustomSiteConfig.php

<?php class CustomSiteConfig extends DataObjectDecorator { function extraStatics() { return array( 'has_many' => array(
        'MyLocation' => 'LocationEmail'
      )
    );
  }
}

We create an extraStatics function which will allow us to add new global settings. In this function are defining that we would like many LocationEmail(‘s) to display in our one objectManager. Next we will then add the function to display the content within the tab.

public function updateCMSFields(FieldSet &$fields)
{
  $manager = new DataObjectManager(
    $this->owner,
    'MyLocation',
    'LocationEmail',
    array(
      'LocationName' => 'Location name',
      'LocationEmailAddress' => 'Email'
    ),
    'getCMSFields_forPopup'
  );
  $manager->setSourceID($this->owner->ID);
  $manager->setAddTitle( 'a new location' );

  $fields->addFieldToTab('Root.EmailLocations', $manager );

  return $fields;
}

You should now have a workable tab item in your site configuration that you can Create, read, update, delete multiple Email Locations all communicating to the database.

Now how to we display this information in the form displayed at the beginning?
That’s where the fun begins.
I’m assuming you know how to create a new page titled contact. Create and edit the /mysite/ContactPage.php.

class ContactPage_Controller extends Page_Controller
{
  /**
   * ContactForm the
   * @return Form
   */
  function ContactForm() {
    Requirements::customScript('
      jQuery(document).ready(function() {
        jQuery("#Form_ContactForm").validate({
          rules: {
            FirstName: "required",
            Surname: "required",
            Location: "required",
            EmailAddress: {
              required: true,
              email: true
            }
          },
          messages: {
            FirstName: "Please enter a valid first name",
            Surname: "Please enter a valid last name",
            Location: "Please enter a valid location",
            EmailAddress: "Please enter a valid email address"
          }
        });
      });
    ');

    $locations = DataObject::get("LocationEmail", '', 'LocationName')->map("ID", "LocationName", "Please Select");

    // Create fields
    $fields = new FieldSet(
      new TextField('FirstName', 'First name'),
      new TextField('Surname', 'Surname'),
      new EmailField('EmailAddress', 'Email address'),
      new DropdownField('Location', 'Location', $locations),
      new TextareaField('Message', 'Message', 3)
    );
    // Create action
    $actions = new FieldSet(
      new FormAction('SendContactForm', 'Submit')
    );
    // Create Validators
    $validator = new RequiredFields('FirstName', 'Surname', 'Location', 'EmailAddress', 'Captcha');
    $validator->setJavascriptValidationHandler('none');

    $form = new Form($this, 'ContactForm', $fields, $actions, $validator);
    $form->setTemplate('Forms/ContactrForm');
    return $form;
  }

There is nothing really new to the code above, it follows a standard way that forms are written and validated using the bassistance jquery validation techniques.
The main thing to note is line 30 where we declare the $locations array. This line will retrieve all the fields from the EmailLocations table and will map the LocationName field to the ID. This will be used as the key->value pair in our select box.
Line 37 declares our select box called location, and populates it with the $locations array.

In themes folder themeName/templates/Forms/ContactEmail.ss,  the locations field can now be accessed (note that below is a snippet from the entire form template)





<li id="Location" class="field text">
  <label for="{$FormName}_Location">Location:</label>
  $dataFieldByName(Location)
</li>





By now you can display the contact form, and submit it – but nothing happens, the last step is sending the email to the correct Location.

function SendNewsletterForm($data) {
  // Find the email address of the user
  $email_destination = DataObject::get_by_id("LocationEmail", $data['Location']);
  $emailDestinationName = $email_destination->LocationName;

  //Set data for email to State/Location
  $From = $data['EmailAddress'];
  $Name = $data['FirstName'] . ' ' . $data['Surname'];
  $To = $email_destination->LocationEmailAddress;
  $Subject = "TESTING NEW WEBSITE:";
  $email = new Email($From, $To, $Subject);
  //set template
  $email->setTemplate('ContactEmail');
  //populate template
  $email->populateTemplate($data);
  // Populate the newly found Location name
  $email->populateTemplate(array('EmailDestinationName' => $emailDestinationName));
  //send mail
  $success = $email->send();

  //Set data for email to recipient
  $From = $email_destination->LocationEmailAddress;
  $To = $data['EmailAddress'];
  $email_recipient = new Email($From, $To, $Subject);
  //set template
  $email_recipient->setTemplate('ContactEmail');
  //populate template
  $email_recipient->populateTemplate($data);
  // Populate the newly found Location name
  $email_recipient->populateTemplate(array('EmailDestinationName' => $emailDestinationName));
  $success = $email_recipient->send();

  //return to submitted message
  Director::redirect($this->Link("?contactformsuccess=1"));
}

Lines 3, 4, and 17 are the only related location information that I feel needs to be explained. On line 3, we query the LocationEmail table for the row where the id equals the form key that was passed for the Location select box. We then get the LocationName attribute from the object (db row) returned.
On line 17, we make sure to populate our email template file with the destination name. This gives the human friendly name of the location the user originally selected.

Test it out, and everything should work as planned.
Please ask questions if you get stuck, and happy Silverstriping 🙂

The post Assigning global attributes for select boxes in Silverstripe appeared first on Shattered Multimedia - Built with love.

]]>
https://www.shatteredmultimedia.com.au/assigning-global-attributes-select-boxes-silverstripe/feed/ 0
Debugging Doctrine SQL queries https://www.shatteredmultimedia.com.au/debugging-doctrine-sql-queries/ https://www.shatteredmultimedia.com.au/debugging-doctrine-sql-queries/#respond Wed, 28 Sep 2011 11:49:32 +0000 https://www.shatteredmultimedia.com.au/?p=205 I recently ran into issues especially with using the Doctrine ORM with my PHP development. My issue was that sometimes database insert and update queries would fail and I would have very limited debugging tools at my disposal. You can try printing out the query but usually if you are binding values to the field…

The post Debugging Doctrine SQL queries appeared first on Shattered Multimedia - Built with love.

]]>
I recently ran into issues especially with using the Doctrine ORM with my PHP development. My issue was that sometimes database insert and update queries would fail and I would have very limited debugging tools at my disposal. You can try printing out the query but usually if you are binding values to the field names, they are not displayed in the printed output.

So after trying many varieties of debugging techniques I came across this post helping explaining how to enable query logging within MySQL itself.

I will explain how to enable this within a windows environment.
I am using Zend Server CE 5.5 in this instance, which installs MySQL Server 5.1.

  1. Go to the MySQL Server folder (c:\Program Files\Zend\MySQL51 in this instance)
  2. edit the my.ini file
  3. Look for the [mysqld] title name and anywhere in that area enter the following:
    # The destination path for the log file for all MySQL transactions
    log="C:/Program Files/Zend/MySQL51/mysql.log
  4. Please change the path above to wherever you would like the log file to save to
  5. You will have to restart the MySQL service to enable the logging
  6. Click Start then Run and type in services.msc and press enter
  7. Find the MySQL_ZendServer51 or equivalent MySQL service and right click, restart
  8. After performing any MySQL interaction with the database, you should be able to open the log file described earlier and see every query that has been sent to the database engine.

With luck you will be able to view the exact query that has been failing and you can correct it.

I would highly recommend commenting out the logging feature once you have finished debugging as it will severely slow down your web server.

The post Debugging Doctrine SQL queries appeared first on Shattered Multimedia - Built with love.

]]>
https://www.shatteredmultimedia.com.au/debugging-doctrine-sql-queries/feed/ 0
Script automation from the command line (part 2 of 2) https://www.shatteredmultimedia.com.au/script-automation-command-line-part-2-2/ https://www.shatteredmultimedia.com.au/script-automation-command-line-part-2-2/#respond Wed, 06 Jul 2011 11:52:39 +0000 https://www.shatteredmultimedia.com.au/?p=207 We’re back to finish part 2 of our command line PHP script to run our cron jobs. We’ll start by creating a new file titled update_prices.php.  This filename should describe the overall goal you are intending to perform.   The first step is to include the database connector class, a methods class and our previously…

The post Script automation from the command line (part 2 of 2) appeared first on Shattered Multimedia - Built with love.

]]>
We’re back to finish part 2 of our command line PHP script to run our cron jobs.

We’ll start by creating a new file titled update_prices.php.  This filename should describe the overall goal you are intending to perform.

 

The first step is to include the database connector class, a methods class and our previously created cron_file.
Then we create our usageMessage which is called in our my_cron.php file (validateArgvArgumentsAndDieWithErrorMessageIfInvalid method) when there has been an input error as we need to give the users some guidance.

<?php
// Filename: update_prices.php
// The dirname() function has been used below because
require_once dirname(__FILE__) . '/class.DBCxn.php'; // Database connector file
require_once dirname(__FILE__) . '/class.integration.php'; // Our methods
require_once dirname(__FILE__) . '/class.my_cron.php'; // Our file created in step 1

// Global variables. 

$usageMessage = <<<STR
* Update or insert into the MySQL DB tables using data exported from a       *
* magical system from a far-away land.                                       *
*                                                                            *
* Usage: php update_prices.php [arguments]                                   *
*                                                                            *
*  [Arguments]                                                               *
*  -actual                                                                   *
*  Actually update the database.                                             *
*  -hypothetical                                                             *
*  Describe the updates that would be performed if -actual was used.         *
*  -verbose                                                                  *
*   Output detailed descriptions of each insert/delete/update action.        *
******************************************************************************

STR;

Once the include files are loaded, it’s time to start calling our validate arguments static method.
We know we will retrieve an array of 2 values back from this method, so we use PHP’s list function which will update the values of our variables.

We check if we’re to run in hypothetical mode and if so, we call the method from my_cron.php to inform the user that we will not be committing this data to the database.

We wrap everything in a try/catch so that we can get the error message. This could be updated to write the error message to a log file and email error to user.

// Globally executed code.
try {
  list($boolActuallyUpdateDatabase, $boolVerboseOutput) = (
    my_cron::validateArgvArgumentsAndDieWithErrorMessageIfInvalid($usageMessage)
  );
  my_cron::runInHypotheticalMode($boolActuallyUpdateDatabase);
} catch (Exception $e) {
  echo $e->getMessage(), "\n\n";
}

You put all your business logic in the class. integration.php file and reference the methods in your master file in this case update_prices.php.

We create an instance of our integration class so that we can access it’s methods.
Then we’re going to call one basic method; in this example and it will sit within the try/catch block above, at the bottom of the try section.

$products = new Integration();

$products->updatePrice($product_id, $prev_price, $upd_price, $boolVerboseOutput);

To finish it off, we have to create class.integration.php and add our updatePrice method to it. The updatePrice method takes four parameters.

The method checks if the new price is different to the previous price and if so will perform an SQL update. If the SQL updated successfully, we check if we need to print out debugging information.

class Integration {
    public $db;

    public function __construct() {
        $this->db = DBCxn::get();
    }

/**
   * Updates prices if required
   * @throws Exception
   * @param integer $product_id
   * @param float $prev_price
   * @param float $upd_price
   * @param boolean $verbose
   * @return string
   *
   */
  public function updatePrices($product_id, $prev_price, $upd_price, $verbose)
  {

    //Add specific business rules regarding price updates

    $sql = "[add sql update statement here]";

$result = $this->db->exec($sql);
    if (!$result) {
      $error = $this->db->errorInfo();
      throw new Exception('Adding updating prices: ' . $error[2]);
    } else {
      echo $verbose ? "\nUpdated Prices {$this->db->lastInsertId()} to to Product" : '';
      return $this->db->lastInsertId();
    }
  }
}

At the very bottom of our update_prices.php file still within the try section. We need to add another try/catch block.

We check whether hypothetical mode was requested and if so, we throw an exception which should take us to the outer catch section therefore rolling back the data.

If no exceptions, then we commit the database transactions and exit.

try {
    if (!$boolActuallyUpdateDatabase) {
      throw new exception("\nHypothetical Mode: No records committed");
    }
    $products->db->commit();
  } catch (Exception $e) {
    echo $e->getMessage(), "\n";
    $products->db->rollBack();
    echo "Error: Database has been rolled back.\n";
    die();
  }

So after all that there’s only one thing to do and that’s call the PHP script from the command line.

C:\Program Files\Zend\Apache2\htdocs\php update_prices.php actual verbose

Some Extras to help you get going:

<?php
// Filename: class.DBCxn.php
class DBCxn {
	// What DSN to connect to?
	public static $dsn = 'mysql:host=localhost;dbname=testdb'; // Change host and database name to suit
	public static $user = 'root'; // Change to your username
	public static $pass = 'root'; // Change to your password
	public static $driverOpts = null;

	// Internal variable to hold the connection
	private static $db;

	// No cloning or instantiating allowed
	final private function __construct() { }
	final private function __clone() { }

	public static function get() {
		// Connect if not already connected
		if (is_null(self::$db)) {
			self::$db = new PDO(self::$dsn, self::$user, self::$pass,
				self::$driverOpts);
		}
		// Return the connection
		return self::$db;
	}
}

That’s it for now, please comment if you have any questions.

Good luck

The post Script automation from the command line (part 2 of 2) appeared first on Shattered Multimedia - Built with love.

]]>
https://www.shatteredmultimedia.com.au/script-automation-command-line-part-2-2/feed/ 0
Script automation from the command line (part 1 of 2) https://www.shatteredmultimedia.com.au/script-automation-command-line-part-1-2/ https://www.shatteredmultimedia.com.au/script-automation-command-line-part-1-2/#respond Thu, 30 Jun 2011 11:53:38 +0000 https://www.shatteredmultimedia.com.au/?p=209 The best part about working with talented PHP Developers in the workplace is learning techniques to make us better developers. Last week I was required to create an automated PHP script to convert a data file of a legacy application into a newly created internal web app. After completing it, a workmate of mine; Tom…

The post Script automation from the command line (part 1 of 2) appeared first on Shattered Multimedia - Built with love.

]]>
The best part about working with talented PHP Developers in the workplace is learning techniques to make us better developers.

Last week I was required to create an automated PHP script to convert a data file of a legacy application into a newly created internal web app. After completing it, a workmate of mine; Tom McDonnell informed me of a script he had developed which accepted command line arguments and provided great feedback of the status of the running script.

With Tom’s permission to publish components of his source code, I would like to share these tips in this two part article.

The first step is creating a common cron class called class.my_cron.php
We do not want the class to be cloned or instantiated, we merely wish to use it’s methods freely.

In this example we will offer the user to add three possible parameters to the script via the command line. These are -actual, -hypothetical, -verbose.

Actual = Commit the changes
Hypothetical = Do not commit the changes, but still perform all the correct sql queries prior
Verbose = Display detailed descriptions of anything you believe is relevant for debugging purposes.

<?php
/**
 * This class is to define a common library file to include to help with common cron scripting tasks.
 */

class my_cron
{

  // No cloning or instantiating allowed.
  final private function __construct(){}
  final private function __clone(){}
}
?>

We require a function that will validate the parameters added to class.my_cron.php via the command line and then return an array of two values:

  1. Is the query going to commit or rollback at the end of the process?
  2.  What kind level of debugging do we wish to output in the command line?
We rely on the built-in global variable titled $argc which provides a count of arguments supplied. Note that there is always one argument provided by default, so the count should be what you expect +1.
If one argument is passed (really none), then we display an ASCII  header for fun and the usage message from our original PHP script which calls this method.
If two or three arguments are passed  (really one/two), then we continue through.
If anything else, we print an incorrect number of arguments error. Combined with  an ASCII  header for fun and the usage message from our original PHP script which calls this method.
Depending on the parameter results, we update the two boolean values to be returned by an array.
  public static function validateArgvArgumentsAndDieWithErrorMessageIfInvalid($usageMessage)
  {
    // Declare PHP Super globals
    // http://www.php.net/manual/en/reserved.variables.php
    global $argv; //Array of CLI arguments
    global $argc; //Count of CLI arguments

    $header = self::cronMsgHeader();

    switch ($argc) {
      case 1:
        echo "$header\n$usageMessage";
        exit(0);
      case 2: // Fall through.
      case 3:
        // Expected number of arguments.  Do nothing here, but proceed to next step.
        break;
      default:
        echo "Incorrect number of arguments.\n$header\n$usageMessage";
        exit(0);
    }

    $boolActuallyUpdateDatabase = null;
    $boolVerboseOutput = false;
    $errorString = 'Only one option of -hypothetical or -actual may be used.';
    $header = self::cronMsgHeader();
    for ($i = 1; $i < $argc; ++$i) {
      switch ($argv[$i]) {
        case '-hypothetical':
          if ($boolActuallyUpdateDatabase !== null) {
            echo "$errorString\n\n$header\n$usageMessage";
            exit(0);
          }
          echo "\n$header\n";
          $boolActuallyUpdateDatabase = false;
          break;

        case '-actual':
          if ($boolActuallyUpdateDatabase !== null) {
            echo "$errorString\n\n$header\n$usageMessage";
            exit(0);
          }
          echo "\n$header\n";
          $boolActuallyUpdateDatabase = true;
          break;

        case '-verbose':
          if ($argc < 3) {
            echo "$errorString\n\n$header\n$usageMessage";
            exit(0);
          }
          echo "\n$header\n";
          $boolVerboseOutput = true;
          break;

        default:
          echo "Incorrect argument '{$argv[1]}'.\n$usageMessage";
          exit(0);
      }
    }

    return array($boolActuallyUpdateDatabase, $boolVerboseOutput);
  }
Our message header that we created for fun to display at the top of the script
/**
 * Create a header usageMessage
 * @return string
 */
public static function cronMsgHeader()
{
  $usageMessage = <<<STRHEADR
******************************************************************************
*                                                                            *
*    MM     MM    YY     YY          CCCCCCC   RRRRR     OOOOOOO   NN    N   *
*    M M   M M     YY   YY           C         R    R    O     O   N N   N   *
*    M  M M  M       Y Y             C         R    R    O     O   N  N  N   *
*    M   M   M        Y              C         RRRRR     O     O   N  N  N   *
*    M       M        Y              C         R   R     O     O   N   N N   *
*    M       M        Y              C         R    R    O     O   N   N N   *
*    M       M        Y              CCCCCCC   R     R   OOOOOOO   N    NN   *
*    M       M        Y                                                      *
******************************************************************************
STRHEADR;

  return $usageMessage;
}
We’ll also add another disclaimer method that to display if the user has chosen to add the hypothetical parameter.
  /**
   * Echo's a disclaimer to the end user if running in hypothetical mode
   * @param $boolActuallyUpdateDatabase
   * @return void
   */
  public static function runInHypotheticalMode($boolActuallyUpdateDatabase) {
    if (!$boolActuallyUpdateDatabase) {
      echo "\nNote Regarding Hypothetical Mode\n";
      echo "--------------------------------\n";
      echo 'The script is running in hypothetical mode.  All database changes referred to';
      echo ' in the output below will be rolled back before the script completes.  The changes';
      echo " will also be rolled back should the script be interrupted part way through.\n";
    }
  }

So that’s all for now, in the next instalment I’ll show you how to implement these features into your code that will run the cron file via command line.

The entire cron class should now look like this.

<?php
/**
 * This class is to define a common library file to include to help with common cron scripting tasks.
 */

class my_cron
{

	// No cloning or instantiating allowed.
	final private function __construct()
	{
		//
	}

	final private function __clone()
	{
		//
	}

	/**
	 * Handles the command line arguments and makes sure they contain valid parameters
	 *
	 * @param $usageMessage
	 *
	 * @return array
	 */
	public static function validateArgvArgumentsAndDieWithErrorMessageIfInvalid($usageMessage)
	{
		// Declare PHP Super globals
		// http://www.php.net/manual/en/reserved.variables.php
		global $argv; //Array of CLI arguments
		global $argc; //Count of CLI arguments

		$header = self::cronMsgHeader();
		switch ($argc) {
			case 1:
				echo "$header\n$usageMessage";
				exit(0);
			case 2: // Fall through.
			case 3:
				// Expected number of arguments.  Do nothing here, but proceed to next step.
				break;
				    default:
				echo "Incorrect number of arguments.\n$header\n$usageMessage";
				exit(0);
		}

		$boolActuallyUpdateDatabase = null;
		$boolVerboseOutput = FALSE;
		$errorString = 'Only one option of -hypothetical or -actual may be used.';
		$header = self::cronMsgHeader();
		for ($i = 1; $i < $argc; ++$i) {
			switch ($argv[$i]) {
				case '-hypothetical':
					if ($boolActuallyUpdateDatabase !== null) {
						echo "$errorString\n\n$header\n$usageMessage";
						exit(0);
					}
					echo "\n$header\n";
					$boolActuallyUpdateDatabase = FALSE;
					break;
				case '-actual':
					if ($boolActuallyUpdateDatabase !== null) {
						echo "$errorString\n\n$header\n$usageMessage";
						exit(0);
					}
					echo "\n$header\n";
					$boolActuallyUpdateDatabase = TRUE;
					break;
				case '-verbose':
					if ($argc < 3) {
						echo "$errorString\n\n$header\n$usageMessage";
						exit(0);
					}
					echo "\n$header\n";
					$boolVerboseOutput = TRUE;
					break;
				default:
					echo "Incorrect argument '{$argv[1]}'.\n$usageMessage";
					exit(0);
			}
		}
		return array($boolActuallyUpdateDatabase, $boolVerboseOutput);
	}

	/**
	 * Create a header usageMessage
	 *
	 * @return string
	 */
	public static function cronMsgHeader()
	{
		$usageMessage = <<<STRHEADR
******************************************************************************
*                                                                            *
*    MM     MM    YY     YY          CCCCCCC   RRRRR     OOOOOOO   NN    N   *
*    M M   M M     YY   YY           C         R    R    O     O   N N   N   *
*    M  M M  M       Y Y             C         R    R    O     O   N  N  N   *
*    M   M   M        Y              C         RRRRR     O     O   N  N  N   *
*    M       M        Y              C         R   R     O     O   N   N N   *
*    M       M        Y              C         R    R    O     O   N   N N   *
*    M       M        Y              CCCCCCC   R     R   OOOOOOO   N    NN   *
*    M       M        Y                                                      *
******************************************************************************
STRHEADR;

		return $usageMessage;
	}

	/**
	 * Echo's a disclaimer to the end user if running in hypothetical mode
	 *
	 * @param $boolActuallyUpdateDatabase
	 * @return void
	 */
	public static function runInHypotheticalMode($boolActuallyUpdateDatabase) {
		if (!$boolActuallyUpdateDatabase) {
			echo "\nNote Regarding Hypothetical Mode\n";
			echo "--------------------------------\n";
			echo 'The script is running in hypothetical mode.  All database changes referred to';
			echo ' in the output below will be rolled back before the script completes.  The changes';
			echo " will also be rolled back should the script be interrupted part way through.\n";
		}
	}
}

The post Script automation from the command line (part 1 of 2) appeared first on Shattered Multimedia - Built with love.

]]>
https://www.shatteredmultimedia.com.au/script-automation-command-line-part-1-2/feed/ 0