private function getRepo()
 {
     $backend = new ArrayRepositoryBackend(new ModelConfig('Actor'), array(array('name' => 'Roger Moore'), array('name' => 'Arnold Schwarzenegger')));
     $repo = new Repository();
     $repo->registerBackend($backend);
     return $repo;
 }
 /**
  * Elke test_* met een schone database beginnen.
  */
 public function fillDatabase($db)
 {
     $db->import(dirname(__FILE__) . '/rebuild_test_database.' . $db->getAttribute(PDO::ATTR_DRIVER_NAME) . '.sql', $error);
     $repo = new Repository();
     Repository::$instances[__CLASS__] = $repo;
     $backend = new DatabaseRepositoryBackend(array($this->dbLink));
     foreach ($backend->configs as $config) {
         $config->class = SimpleRecord::class;
     }
     $repo->registerBackend($backend);
 }
Exemple #3
0
 public function testMultiRecordWrite()
 {
     $repo = Repository::instance();
     $post = $repo->createPost();
     $post->setMeta('gallery', ['__MULTIRECORD__', 'first', 'second']);
     $this->assertCount(2, $post->meta);
     $this->assertEquals(['__MULTIRECORD__', 'first', 'second'], $post->getMeta('gallery'));
 }
 /**
  * @return string
  */
 public function createSnapshot()
 {
     $repo = Repository::instance();
     $options = $repo->allOptions()->orderBy('key');
     $sql = $options->getQuery()->andWhere('option_name NOT LIKE "%_transient_%"');
     $options->setQuery($sql);
     return $options->select('value', 'key')->toArray();
 }
Exemple #5
0
 /**
  * Set or create the option.
  *
  * @param string       $key
  * @param string|array $value
  */
 public static function overwrite($key, $value)
 {
     $repo = Repository::instance();
     $option = $repo->oneOption(['key' => $key], true);
     if ($option === null) {
         $option = $repo->createOption(['key' => $key]);
     }
     $option->value = $value;
     $repo->saveOption($option);
 }
 public function generateContent()
 {
     Bridge::initialize();
     $repo = Repository::instance();
     $lastPosts = $repo->allTaxonomies()->orderByDescending('id')->take(25);
     //['AND', 'status !=' => 'auto-draft', 'type !=' => 'revision']
     $options = $lastPosts->select(function ($taxonomy) {
         return $taxonomy->id . ') ' . $taxonomy->taxonomy . ' - ' . $taxonomy->term->name;
     }, 'id')->toArray();
     \Sledgehammer\array_key_unshift($options, 'custom', 'Custom ID');
     $form = new Form(['method' => 'GET', 'fields' => ['taxonomy' => new Input(['name' => 'id', 'class' => 'form-control', 'type' => 'select', 'options' => $options, 'label' => 'Select post', 'value' => $lastPosts[0]->id]), 'id' => new Input(['name' => 'custom', 'class' => 'form-control', 'label' => 'Custom ID']), 'varname' => new Input(['name' => 'varname', 'class' => 'form-control', 'label' => 'Variable name', 'value' => '$taxonomy'])], 'actions' => [new Button('Export', ['class' => 'btn btn-primary'])]]);
     $values = $form->import();
     if ($form->isSent()) {
         if ($values['id'] !== '') {
             $form->setValue(['taxonomy' => $values['id']]);
             $id = $values['id'];
         } else {
             $id = $values['taxonomy'];
         }
         if ($id === 'custom') {
             return $form;
         }
         $taxonomy = $repo->getTaxonomy($id);
         $var = $values['varname'];
         $mustSave = false;
         $php = $var . ' = Sledgehammer\\Wordpress\\Migrate::taxonomy(' . var_export($taxonomy->taxonomy, true) . ', ' . var_export($taxonomy->term->name, true) . ', ' . var_export($taxonomy->term->slug, true) . ');';
         if (count($taxonomy->term->getMeta()) > 0) {
             $php .= $var . '->setMeta(' . var_export($taxonomy->term->getMeta(), true) . ");\n";
             $mustSave = true;
         }
         $php .= "\n\n";
         //            if ($taxonomy->posts->count() > 0) {
         //                $php .= "\$repo->resolveProperty(".$var.", 'posts', ['model' => 'Taxonomy']);\n";
         //                foreach ($taxonomy->posts as $post) {
         //                    $php .= $var."->posts[] = ";
         //                    $phpPost = "\$repo->onePost(['AND', 'type' => ".var_export($post->type, true).", 'slug' => ".var_export($post->slug, true)."])";
         //                    if ($post->order == '0') {
         //                        $php .= $phpPost.";\n";
         //                    } else {
         //                        $php .= "new Sledgehammer\Orm\Junction(".$phpPost.", ['order' => ".var_export($post->order, true)."]);\n";
         //                    }
         //                }
         //                $php .= $var."->count = ".$var."->posts->count();\n";
         //                $mustSave = true;
         //            }
         if ($mustSave) {
             $php .= "\$repo->saveTaxonomy(" . $var . ");\n";
         }
         return new Template('sledgehammer/wordpress/templates/export_post.php', ['form' => $form, 'php' => $php]);
     }
     return $form;
 }
