PHP code example of dynamic / silverstripe-salsify

1. Go to this page and download the library: Download dynamic/silverstripe-salsify library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dynamic / silverstripe-salsify example snippets


namespace {
    use SilverStripe\CMS\Model\SiteTree;

    class Page extends SiteTree
    {

        /**
         * @var array
         */
        private static $many_many = [
            'Features' => Feature::class,
        ];

        private static $many_many_extraFields = [
            'Features' => [
                'SortOrder'=> 'Int',
            ],
        ];
    }
}



namespace {
    use \Page;
    use SilverStripe\ORM\DataObject;

    /**
     * Class Feature
     *
     * @property string Name
     */
    class Feature extends DataObject
    {
        /**
         * @var string
         */
        private static $table_name = 'Feature';

        /**
         * @var array
         */
        private static $db = [
            'Name' => 'Varchar(100)',
        ];

        /**
         * @var array
         */
        private static $belongs_many_many = [
            'Pages' => Page::class,
        ];

        /**
         * @var array
         */
        private static $indexes = [
            'Name' => [
                'type' => 'unique',
                'columns' => ['Name'],
            ],
        ];
    }
}



namespace {

    use SilverStripe\Core\Extension;

    /**
     * Class SalsifyExtension
     */
    class SalsifyExtension extends Extension
    {
        /**
         * @param string|\SilverStripe\ORM\DataObject $class
         * @param string $dbField
         * @param array $config
         * @param array $data
         *
         * @return array
         */
        public function featureModifier($class, $dbField, $config, $data)
        {
            $features = [];
            foreach ($this->owner->config()->get('featureFields') as $featuredField) {
                if (array_key_exists($featuredField, $data) && $this->is_true($data[$featuredField])) {
                    $features[] = [
                        'FeatureName' => $featuredField,
                    ];
                }
            }
            $data['Features'] = $features;
            return $data;
        }

        /**
         * @param $val
         * @param bool $return_null
         * @return bool|mixed|null
         *
         * FROM https://www.php.net/manual/en/function.boolval.php#116547
         */
        private function is_true($val, $return_null = false)
        {
            $boolval = (bool)$val;

            if (is_string($val)) {
                $boolval = filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
            }

            if ($boolval === null && !$return_null) {
                return false;
            }

            return $boolval;
        }
    }
}


namespace {
    use SilverStripe\Core\Extension;
    use JsonMachine\JsonMachine;

    /**
     * Class ExampleFeatureExtension
     */
    class ExampleFeatureExtension extends Extension
    {
        /**
         * Gets all the attributes that are in a field group and sets them in the mapper's config
         * @param $file
         * @param bool $multiple
         */
        public function onBeforeMap($file, $multiple)
        {
            $attributes = [];
            $attributeStream = JsonMachine::fromFile($file, '/1/attributes');
            foreach ($this->owner->yieldSingle($attributeStream) as $attribute) {
                if (array_key_exists('salsify:attribute_group', $attribute)) {
                    if ($attribute['salsify:attribute_group'] == 'Product Features') {
                        $attributes[] = $attribute['salsify:id'];
                    }
                }
            }

            $this->owner->config()->set('featureFields', $attributes);
        }
    }
}


namespace {
    use SilverStripe\Core\Extension;
    use JsonMachine\JsonMachine;
    use Dynamic\Salsify\Task\ImportTask;
    use Dynamic\Salsify\Model\Mapper;

    /**
     * Class ExampleCleanUpExtension
     */
    class ExampleCleanUpExtension extends Extension
    {
        /**
         * @param $file
         * @param bool $multiple
         */
        public function onAfterMap($file, $multiple)
        {
            // don't clean up on a single product import
            if ($multiple == Mapper::$SINGLE) {
                return;
            }

            $productStream = JsonMachine::fromFile($file, '/4/products');
            $productCodes = [];

            foreach ($this->owner->yieldKeyVal($productStream) as $name => $data) {
                $productCodes[] = $data['salsify:id'];
            }

            $invalidProducts = Product::get()->exclude([
                'SalsifyID' => $productCodes,
            ]);

            $count = 0;
            foreach ($this->owner->yieldSingle($invalidProducts) as $invalidProduct) {
                /** @var Product $invalidProduct */
                $invalidProduct->doArchive();
                $count++;
            }
            ImportTask::output("Archived {$count} products");
        }
    }
}


namespace {
    use SilverStripe\Core\Extension;
    use SilverStripe\ORM\DataObject;
    use SilverStripe\RedirectedURLs\Model\RedirectedURL;
    use Dynamic\Salsify\Task\ImportTask;

    /**
     * Class ExampleRedirectExtension
     */
    class ExampleRedirectExtension extends Extension
    {
        /**
         * This will create a redirect if a page's parent changes
         * @param DataObject $object
         */
        public function beforeObjectWrite($object)
        {
            if (!$object instanceof \Page) {
                return;
            }

            if (!$object->isChanged()) {
                return;
            }

            $changed = $object->getChangedFields(false, DataObject::CHANGE_VALUE);

            if (!array_key_exists('ParentID', $changed) && !array_key_exists('URLSegment', $changed)) {
                return;
            }

            $oldParent = $object->ParentID;
            $oldSegment = $object->URLSegment;
            if (array_key_exists('ParentID', $changed)) {
                $parent = $changed['ParentID'];
                $oldParent = $parent['before'];
            }

            if (array_key_exists('URLSegment', $changed)) {
                $segment = $changed['URLSegment'];
                $oldSegment = $segment['before'];
            }

            $this->createRedirect($oldParent, $oldSegment, $object->ID);
        }

        /**
         * @param \Page|int $oldParent
         * @param string $oldSegment
         * @param int $objectID
         */
        private function createRedirect($oldParent, $oldSegment, $objectID)
        {
            if (is_int($oldParent)) {
                $oldParent = \Page::get()->byID($oldParent);
            }

            $redirect = RedirectedURL::create();
            $redirect->RedirectCode = 301;
            $redirect->FromBase = preg_replace('/\?.*/', '', $oldParent->Link($oldSegment));
            $redirect->LinkToID = $objectID;
            $redirect->write();
            ImportTask::output("Created redirect from {$redirect->FromBase} to {$redirect->LinkTo()->Link()}");
        }
    }
}


namespace {
    use SilverStripe\Core\Extension;
    use SilverStripe\Versioned\Versioned;

    /**
     * Class ExamplePublishExtension
     */
    class ExamplePublishExtension extends Extension
    {
        /**
         * This will publish all new mapped objects and mapped objects that are already published.
         * @param DataObject|Versioned $object
         * @param bool $wasWritten
         * @param bool $wasPublished
         */
        public function afterObjectWrite($object, $wasWritten, $wasPublished)
        {
            if ($object->hasExtension(Versioned::class)) {
                if (!$wasWritten || $wasPublished) {
                    $object->publishRecursive();
                }
            }
        }
    }
}