Exemple #7
0
 /**
  * Open or create the post and patch the properties and meta data.
  *
  * @param array  $properties
  * @param array  $meta
  * @param string $guidPrefix Example: WP_HOME.'/?p=' for posts and WP_HOME.'/?page_id=' for pages.
  */
 public static function post($properties, $meta, $guidPrefix)
 {
     $repo = Repository::instance();
     $conditions = ['AND', 'type' => $properties['type'], 'slug' => $properties['slug']];
     $post = $repo->onePost($conditions, true);
     if ($post === null) {
         $post = $repo->createPost($properties);
     } else {
         \Sledgehammer\set_object_vars($post, $properties);
     }
     $post->setMeta($meta);
     $repo->savePost($post);
     if (!$post->guid && $guidPrefix !== false) {
         $post->guid = $guidPrefix . $post->id;
         $repo->savePost($post, ['ignore_relations' => true]);
     }
     return $post;
 }
 /**
  * Replace the placeholder with the referenced object.
  */
 private function __replacePlaceholder()
 {
     if (is_string($this->__placeholder) === false) {
         // Is the placeholder already replaced?
         // Multiple lookups are valid use-case.
         // The property (as placeholder) could be passed to another function as a value.
         return;
     }
     $parts = explode('/', $this->__placeholder);
     $repositoryId = array_shift($parts);
     $model = array_shift($parts);
     $property = implode('/', $parts);
     $self = PropertyPath::get($property, $this->__container);
     if ($self !== $this) {
         notice('This placeholder belongs to an other object', 'Did you clone the object?');
         $this->__placeholder = $self;
         return;
     }
     $repo = Repository::instance($repositoryId);
     $this->__placeholder = $repo->resolveProperty($this->__container, $property, array('model' => $model));
 }
Exemple #9
0
 /**
  * Set meta records.
  *
  * Usage:
  *   $post->setMeta(['my_key' => 'my_value']);
  * or
  *   $post->setMeta('my_key', 'my_value');
  *
  * @param $keyOrvalues
  * @param $value
  */
 public function setMeta($keyOrvalues, $value = null)
 {
     $repo = Repository::instance();
     if (is_array($keyOrvalues)) {
         foreach ($keyOrvalues as $key => $value) {
             $this->setMeta($key, $value);
         }
     } else {
         $key = $keyOrvalues;
         if (array_value($value, 0) === '__MULTIRECORD__') {
             $this->meta->remove(['key' => $key], true);
             array_shift($value);
             foreach ($value as $item) {
                 $this->meta[] = $repo->create(static::META_MODEL, ['key' => $key, 'value' => $item]);
             }
         } else {
             $found = false;
             foreach ($this->meta as $i => $old) {
                 if ($old->key === $key) {
                     if ($found) {
                         // was a multirecord
                         unset($this->meta[$i]);
                         // remove other values
                     } else {
                         $old->value = $value;
                         // Update existing value
                         $found = true;
                     }
                 }
             }
             if ($found === false) {
                 // Not found? add new key/value
                 $this->meta[] = $repo->create(static::META_MODEL, ['key' => $key, 'value' => $value]);
             }
         }
     }
 }
Exemple #10
0
 /**
  * Register closures that lazily configure the default repository.
  * 
  * @param Closure $closure A closure that received the repository as the first argument
  */
 public static function configureDefault($closure)
 {
     if (\Sledgehammer\is_closure($closure) === false) {
         throw new Exception('Closure expected as first argument');
     }
     if (static::$lazyConfigurations === false) {
         // default repository already initialized
         $closure(Repository::instance());
     } else {
         static::$lazyConfigurations[] = $closure;
     }
 }
Exemple #11
0
 /**
  * Get a Customer instance where all the properties are still placeholders
  * (Slow/Expensive operation, initializes a new Repository on every call).
  *
  * @param string $id
  *
  * @return stdClass
  */
 private function getDirtyCustomer($id)
 {
     $repo = new Repository();
     $repo->registerBackend(new DatabaseRepositoryBackend($this->dbLink));
     return $repo->getCustomer($id);
 }
 /**
  * Convert the raw data to an repository object.
  *
  * @param mixed $item
  *
  * @return object
  */
 private function convertItem($item)
 {
     if ($this->isConverted) {
         return $item;
     }
     $repo = Repository::instance($this->repository);
     return $repo->convert($this->model, $item, $this->options);
 }
Exemple #13
0
 public function generateContent()
 {
     Bridge::initialize();
     $repo = Repository::instance();
     $lastPosts = $repo->allPosts(['AND', 'status !=' => 'auto-draft', 'type !=' => 'revision'])->orderByDescending('id')->take(25);
     $options = $lastPosts->select(function ($post) {
         return $post->id . ') ' . $post->type . ' - ' . $post->slug;
     }, 'id')->toArray();
     \Sledgehammer\array_key_unshift($options, 'custom', 'Custom ID');
     $form = new Form(['method' => 'GET', 'fields' => ['post' => new Input(['name' => 'id', 'class' => 'form-control', 'type' => 'select', 'options' => $options, 'label' => 'Select post', 'value' => $lastPosts[0]->id]), 'id' => new Input(['name' => 'custom', 'class' => 'form-control', 'label' => 'Custom ID']), 'varname' => new Input(['name' => 'varname', 'class' => 'form-control', 'label' => 'Variable name', 'value' => '$post']), 'export_defaults' => new Input(['name' => 'export_defaults', 'type' => 'checkbox', 'label' => 'Force defaults (verbose export)'])], 'actions' => [new Button('Export', ['class' => 'btn btn-primary'])]]);
     $values = $form->import();
     if ($form->isSent()) {
         if ($values['id'] !== '') {
             $form->setValue(['post' => $values['id']]);
             $id = $values['id'];
         } else {
             $id = $values['post'];
         }
         if ($id === 'custom') {
             return $form;
         }
         $post = $repo->getPost($id);
         $var = $values['varname'];
         $defaults = $repo->createPost();
         $taxonomies = [];
         $php = '';
         foreach ($post->taxonomies as $i => $taxonomy) {
             if ($taxonomy->parent_id !== '0' || $taxonomy->description !== '' || $taxonomy->term->group !== '0' || $taxonomy->order !== '0') {
                 throw new Exception('@todo Implement taxonomy feature');
             }
             if (count($taxonomy->term->getMeta()) === 0) {
                 $taxonomies[] = 'Migrate::taxonomy(' . var_export($taxonomy->taxonomy, true) . ', ' . var_export($taxonomy->term->name, true) . ', ' . var_export($taxonomy->term->slug, true) . ')';
             } else {
                 $php .= '$taxonomy' . $i . ' = Migrate::taxonomy(' . var_export($taxonomy->taxonomy, true) . ', ' . var_export($taxonomy->term->name, true) . ', ' . var_export($taxonomy->term->slug, true) . ");\n";
                 $php .= '$taxonomy' . $i . '->setMeta(' . var_export($taxonomy->term->getMeta(), true) . ");\n";
                 $taxonomies[] = '$taxonomy' . $i;
             }
         }
         $php .= $var . " = Sledgehammer\\Wordpress\\Migrate::post([\n";
         $fields = ['type', 'title', 'slug', 'excerpt', 'status', 'content', 'comment_status', 'ping_status', 'password', 'to_ping', 'pinged', 'content_filtered', 'menu_order', 'mimetype', 'comment_count', 'parent_id', 'author', 'date', 'date_gmt', 'modified', 'modified_gmt'];
         if ($post->type === 'attachment') {
             $fields[] = 'guid';
         }
         foreach ($fields as $property) {
             if ($values['export_defaults'] === false && $defaults->{$property} === $post->{$property}) {
                 continue;
                 // skip default values
             }
             if ($property === 'author') {
                 $value = "\$repo->oneUser(['login' => " . var_export($post->author->login, true) . '])';
             } elseif ($property === 'guid') {
                 $guid = var_export($post->guid, true);
                 $value = str_replace("'" . WP_HOME, 'WP_HOME.\'', $guid);
             } elseif ($property === 'parent_id') {
                 if ($post->parent_id === '0') {
                     $value = "'0'";
                 } else {
                     $parent = $repo->getPost($post->parent_id);
                     $value = "\$repo->onePost(['AND', 'type' => " . var_export($parent->type, true) . ", 'slug' => " . var_export($parent->slug, true) . '])->id';
                 }
             } else {
                 $value = var_export($post->{$property}, true);
             }
             $php .= "    '" . $property . "' => " . $value . ",\n";
         }
         if ($taxonomies) {
             $php .= "    'taxonomies' => [\n        " . implode(",\n        ", $taxonomies) . "\n    ],\n";
         }
         $php .= "],[\n";
         $meta = $post->getMeta();
         foreach ($meta as $key => $value) {
             if (in_array($key, ['_edit_lock', '_edit_last'])) {
                 continue;
             }
             if ($key === '_thumbnail_id') {
                 $attachment = $repo->getPost($value);
                 $guid = var_export($attachment->guid, true);
                 $value = "\$repo->onePost(['AND','type' => 'attachment', 'guid' => " . str_replace("'" . WP_HOME, 'WP_HOME.\'', $guid) . '])';
             } else {
                 $value = var_export($value, true);
             }
             $php .= "    '" . $key . "' => " . $value . ",\n";
         }
         $php .= '], ';
         if ($post->type === 'attachment') {
             $php .= 'false';
         } else {
             $guid = var_export($post->guid, true);
             $guid = str_replace("'" . WP_HOME, 'WP_HOME.\'', $guid);
             $php .= str_replace('=' . $post->id . "'", "='", $guid);
         }
         $php .= ");\n";
         return new Template('sledgehammer/wordpress/templates/export_post.php', ['form' => $form, 'php' => $php]);
     }
     return $form;
 }
Exemple #14
0
 /**
  * Inspect the worpress database and.
  */
 public static function initialize()
 {
     static $initialized = false;
     if ($initialized) {
         return;
     }
     $initialized = true;
     if (function_exists('the_post') === false) {
         throw new Exception('Wordpress is not yet initialized');
     }
     // Lazy database connection
     Connection::$instances['wordpress'] = function () {
         if (defined('DB_USER') === false) {
             throw new Exception('No database configured');
         }
         $connection = new Connection('mysql://' . DB_USER . ':' . DB_PASSWORD . '@' . DB_HOST . '/' . DB_NAME);
         if (empty(Logger::$instances['Database[wordpress]'])) {
             $index = array_search($connection->logger, Logger::$instances);
             unset(Logger::$instances[$index]);
             Logger::$instances['Database[wordpress]'] = $connection->logger;
         }
         return $connection;
     };
     if (empty(Connection::$instances['default'])) {
         Connection::$instances['default'] = 'wordpress';
     }
     // Sledgehammer ORM configuration
     Repository::configureDefault(function ($repo) {
         $repo->registerBackend(new WordpressRepositoryBackend());
     });
     if (defined('Sledgehammer\\WEBPATH') === false) {
         $url = new Url(WP_HOME);
         $path = $url->path === '/' ? '/' : $url->path . '/';
         define('Sledgehammer\\WEBPATH', $path);
         define('Sledgehammer\\WEBROOT', $path);
     }
     define('WEBPATH', \Sledgehammer\WEBPATH);
     if (WP_DEBUG || !empty($_GET[\Sledgehammer\DEBUG_VAR])) {
         add_action('admin_enqueue_scripts', function () {
             wp_enqueue_style('sh-debug', '/../core/css/debug.css');
         });
         add_action('admin_footer', [self::class, 'statusbar']);
         add_action('wp_footer', [self::class, 'statusbar']);
         add_action('send_headers', function () {
             if (DebugR::isEnabled()) {
                 ob_start();
                 echo $_SERVER['REQUEST_METHOD'] . ' ' . $_SERVER['REQUEST_URI'];
                 \Sledgehammer\statusbar();
                 DebugR::send('sledgehammer-statusbar', ob_get_clean(), true);
             }
         }, PHP_INT_MAX);
         add_filter('template_include', function ($template) {
             if (empty(ErrorHandler::$instances['default'])) {
                 ErrorHandler::enable();
             }
             if (defined('Sledgehammer\\GENERATED') === false) {
                 define('Sledgehammer\\GENERATED', microtime(true));
             }
             return $template;
         }, PHP_INT_MAX);
     }
 }
 public function current()
 {
     $repo = Repository::instance($this->repository);
     return $repo->convert($this->model, $this->iterator->current());
 }
 public function test_many_to_many_relation_with_mapped_fields()
 {
     $repo = new Repository();
     $backend = new DatabaseRepositoryBackend(array($this->dbLink));
     $repo->registerBackend($backend);
     $backend->configs['Customer']->hasMany['ratings']['fields']['rating'] = 'groupRating';
     $bob = $repo->getCustomer(1);
     // Reading
     $this->assertCount(1, $bob->ratings);
     $groupRating = $bob->ratings[0];
     $this->assertEquals('Hacker', $groupRating->title);
     // Access normal property
     $this->assertEquals('5', $groupRating->groupRating);
     // Access additional property
     $this->assertInstanceOf(Junction::class, $groupRating);
     // Updating
     $this->assertCount(1, $bob->ratings);
     $groupRating->groupRating = '4';
     // Using a string because an int would change detection when saving the $group
     $repo->saveCustomer($bob);
     $this->assertLastQuery("UPDATE ratings SET rating = '4' WHERE customer_id = 1 AND group_id = 1");
     $group = $repo->getGroup($groupRating->id);
     $this->assertCount(2, $group->ratings->toArray());
     $this->assertLastQuery('SELECT * FROM customers WHERE id IN (1, 2)');
     // The many to many for the group was't yet loaded.
     $this->assertEquals('Bob Fanger', $group->ratings[0]->name, 'Sanity check');
     $this->assertEquals(4, $group->ratings[0]->rating);
     $this->assertRelativeQueryCount(6, 'Sanity check');
     $repo->saveGroup($group);
     $this->assertRelativeQueryCount(6, '0 changes, 0 queries.');
     $group->ratings[0]->rating = 10;
     $repo->saveGroup($group);
     $this->assertQuery('UPDATE ratings SET rating = 10 WHERE customer_id = 1 AND group_id = 1');
     $this->assertRelativeQueryCount(7);
     $this->assertEquals(10, $bob->ratings[0]->groupRating, 'The many-to-many relation should be updated on both ends');
     // Deleting
     unset($group->ratings[0]);
     $repo->saveGroup($group);
     $this->assertLastQuery('DELETE FROM ratings WHERE customer_id = 1 AND group_id = 1');
     $this->assertRelativeQueryCount(8);
     $this->assertCount(0, $bob->ratings, 'The many-to-many relation should be updated on both ends');
 }
Exemple #17
0
 /**
  * Detect the repository.
  *
  * Checks the $options array.
  * Checks if the $_repository property is defined in the subclass.
  * Or uses the default repository.
  *
  * @param array $options
  *
  * @return Repository
  */
 protected static function _getRepostory($options = [])
 {
     if (isset($options['repository'])) {
         // Use the repository given in the parameters
         return Repository::instance($options['repository']);
     }
     $class = get_called_class();
     $properties = get_class_vars($class);
     if ($properties['_repository'] !== null) {
         // Use the repository defined in de subclass
         return Repository::instance($properties['_repository']);
     }
     return Repository::instance();
     // Use the default repository
 }